blob: 323675a583d29ca62dcf79ce40e9b54050561cfe [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
Anastasia Stulova2b461202016-11-14 15:34:01 +0000454 // Fifth argument is always passed as a pointer to clk_event_t.
455 if (!Arg4->isNullPointerConstant(S.Context,
456 Expr::NPC_ValueDependentIsNotNull) &&
457 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000458 S.Diag(TheCall->getArg(4)->getLocStart(),
459 diag::err_opencl_enqueue_kernel_expected_type)
460 << S.Context.getPointerType(S.Context.OCLClkEventTy);
461 return true;
462 }
463
Anastasia Stulova2b461202016-11-14 15:34:01 +0000464 // Sixth argument is always passed as a pointer to clk_event_t.
465 if (!Arg5->isNullPointerConstant(S.Context,
466 Expr::NPC_ValueDependentIsNotNull) &&
467 !(Arg5->getType()->isPointerType() &&
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000468 Arg5->getType()->getPointeeType()->isClkEventT())) {
469 S.Diag(TheCall->getArg(5)->getLocStart(),
470 diag::err_opencl_enqueue_kernel_expected_type)
471 << S.Context.getPointerType(S.Context.OCLClkEventTy);
472 return true;
473 }
474
475 if (NumArgs == 7)
476 return false;
477
478 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
479 }
480
481 // None of the specific case has been detected, give generic error
482 S.Diag(TheCall->getLocStart(),
483 diag::err_opencl_enqueue_kernel_incorrect_args);
484 return true;
485}
486
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000487/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000488static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000489 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000490}
491
492/// Returns true if pipe element type is different from the pointer.
493static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
494 const Expr *Arg0 = Call->getArg(0);
495 // First argument type should always be pipe.
496 if (!Arg0->getType()->isPipeType()) {
497 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000498 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000499 return true;
500 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000501 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000502 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
503 // Validates the access qualifier is compatible with the call.
504 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
505 // read_only and write_only, and assumed to be read_only if no qualifier is
506 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000507 switch (Call->getDirectCallee()->getBuiltinID()) {
508 case Builtin::BIread_pipe:
509 case Builtin::BIreserve_read_pipe:
510 case Builtin::BIcommit_read_pipe:
511 case Builtin::BIwork_group_reserve_read_pipe:
512 case Builtin::BIsub_group_reserve_read_pipe:
513 case Builtin::BIwork_group_commit_read_pipe:
514 case Builtin::BIsub_group_commit_read_pipe:
515 if (!(!AccessQual || AccessQual->isReadOnly())) {
516 S.Diag(Arg0->getLocStart(),
517 diag::err_opencl_builtin_pipe_invalid_access_modifier)
518 << "read_only" << Arg0->getSourceRange();
519 return true;
520 }
521 break;
522 case Builtin::BIwrite_pipe:
523 case Builtin::BIreserve_write_pipe:
524 case Builtin::BIcommit_write_pipe:
525 case Builtin::BIwork_group_reserve_write_pipe:
526 case Builtin::BIsub_group_reserve_write_pipe:
527 case Builtin::BIwork_group_commit_write_pipe:
528 case Builtin::BIsub_group_commit_write_pipe:
529 if (!(AccessQual && AccessQual->isWriteOnly())) {
530 S.Diag(Arg0->getLocStart(),
531 diag::err_opencl_builtin_pipe_invalid_access_modifier)
532 << "write_only" << Arg0->getSourceRange();
533 return true;
534 }
535 break;
536 default:
537 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000538 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000539 return false;
540}
541
542/// Returns true if pipe element type is different from the pointer.
543static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
544 const Expr *Arg0 = Call->getArg(0);
545 const Expr *ArgIdx = Call->getArg(Idx);
546 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000547 const QualType EltTy = PipeTy->getElementType();
548 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000549 // The Idx argument should be a pointer and the type of the pointer and
550 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000551 if (!ArgTy ||
552 !S.Context.hasSameType(
553 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000554 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000555 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000556 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000557 return true;
558 }
559 return false;
560}
561
562// \brief Performs semantic analysis for the read/write_pipe call.
563// \param S Reference to the semantic analyzer.
564// \param Call A pointer to the builtin call.
565// \return True if a semantic error has been found, false otherwise.
566static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000567 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
568 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000569 switch (Call->getNumArgs()) {
570 case 2: {
571 if (checkOpenCLPipeArg(S, Call))
572 return true;
573 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000574 // read/write_pipe(pipe T, T*).
575 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000576 if (checkOpenCLPipePacketType(S, Call, 1))
577 return true;
578 } break;
579
580 case 4: {
581 if (checkOpenCLPipeArg(S, Call))
582 return true;
583 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000584 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
585 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000586 if (!Call->getArg(1)->getType()->isReserveIDT()) {
587 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000588 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000589 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000590 return true;
591 }
592
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000593 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000594 const Expr *Arg2 = Call->getArg(2);
595 if (!Arg2->getType()->isIntegerType() &&
596 !Arg2->getType()->isUnsignedIntegerType()) {
597 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000598 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000599 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000600 return true;
601 }
602
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000603 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000604 if (checkOpenCLPipePacketType(S, Call, 3))
605 return true;
606 } break;
607 default:
608 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000609 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000610 return true;
611 }
612
613 return false;
614}
615
616// \brief Performs a semantic analysis on the {work_group_/sub_group_
617// /_}reserve_{read/write}_pipe
618// \param S Reference to the semantic analyzer.
619// \param Call The call to the builtin function to be analyzed.
620// \return True if a semantic error was found, false otherwise.
621static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
622 if (checkArgCount(S, Call, 2))
623 return true;
624
625 if (checkOpenCLPipeArg(S, Call))
626 return true;
627
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000628 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000629 if (!Call->getArg(1)->getType()->isIntegerType() &&
630 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
631 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000632 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000633 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000634 return true;
635 }
636
637 return false;
638}
639
640// \brief Performs a semantic analysis on {work_group_/sub_group_
641// /_}commit_{read/write}_pipe
642// \param S Reference to the semantic analyzer.
643// \param Call The call to the builtin function to be analyzed.
644// \return True if a semantic error was found, false otherwise.
645static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
646 if (checkArgCount(S, Call, 2))
647 return true;
648
649 if (checkOpenCLPipeArg(S, Call))
650 return true;
651
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000652 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000653 if (!Call->getArg(1)->getType()->isReserveIDT()) {
654 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000655 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000656 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000657 return true;
658 }
659
660 return false;
661}
662
663// \brief Performs a semantic analysis on the call to built-in Pipe
664// Query Functions.
665// \param S Reference to the semantic analyzer.
666// \param Call The call to the builtin function to be analyzed.
667// \return True if a semantic error was found, false otherwise.
668static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
669 if (checkArgCount(S, Call, 1))
670 return true;
671
672 if (!Call->getArg(0)->getType()->isPipeType()) {
673 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000674 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000675 return true;
676 }
677
678 return false;
679}
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +0000680// \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
Yaxun Liuf7449a12016-05-20 19:54:38 +0000681// \brief Performs semantic analysis for the to_global/local/private call.
682// \param S Reference to the semantic analyzer.
683// \param BuiltinID ID of the builtin function.
684// \param Call A pointer to the builtin call.
685// \return True if a semantic error has been found, false otherwise.
686static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
687 CallExpr *Call) {
Yaxun Liuf7449a12016-05-20 19:54:38 +0000688 if (Call->getNumArgs() != 1) {
689 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
690 << Call->getDirectCallee() << Call->getSourceRange();
691 return true;
692 }
693
694 auto RT = Call->getArg(0)->getType();
695 if (!RT->isPointerType() || RT->getPointeeType()
696 .getAddressSpace() == LangAS::opencl_constant) {
697 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
698 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
699 return true;
700 }
701
702 RT = RT->getPointeeType();
703 auto Qual = RT.getQualifiers();
704 switch (BuiltinID) {
705 case Builtin::BIto_global:
706 Qual.setAddressSpace(LangAS::opencl_global);
707 break;
708 case Builtin::BIto_local:
709 Qual.setAddressSpace(LangAS::opencl_local);
710 break;
711 default:
712 Qual.removeAddressSpace();
713 }
714 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
715 RT.getUnqualifiedType(), Qual)));
716
717 return false;
718}
719
John McCalldadc5752010-08-24 06:29:42 +0000720ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000721Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
722 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000723 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000724
Chris Lattner3be167f2010-10-01 23:23:24 +0000725 // Find out if any arguments are required to be integer constant expressions.
726 unsigned ICEArguments = 0;
727 ASTContext::GetBuiltinTypeError Error;
728 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
729 if (Error != ASTContext::GE_None)
730 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
731
732 // If any arguments are required to be ICE's, check and diagnose.
733 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
734 // Skip arguments not required to be ICE's.
735 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
736
737 llvm::APSInt Result;
738 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
739 return true;
740 ICEArguments &= ~(1 << ArgNo);
741 }
742
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000743 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000744 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000745 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000746 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000747 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000748 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000749 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000750 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000751 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000752 if (SemaBuiltinVAStart(TheCall))
753 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000754 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000755 case Builtin::BI__va_start: {
756 switch (Context.getTargetInfo().getTriple().getArch()) {
757 case llvm::Triple::arm:
758 case llvm::Triple::thumb:
759 if (SemaBuiltinVAStartARM(TheCall))
760 return ExprError();
761 break;
762 default:
763 if (SemaBuiltinVAStart(TheCall))
764 return ExprError();
765 break;
766 }
767 break;
768 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000769 case Builtin::BI__builtin_isgreater:
770 case Builtin::BI__builtin_isgreaterequal:
771 case Builtin::BI__builtin_isless:
772 case Builtin::BI__builtin_islessequal:
773 case Builtin::BI__builtin_islessgreater:
774 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000775 if (SemaBuiltinUnorderedCompare(TheCall))
776 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000777 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000778 case Builtin::BI__builtin_fpclassify:
779 if (SemaBuiltinFPClassification(TheCall, 6))
780 return ExprError();
781 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000782 case Builtin::BI__builtin_isfinite:
783 case Builtin::BI__builtin_isinf:
784 case Builtin::BI__builtin_isinf_sign:
785 case Builtin::BI__builtin_isnan:
786 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000787 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000788 return ExprError();
789 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000790 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000791 return SemaBuiltinShuffleVector(TheCall);
792 // TheCall will be freed by the smart pointer here, but that's fine, since
793 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000794 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000795 if (SemaBuiltinPrefetch(TheCall))
796 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000797 break;
David Majnemer51169932016-10-31 05:37:48 +0000798 case Builtin::BI__builtin_alloca_with_align:
799 if (SemaBuiltinAllocaWithAlign(TheCall))
800 return ExprError();
801 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000802 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000803 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000804 if (SemaBuiltinAssume(TheCall))
805 return ExprError();
806 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000807 case Builtin::BI__builtin_assume_aligned:
808 if (SemaBuiltinAssumeAligned(TheCall))
809 return ExprError();
810 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000811 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000812 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000813 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000814 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000815 case Builtin::BI__builtin_longjmp:
816 if (SemaBuiltinLongjmp(TheCall))
817 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000818 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000819 case Builtin::BI__builtin_setjmp:
820 if (SemaBuiltinSetjmp(TheCall))
821 return ExprError();
822 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000823 case Builtin::BI_setjmp:
824 case Builtin::BI_setjmpex:
825 if (checkArgCount(*this, TheCall, 1))
826 return true;
827 break;
John McCallbebede42011-02-26 05:39:39 +0000828
829 case Builtin::BI__builtin_classify_type:
830 if (checkArgCount(*this, TheCall, 1)) return true;
831 TheCall->setType(Context.IntTy);
832 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000833 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000834 if (checkArgCount(*this, TheCall, 1)) return true;
835 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000836 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000837 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000838 case Builtin::BI__sync_fetch_and_add_1:
839 case Builtin::BI__sync_fetch_and_add_2:
840 case Builtin::BI__sync_fetch_and_add_4:
841 case Builtin::BI__sync_fetch_and_add_8:
842 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000843 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000844 case Builtin::BI__sync_fetch_and_sub_1:
845 case Builtin::BI__sync_fetch_and_sub_2:
846 case Builtin::BI__sync_fetch_and_sub_4:
847 case Builtin::BI__sync_fetch_and_sub_8:
848 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000849 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000850 case Builtin::BI__sync_fetch_and_or_1:
851 case Builtin::BI__sync_fetch_and_or_2:
852 case Builtin::BI__sync_fetch_and_or_4:
853 case Builtin::BI__sync_fetch_and_or_8:
854 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000855 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000856 case Builtin::BI__sync_fetch_and_and_1:
857 case Builtin::BI__sync_fetch_and_and_2:
858 case Builtin::BI__sync_fetch_and_and_4:
859 case Builtin::BI__sync_fetch_and_and_8:
860 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000861 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000862 case Builtin::BI__sync_fetch_and_xor_1:
863 case Builtin::BI__sync_fetch_and_xor_2:
864 case Builtin::BI__sync_fetch_and_xor_4:
865 case Builtin::BI__sync_fetch_and_xor_8:
866 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000867 case Builtin::BI__sync_fetch_and_nand:
868 case Builtin::BI__sync_fetch_and_nand_1:
869 case Builtin::BI__sync_fetch_and_nand_2:
870 case Builtin::BI__sync_fetch_and_nand_4:
871 case Builtin::BI__sync_fetch_and_nand_8:
872 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000873 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000874 case Builtin::BI__sync_add_and_fetch_1:
875 case Builtin::BI__sync_add_and_fetch_2:
876 case Builtin::BI__sync_add_and_fetch_4:
877 case Builtin::BI__sync_add_and_fetch_8:
878 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000879 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000880 case Builtin::BI__sync_sub_and_fetch_1:
881 case Builtin::BI__sync_sub_and_fetch_2:
882 case Builtin::BI__sync_sub_and_fetch_4:
883 case Builtin::BI__sync_sub_and_fetch_8:
884 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000885 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000886 case Builtin::BI__sync_and_and_fetch_1:
887 case Builtin::BI__sync_and_and_fetch_2:
888 case Builtin::BI__sync_and_and_fetch_4:
889 case Builtin::BI__sync_and_and_fetch_8:
890 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000891 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000892 case Builtin::BI__sync_or_and_fetch_1:
893 case Builtin::BI__sync_or_and_fetch_2:
894 case Builtin::BI__sync_or_and_fetch_4:
895 case Builtin::BI__sync_or_and_fetch_8:
896 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000897 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000898 case Builtin::BI__sync_xor_and_fetch_1:
899 case Builtin::BI__sync_xor_and_fetch_2:
900 case Builtin::BI__sync_xor_and_fetch_4:
901 case Builtin::BI__sync_xor_and_fetch_8:
902 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000903 case Builtin::BI__sync_nand_and_fetch:
904 case Builtin::BI__sync_nand_and_fetch_1:
905 case Builtin::BI__sync_nand_and_fetch_2:
906 case Builtin::BI__sync_nand_and_fetch_4:
907 case Builtin::BI__sync_nand_and_fetch_8:
908 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000909 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000910 case Builtin::BI__sync_val_compare_and_swap_1:
911 case Builtin::BI__sync_val_compare_and_swap_2:
912 case Builtin::BI__sync_val_compare_and_swap_4:
913 case Builtin::BI__sync_val_compare_and_swap_8:
914 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000915 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000916 case Builtin::BI__sync_bool_compare_and_swap_1:
917 case Builtin::BI__sync_bool_compare_and_swap_2:
918 case Builtin::BI__sync_bool_compare_and_swap_4:
919 case Builtin::BI__sync_bool_compare_and_swap_8:
920 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000921 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000922 case Builtin::BI__sync_lock_test_and_set_1:
923 case Builtin::BI__sync_lock_test_and_set_2:
924 case Builtin::BI__sync_lock_test_and_set_4:
925 case Builtin::BI__sync_lock_test_and_set_8:
926 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000927 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000928 case Builtin::BI__sync_lock_release_1:
929 case Builtin::BI__sync_lock_release_2:
930 case Builtin::BI__sync_lock_release_4:
931 case Builtin::BI__sync_lock_release_8:
932 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000933 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000934 case Builtin::BI__sync_swap_1:
935 case Builtin::BI__sync_swap_2:
936 case Builtin::BI__sync_swap_4:
937 case Builtin::BI__sync_swap_8:
938 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000939 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000940 case Builtin::BI__builtin_nontemporal_load:
941 case Builtin::BI__builtin_nontemporal_store:
942 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000943#define BUILTIN(ID, TYPE, ATTRS)
944#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
945 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000946 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000947#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000948 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000949 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000950 return ExprError();
951 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000952 case Builtin::BI__builtin_addressof:
953 if (SemaBuiltinAddressof(*this, TheCall))
954 return ExprError();
955 break;
John McCall03107a42015-10-29 20:48:01 +0000956 case Builtin::BI__builtin_add_overflow:
957 case Builtin::BI__builtin_sub_overflow:
958 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +0000959 if (SemaBuiltinOverflow(*this, TheCall))
960 return ExprError();
961 break;
Richard Smith760520b2014-06-03 23:27:44 +0000962 case Builtin::BI__builtin_operator_new:
963 case Builtin::BI__builtin_operator_delete:
964 if (!getLangOpts().CPlusPlus) {
965 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
966 << (BuiltinID == Builtin::BI__builtin_operator_new
967 ? "__builtin_operator_new"
968 : "__builtin_operator_delete")
969 << "C++";
970 return ExprError();
971 }
972 // CodeGen assumes it can find the global new and delete to call,
973 // so ensure that they are declared.
974 DeclareGlobalNewDelete();
975 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000976
977 // check secure string manipulation functions where overflows
978 // are detectable at compile time
979 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000980 case Builtin::BI__builtin___memmove_chk:
981 case Builtin::BI__builtin___memset_chk:
982 case Builtin::BI__builtin___strlcat_chk:
983 case Builtin::BI__builtin___strlcpy_chk:
984 case Builtin::BI__builtin___strncat_chk:
985 case Builtin::BI__builtin___strncpy_chk:
986 case Builtin::BI__builtin___stpncpy_chk:
987 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
988 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000989 case Builtin::BI__builtin___memccpy_chk:
990 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
991 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000992 case Builtin::BI__builtin___snprintf_chk:
993 case Builtin::BI__builtin___vsnprintf_chk:
994 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
995 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000996 case Builtin::BI__builtin_call_with_static_chain:
997 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
998 return ExprError();
999 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001000 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001001 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001002 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1003 diag::err_seh___except_block))
1004 return ExprError();
1005 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001006 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001007 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001008 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1009 diag::err_seh___except_filter))
1010 return ExprError();
1011 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001012 case Builtin::BI__GetExceptionInfo:
1013 if (checkArgCount(*this, TheCall, 1))
1014 return ExprError();
1015
1016 if (CheckCXXThrowOperand(
1017 TheCall->getLocStart(),
1018 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1019 TheCall))
1020 return ExprError();
1021
1022 TheCall->setType(Context.VoidPtrTy);
1023 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001024 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001025 case Builtin::BIread_pipe:
1026 case Builtin::BIwrite_pipe:
1027 // Since those two functions are declared with var args, we need a semantic
1028 // check for the argument.
1029 if (SemaBuiltinRWPipe(*this, TheCall))
1030 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001031 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001032 break;
1033 case Builtin::BIreserve_read_pipe:
1034 case Builtin::BIreserve_write_pipe:
1035 case Builtin::BIwork_group_reserve_read_pipe:
1036 case Builtin::BIwork_group_reserve_write_pipe:
1037 case Builtin::BIsub_group_reserve_read_pipe:
1038 case Builtin::BIsub_group_reserve_write_pipe:
1039 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1040 return ExprError();
1041 // Since return type of reserve_read/write_pipe built-in function is
1042 // reserve_id_t, which is not defined in the builtin def file , we used int
1043 // as return type and need to override the return type of these functions.
1044 TheCall->setType(Context.OCLReserveIDTy);
1045 break;
1046 case Builtin::BIcommit_read_pipe:
1047 case Builtin::BIcommit_write_pipe:
1048 case Builtin::BIwork_group_commit_read_pipe:
1049 case Builtin::BIwork_group_commit_write_pipe:
1050 case Builtin::BIsub_group_commit_read_pipe:
1051 case Builtin::BIsub_group_commit_write_pipe:
1052 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1053 return ExprError();
1054 break;
1055 case Builtin::BIget_pipe_num_packets:
1056 case Builtin::BIget_pipe_max_packets:
1057 if (SemaBuiltinPipePackets(*this, TheCall))
1058 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001059 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001060 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001061 case Builtin::BIto_global:
1062 case Builtin::BIto_local:
1063 case Builtin::BIto_private:
1064 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1065 return ExprError();
1066 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001067 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1068 case Builtin::BIenqueue_kernel:
1069 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1070 return ExprError();
1071 break;
1072 case Builtin::BIget_kernel_work_group_size:
1073 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1074 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1075 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001076 break;
1077 case Builtin::BI__builtin_os_log_format:
1078 case Builtin::BI__builtin_os_log_format_buffer_size:
1079 if (SemaBuiltinOSLogFormat(TheCall)) {
1080 return ExprError();
1081 }
1082 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001083 }
Richard Smith760520b2014-06-03 23:27:44 +00001084
Nate Begeman4904e322010-06-08 02:47:44 +00001085 // Since the target specific builtins for each arch overlap, only check those
1086 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001087 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001088 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001089 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001090 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001091 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001092 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001093 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1094 return ExprError();
1095 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001096 case llvm::Triple::aarch64:
1097 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001098 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001099 return ExprError();
1100 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001101 case llvm::Triple::mips:
1102 case llvm::Triple::mipsel:
1103 case llvm::Triple::mips64:
1104 case llvm::Triple::mips64el:
1105 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1106 return ExprError();
1107 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001108 case llvm::Triple::systemz:
1109 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1110 return ExprError();
1111 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001112 case llvm::Triple::x86:
1113 case llvm::Triple::x86_64:
1114 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1115 return ExprError();
1116 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001117 case llvm::Triple::ppc:
1118 case llvm::Triple::ppc64:
1119 case llvm::Triple::ppc64le:
1120 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1121 return ExprError();
1122 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001123 default:
1124 break;
1125 }
1126 }
1127
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001128 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001129}
1130
Nate Begeman91e1fea2010-06-14 05:21:25 +00001131// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001132static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001133 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001134 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001135 switch (Type.getEltType()) {
1136 case NeonTypeFlags::Int8:
1137 case NeonTypeFlags::Poly8:
1138 return shift ? 7 : (8 << IsQuad) - 1;
1139 case NeonTypeFlags::Int16:
1140 case NeonTypeFlags::Poly16:
1141 return shift ? 15 : (4 << IsQuad) - 1;
1142 case NeonTypeFlags::Int32:
1143 return shift ? 31 : (2 << IsQuad) - 1;
1144 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001145 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001146 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001147 case NeonTypeFlags::Poly128:
1148 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001149 case NeonTypeFlags::Float16:
1150 assert(!shift && "cannot shift float types!");
1151 return (4 << IsQuad) - 1;
1152 case NeonTypeFlags::Float32:
1153 assert(!shift && "cannot shift float types!");
1154 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001155 case NeonTypeFlags::Float64:
1156 assert(!shift && "cannot shift float types!");
1157 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001158 }
David Blaikie8a40f702012-01-17 06:56:22 +00001159 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001160}
1161
Bob Wilsone4d77232011-11-08 05:04:11 +00001162/// getNeonEltType - Return the QualType corresponding to the elements of
1163/// the vector type specified by the NeonTypeFlags. This is used to check
1164/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001165static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001166 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001167 switch (Flags.getEltType()) {
1168 case NeonTypeFlags::Int8:
1169 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1170 case NeonTypeFlags::Int16:
1171 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1172 case NeonTypeFlags::Int32:
1173 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1174 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001175 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001176 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1177 else
1178 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1179 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001180 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001181 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001182 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001183 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001184 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001185 if (IsInt64Long)
1186 return Context.UnsignedLongTy;
1187 else
1188 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001189 case NeonTypeFlags::Poly128:
1190 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001191 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001192 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001193 case NeonTypeFlags::Float32:
1194 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001195 case NeonTypeFlags::Float64:
1196 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001197 }
David Blaikie8a40f702012-01-17 06:56:22 +00001198 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001199}
1200
Tim Northover12670412014-02-19 10:37:05 +00001201bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001202 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001203 uint64_t mask = 0;
1204 unsigned TV = 0;
1205 int PtrArgNum = -1;
1206 bool HasConstPtr = false;
1207 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001208#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001209#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001210#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001211 }
1212
1213 // For NEON intrinsics which are overloaded on vector element type, validate
1214 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001215 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001216 if (mask) {
1217 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1218 return true;
1219
1220 TV = Result.getLimitedValue(64);
1221 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1222 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001223 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001224 }
1225
1226 if (PtrArgNum >= 0) {
1227 // Check that pointer arguments have the specified type.
1228 Expr *Arg = TheCall->getArg(PtrArgNum);
1229 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1230 Arg = ICE->getSubExpr();
1231 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1232 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001233
Tim Northovera2ee4332014-03-29 15:09:45 +00001234 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +00001235 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +00001236 bool IsInt64Long =
1237 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1238 QualType EltTy =
1239 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001240 if (HasConstPtr)
1241 EltTy = EltTy.withConst();
1242 QualType LHSTy = Context.getPointerType(EltTy);
1243 AssignConvertType ConvTy;
1244 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1245 if (RHS.isInvalid())
1246 return true;
1247 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1248 RHS.get(), AA_Assigning))
1249 return true;
1250 }
1251
1252 // For NEON intrinsics which take an immediate value as part of the
1253 // instruction, range check them here.
1254 unsigned i = 0, l = 0, u = 0;
1255 switch (BuiltinID) {
1256 default:
1257 return false;
Tim Northover12670412014-02-19 10:37:05 +00001258#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001259#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001260#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001261 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001262
Richard Sandiford28940af2014-04-16 08:47:51 +00001263 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001264}
1265
Tim Northovera2ee4332014-03-29 15:09:45 +00001266bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1267 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001268 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001269 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001270 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001271 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001272 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001273 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1274 BuiltinID == AArch64::BI__builtin_arm_strex ||
1275 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001276 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001277 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001278 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1279 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1280 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001281
1282 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1283
1284 // Ensure that we have the proper number of arguments.
1285 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1286 return true;
1287
1288 // Inspect the pointer argument of the atomic builtin. This should always be
1289 // a pointer type, whose element is an integral scalar or pointer type.
1290 // Because it is a pointer type, we don't have to worry about any implicit
1291 // casts here.
1292 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1293 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1294 if (PointerArgRes.isInvalid())
1295 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001296 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001297
1298 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1299 if (!pointerType) {
1300 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1301 << PointerArg->getType() << PointerArg->getSourceRange();
1302 return true;
1303 }
1304
1305 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1306 // task is to insert the appropriate casts into the AST. First work out just
1307 // what the appropriate type is.
1308 QualType ValType = pointerType->getPointeeType();
1309 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1310 if (IsLdrex)
1311 AddrType.addConst();
1312
1313 // Issue a warning if the cast is dodgy.
1314 CastKind CastNeeded = CK_NoOp;
1315 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1316 CastNeeded = CK_BitCast;
1317 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1318 << PointerArg->getType()
1319 << Context.getPointerType(AddrType)
1320 << AA_Passing << PointerArg->getSourceRange();
1321 }
1322
1323 // Finally, do the cast and replace the argument with the corrected version.
1324 AddrType = Context.getPointerType(AddrType);
1325 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1326 if (PointerArgRes.isInvalid())
1327 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001328 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001329
1330 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1331
1332 // In general, we allow ints, floats and pointers to be loaded and stored.
1333 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1334 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1335 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1336 << PointerArg->getType() << PointerArg->getSourceRange();
1337 return true;
1338 }
1339
1340 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001341 if (Context.getTypeSize(ValType) > MaxWidth) {
1342 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001343 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1344 << PointerArg->getType() << PointerArg->getSourceRange();
1345 return true;
1346 }
1347
1348 switch (ValType.getObjCLifetime()) {
1349 case Qualifiers::OCL_None:
1350 case Qualifiers::OCL_ExplicitNone:
1351 // okay
1352 break;
1353
1354 case Qualifiers::OCL_Weak:
1355 case Qualifiers::OCL_Strong:
1356 case Qualifiers::OCL_Autoreleasing:
1357 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1358 << ValType << PointerArg->getSourceRange();
1359 return true;
1360 }
1361
Tim Northover6aacd492013-07-16 09:47:53 +00001362 if (IsLdrex) {
1363 TheCall->setType(ValType);
1364 return false;
1365 }
1366
1367 // Initialize the argument to be stored.
1368 ExprResult ValArg = TheCall->getArg(0);
1369 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1370 Context, ValType, /*consume*/ false);
1371 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1372 if (ValArg.isInvalid())
1373 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001374 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001375
1376 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1377 // but the custom checker bypasses all default analysis.
1378 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001379 return false;
1380}
1381
Nate Begeman4904e322010-06-08 02:47:44 +00001382bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +00001383 llvm::APSInt Result;
1384
Tim Northover6aacd492013-07-16 09:47:53 +00001385 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001386 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1387 BuiltinID == ARM::BI__builtin_arm_strex ||
1388 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001389 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001390 }
1391
Yi Kong26d104a2014-08-13 19:18:14 +00001392 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1393 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1394 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1395 }
1396
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001397 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1398 BuiltinID == ARM::BI__builtin_arm_wsr64)
1399 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1400
1401 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1402 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1403 BuiltinID == ARM::BI__builtin_arm_wsr ||
1404 BuiltinID == ARM::BI__builtin_arm_wsrp)
1405 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1406
Tim Northover12670412014-02-19 10:37:05 +00001407 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1408 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001409
Yi Kong4efadfb2014-07-03 16:01:25 +00001410 // For intrinsics which take an immediate value as part of the instruction,
1411 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001412 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001413 switch (BuiltinID) {
1414 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001415 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1416 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001417 case ARM::BI__builtin_arm_vcvtr_f:
1418 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001419 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001420 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001421 case ARM::BI__builtin_arm_isb:
1422 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001423 }
Nate Begemand773fe62010-06-13 04:47:52 +00001424
Nate Begemanf568b072010-08-03 21:32:34 +00001425 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001426 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001427}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001428
Tim Northover573cbee2014-05-24 12:52:07 +00001429bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001430 CallExpr *TheCall) {
1431 llvm::APSInt Result;
1432
Tim Northover573cbee2014-05-24 12:52:07 +00001433 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001434 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1435 BuiltinID == AArch64::BI__builtin_arm_strex ||
1436 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001437 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1438 }
1439
Yi Konga5548432014-08-13 19:18:20 +00001440 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1441 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1442 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1443 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1444 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1445 }
1446
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001447 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1448 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001449 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001450
1451 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1452 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1453 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1454 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1455 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1456
Tim Northovera2ee4332014-03-29 15:09:45 +00001457 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1458 return true;
1459
Yi Kong19a29ac2014-07-17 10:52:06 +00001460 // For intrinsics which take an immediate value as part of the instruction,
1461 // range check them here.
1462 unsigned i = 0, l = 0, u = 0;
1463 switch (BuiltinID) {
1464 default: return false;
1465 case AArch64::BI__builtin_arm_dmb:
1466 case AArch64::BI__builtin_arm_dsb:
1467 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1468 }
1469
Yi Kong19a29ac2014-07-17 10:52:06 +00001470 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001471}
1472
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001473// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1474// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1475// ordering for DSP is unspecified. MSA is ordered by the data format used
1476// by the underlying instruction i.e., df/m, df/n and then by size.
1477//
1478// FIXME: The size tests here should instead be tablegen'd along with the
1479// definitions from include/clang/Basic/BuiltinsMips.def.
1480// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1481// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001482bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001483 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001484 switch (BuiltinID) {
1485 default: return false;
1486 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1487 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001488 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1489 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1490 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1491 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1492 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001493 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1494 // df/m field.
1495 // These intrinsics take an unsigned 3 bit immediate.
1496 case Mips::BI__builtin_msa_bclri_b:
1497 case Mips::BI__builtin_msa_bnegi_b:
1498 case Mips::BI__builtin_msa_bseti_b:
1499 case Mips::BI__builtin_msa_sat_s_b:
1500 case Mips::BI__builtin_msa_sat_u_b:
1501 case Mips::BI__builtin_msa_slli_b:
1502 case Mips::BI__builtin_msa_srai_b:
1503 case Mips::BI__builtin_msa_srari_b:
1504 case Mips::BI__builtin_msa_srli_b:
1505 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1506 case Mips::BI__builtin_msa_binsli_b:
1507 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1508 // These intrinsics take an unsigned 4 bit immediate.
1509 case Mips::BI__builtin_msa_bclri_h:
1510 case Mips::BI__builtin_msa_bnegi_h:
1511 case Mips::BI__builtin_msa_bseti_h:
1512 case Mips::BI__builtin_msa_sat_s_h:
1513 case Mips::BI__builtin_msa_sat_u_h:
1514 case Mips::BI__builtin_msa_slli_h:
1515 case Mips::BI__builtin_msa_srai_h:
1516 case Mips::BI__builtin_msa_srari_h:
1517 case Mips::BI__builtin_msa_srli_h:
1518 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1519 case Mips::BI__builtin_msa_binsli_h:
1520 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1521 // These intrinsics take an unsigned 5 bit immedate.
1522 // The first block of intrinsics actually have an unsigned 5 bit field,
1523 // not a df/n field.
1524 case Mips::BI__builtin_msa_clei_u_b:
1525 case Mips::BI__builtin_msa_clei_u_h:
1526 case Mips::BI__builtin_msa_clei_u_w:
1527 case Mips::BI__builtin_msa_clei_u_d:
1528 case Mips::BI__builtin_msa_clti_u_b:
1529 case Mips::BI__builtin_msa_clti_u_h:
1530 case Mips::BI__builtin_msa_clti_u_w:
1531 case Mips::BI__builtin_msa_clti_u_d:
1532 case Mips::BI__builtin_msa_maxi_u_b:
1533 case Mips::BI__builtin_msa_maxi_u_h:
1534 case Mips::BI__builtin_msa_maxi_u_w:
1535 case Mips::BI__builtin_msa_maxi_u_d:
1536 case Mips::BI__builtin_msa_mini_u_b:
1537 case Mips::BI__builtin_msa_mini_u_h:
1538 case Mips::BI__builtin_msa_mini_u_w:
1539 case Mips::BI__builtin_msa_mini_u_d:
1540 case Mips::BI__builtin_msa_addvi_b:
1541 case Mips::BI__builtin_msa_addvi_h:
1542 case Mips::BI__builtin_msa_addvi_w:
1543 case Mips::BI__builtin_msa_addvi_d:
1544 case Mips::BI__builtin_msa_bclri_w:
1545 case Mips::BI__builtin_msa_bnegi_w:
1546 case Mips::BI__builtin_msa_bseti_w:
1547 case Mips::BI__builtin_msa_sat_s_w:
1548 case Mips::BI__builtin_msa_sat_u_w:
1549 case Mips::BI__builtin_msa_slli_w:
1550 case Mips::BI__builtin_msa_srai_w:
1551 case Mips::BI__builtin_msa_srari_w:
1552 case Mips::BI__builtin_msa_srli_w:
1553 case Mips::BI__builtin_msa_srlri_w:
1554 case Mips::BI__builtin_msa_subvi_b:
1555 case Mips::BI__builtin_msa_subvi_h:
1556 case Mips::BI__builtin_msa_subvi_w:
1557 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1558 case Mips::BI__builtin_msa_binsli_w:
1559 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1560 // These intrinsics take an unsigned 6 bit immediate.
1561 case Mips::BI__builtin_msa_bclri_d:
1562 case Mips::BI__builtin_msa_bnegi_d:
1563 case Mips::BI__builtin_msa_bseti_d:
1564 case Mips::BI__builtin_msa_sat_s_d:
1565 case Mips::BI__builtin_msa_sat_u_d:
1566 case Mips::BI__builtin_msa_slli_d:
1567 case Mips::BI__builtin_msa_srai_d:
1568 case Mips::BI__builtin_msa_srari_d:
1569 case Mips::BI__builtin_msa_srli_d:
1570 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1571 case Mips::BI__builtin_msa_binsli_d:
1572 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1573 // These intrinsics take a signed 5 bit immediate.
1574 case Mips::BI__builtin_msa_ceqi_b:
1575 case Mips::BI__builtin_msa_ceqi_h:
1576 case Mips::BI__builtin_msa_ceqi_w:
1577 case Mips::BI__builtin_msa_ceqi_d:
1578 case Mips::BI__builtin_msa_clti_s_b:
1579 case Mips::BI__builtin_msa_clti_s_h:
1580 case Mips::BI__builtin_msa_clti_s_w:
1581 case Mips::BI__builtin_msa_clti_s_d:
1582 case Mips::BI__builtin_msa_clei_s_b:
1583 case Mips::BI__builtin_msa_clei_s_h:
1584 case Mips::BI__builtin_msa_clei_s_w:
1585 case Mips::BI__builtin_msa_clei_s_d:
1586 case Mips::BI__builtin_msa_maxi_s_b:
1587 case Mips::BI__builtin_msa_maxi_s_h:
1588 case Mips::BI__builtin_msa_maxi_s_w:
1589 case Mips::BI__builtin_msa_maxi_s_d:
1590 case Mips::BI__builtin_msa_mini_s_b:
1591 case Mips::BI__builtin_msa_mini_s_h:
1592 case Mips::BI__builtin_msa_mini_s_w:
1593 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1594 // These intrinsics take an unsigned 8 bit immediate.
1595 case Mips::BI__builtin_msa_andi_b:
1596 case Mips::BI__builtin_msa_nori_b:
1597 case Mips::BI__builtin_msa_ori_b:
1598 case Mips::BI__builtin_msa_shf_b:
1599 case Mips::BI__builtin_msa_shf_h:
1600 case Mips::BI__builtin_msa_shf_w:
1601 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1602 case Mips::BI__builtin_msa_bseli_b:
1603 case Mips::BI__builtin_msa_bmnzi_b:
1604 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1605 // df/n format
1606 // These intrinsics take an unsigned 4 bit immediate.
1607 case Mips::BI__builtin_msa_copy_s_b:
1608 case Mips::BI__builtin_msa_copy_u_b:
1609 case Mips::BI__builtin_msa_insve_b:
1610 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1611 case Mips::BI__builtin_msa_sld_b:
1612 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1613 // These intrinsics take an unsigned 3 bit immediate.
1614 case Mips::BI__builtin_msa_copy_s_h:
1615 case Mips::BI__builtin_msa_copy_u_h:
1616 case Mips::BI__builtin_msa_insve_h:
1617 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1618 case Mips::BI__builtin_msa_sld_h:
1619 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1620 // These intrinsics take an unsigned 2 bit immediate.
1621 case Mips::BI__builtin_msa_copy_s_w:
1622 case Mips::BI__builtin_msa_copy_u_w:
1623 case Mips::BI__builtin_msa_insve_w:
1624 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1625 case Mips::BI__builtin_msa_sld_w:
1626 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1627 // These intrinsics take an unsigned 1 bit immediate.
1628 case Mips::BI__builtin_msa_copy_s_d:
1629 case Mips::BI__builtin_msa_copy_u_d:
1630 case Mips::BI__builtin_msa_insve_d:
1631 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1632 case Mips::BI__builtin_msa_sld_d:
1633 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1634 // Memory offsets and immediate loads.
1635 // These intrinsics take a signed 10 bit immediate.
1636 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 127; break;
1637 case Mips::BI__builtin_msa_ldi_h:
1638 case Mips::BI__builtin_msa_ldi_w:
1639 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1640 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1641 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1642 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1643 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1644 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1645 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1646 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1647 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001648 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001649
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001650 if (!m)
1651 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1652
1653 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1654 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001655}
1656
Kit Bartone50adcb2015-03-30 19:40:59 +00001657bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1658 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001659 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1660 BuiltinID == PPC::BI__builtin_divdeu ||
1661 BuiltinID == PPC::BI__builtin_bpermd;
1662 bool IsTarget64Bit = Context.getTargetInfo()
1663 .getTypeWidth(Context
1664 .getTargetInfo()
1665 .getIntPtrType()) == 64;
1666 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1667 BuiltinID == PPC::BI__builtin_divweu ||
1668 BuiltinID == PPC::BI__builtin_divde ||
1669 BuiltinID == PPC::BI__builtin_divdeu;
1670
1671 if (Is64BitBltin && !IsTarget64Bit)
1672 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1673 << TheCall->getSourceRange();
1674
1675 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1676 (BuiltinID == PPC::BI__builtin_bpermd &&
1677 !Context.getTargetInfo().hasFeature("bpermd")))
1678 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1679 << TheCall->getSourceRange();
1680
Kit Bartone50adcb2015-03-30 19:40:59 +00001681 switch (BuiltinID) {
1682 default: return false;
1683 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1684 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1685 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1686 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1687 case PPC::BI__builtin_tbegin:
1688 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1689 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1690 case PPC::BI__builtin_tabortwc:
1691 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1692 case PPC::BI__builtin_tabortwci:
1693 case PPC::BI__builtin_tabortdci:
1694 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1695 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1696 }
1697 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1698}
1699
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001700bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1701 CallExpr *TheCall) {
1702 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1703 Expr *Arg = TheCall->getArg(0);
1704 llvm::APSInt AbortCode(32);
1705 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1706 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1707 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1708 << Arg->getSourceRange();
1709 }
1710
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001711 // For intrinsics which take an immediate value as part of the instruction,
1712 // range check them here.
1713 unsigned i = 0, l = 0, u = 0;
1714 switch (BuiltinID) {
1715 default: return false;
1716 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1717 case SystemZ::BI__builtin_s390_verimb:
1718 case SystemZ::BI__builtin_s390_verimh:
1719 case SystemZ::BI__builtin_s390_verimf:
1720 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1721 case SystemZ::BI__builtin_s390_vfaeb:
1722 case SystemZ::BI__builtin_s390_vfaeh:
1723 case SystemZ::BI__builtin_s390_vfaef:
1724 case SystemZ::BI__builtin_s390_vfaebs:
1725 case SystemZ::BI__builtin_s390_vfaehs:
1726 case SystemZ::BI__builtin_s390_vfaefs:
1727 case SystemZ::BI__builtin_s390_vfaezb:
1728 case SystemZ::BI__builtin_s390_vfaezh:
1729 case SystemZ::BI__builtin_s390_vfaezf:
1730 case SystemZ::BI__builtin_s390_vfaezbs:
1731 case SystemZ::BI__builtin_s390_vfaezhs:
1732 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1733 case SystemZ::BI__builtin_s390_vfidb:
1734 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1735 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1736 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1737 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1738 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1739 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1740 case SystemZ::BI__builtin_s390_vstrcb:
1741 case SystemZ::BI__builtin_s390_vstrch:
1742 case SystemZ::BI__builtin_s390_vstrcf:
1743 case SystemZ::BI__builtin_s390_vstrczb:
1744 case SystemZ::BI__builtin_s390_vstrczh:
1745 case SystemZ::BI__builtin_s390_vstrczf:
1746 case SystemZ::BI__builtin_s390_vstrcbs:
1747 case SystemZ::BI__builtin_s390_vstrchs:
1748 case SystemZ::BI__builtin_s390_vstrcfs:
1749 case SystemZ::BI__builtin_s390_vstrczbs:
1750 case SystemZ::BI__builtin_s390_vstrczhs:
1751 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1752 }
1753 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001754}
1755
Craig Topper5ba2c502015-11-07 08:08:31 +00001756/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1757/// This checks that the target supports __builtin_cpu_supports and
1758/// that the string argument is constant and valid.
1759static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1760 Expr *Arg = TheCall->getArg(0);
1761
1762 // Check if the argument is a string literal.
1763 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1764 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1765 << Arg->getSourceRange();
1766
1767 // Check the contents of the string.
1768 StringRef Feature =
1769 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1770 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1771 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1772 << Arg->getSourceRange();
1773 return false;
1774}
1775
Craig Toppera7e253e2016-09-23 04:48:31 +00001776// Check if the rounding mode is legal.
1777bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1778 // Indicates if this instruction has rounding control or just SAE.
1779 bool HasRC = false;
1780
1781 unsigned ArgNum = 0;
1782 switch (BuiltinID) {
1783 default:
1784 return false;
1785 case X86::BI__builtin_ia32_vcvttsd2si32:
1786 case X86::BI__builtin_ia32_vcvttsd2si64:
1787 case X86::BI__builtin_ia32_vcvttsd2usi32:
1788 case X86::BI__builtin_ia32_vcvttsd2usi64:
1789 case X86::BI__builtin_ia32_vcvttss2si32:
1790 case X86::BI__builtin_ia32_vcvttss2si64:
1791 case X86::BI__builtin_ia32_vcvttss2usi32:
1792 case X86::BI__builtin_ia32_vcvttss2usi64:
1793 ArgNum = 1;
1794 break;
1795 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1796 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1797 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1798 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1799 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1800 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1801 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1802 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1803 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1804 case X86::BI__builtin_ia32_exp2pd_mask:
1805 case X86::BI__builtin_ia32_exp2ps_mask:
1806 case X86::BI__builtin_ia32_getexppd512_mask:
1807 case X86::BI__builtin_ia32_getexpps512_mask:
1808 case X86::BI__builtin_ia32_rcp28pd_mask:
1809 case X86::BI__builtin_ia32_rcp28ps_mask:
1810 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1811 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1812 case X86::BI__builtin_ia32_vcomisd:
1813 case X86::BI__builtin_ia32_vcomiss:
1814 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1815 ArgNum = 3;
1816 break;
1817 case X86::BI__builtin_ia32_cmppd512_mask:
1818 case X86::BI__builtin_ia32_cmpps512_mask:
1819 case X86::BI__builtin_ia32_cmpsd_mask:
1820 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001821 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001822 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1823 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001824 case X86::BI__builtin_ia32_maxpd512_mask:
1825 case X86::BI__builtin_ia32_maxps512_mask:
1826 case X86::BI__builtin_ia32_maxsd_round_mask:
1827 case X86::BI__builtin_ia32_maxss_round_mask:
1828 case X86::BI__builtin_ia32_minpd512_mask:
1829 case X86::BI__builtin_ia32_minps512_mask:
1830 case X86::BI__builtin_ia32_minsd_round_mask:
1831 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001832 case X86::BI__builtin_ia32_rcp28sd_round_mask:
1833 case X86::BI__builtin_ia32_rcp28ss_round_mask:
1834 case X86::BI__builtin_ia32_reducepd512_mask:
1835 case X86::BI__builtin_ia32_reduceps512_mask:
1836 case X86::BI__builtin_ia32_rndscalepd_mask:
1837 case X86::BI__builtin_ia32_rndscaleps_mask:
1838 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1839 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1840 ArgNum = 4;
1841 break;
1842 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001843 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001844 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001845 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001846 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001847 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001848 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001849 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001850 case X86::BI__builtin_ia32_rangepd512_mask:
1851 case X86::BI__builtin_ia32_rangeps512_mask:
1852 case X86::BI__builtin_ia32_rangesd128_round_mask:
1853 case X86::BI__builtin_ia32_rangess128_round_mask:
1854 case X86::BI__builtin_ia32_reducesd_mask:
1855 case X86::BI__builtin_ia32_reducess_mask:
1856 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1857 case X86::BI__builtin_ia32_rndscaless_round_mask:
1858 ArgNum = 5;
1859 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00001860 case X86::BI__builtin_ia32_vcvtsd2si64:
1861 case X86::BI__builtin_ia32_vcvtsd2si32:
1862 case X86::BI__builtin_ia32_vcvtsd2usi32:
1863 case X86::BI__builtin_ia32_vcvtsd2usi64:
1864 case X86::BI__builtin_ia32_vcvtss2si32:
1865 case X86::BI__builtin_ia32_vcvtss2si64:
1866 case X86::BI__builtin_ia32_vcvtss2usi32:
1867 case X86::BI__builtin_ia32_vcvtss2usi64:
1868 ArgNum = 1;
1869 HasRC = true;
1870 break;
Craig Topper8e066312016-11-07 07:01:09 +00001871 case X86::BI__builtin_ia32_cvtsi2sd64:
1872 case X86::BI__builtin_ia32_cvtsi2ss32:
1873 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00001874 case X86::BI__builtin_ia32_cvtusi2sd64:
1875 case X86::BI__builtin_ia32_cvtusi2ss32:
1876 case X86::BI__builtin_ia32_cvtusi2ss64:
1877 ArgNum = 2;
1878 HasRC = true;
1879 break;
1880 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1881 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1882 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1883 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1884 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1885 case X86::BI__builtin_ia32_cvtps2qq512_mask:
1886 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1887 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1888 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1889 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1890 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001891 case X86::BI__builtin_ia32_sqrtpd512_mask:
1892 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001893 ArgNum = 3;
1894 HasRC = true;
1895 break;
1896 case X86::BI__builtin_ia32_addpd512_mask:
1897 case X86::BI__builtin_ia32_addps512_mask:
1898 case X86::BI__builtin_ia32_divpd512_mask:
1899 case X86::BI__builtin_ia32_divps512_mask:
1900 case X86::BI__builtin_ia32_mulpd512_mask:
1901 case X86::BI__builtin_ia32_mulps512_mask:
1902 case X86::BI__builtin_ia32_subpd512_mask:
1903 case X86::BI__builtin_ia32_subps512_mask:
1904 case X86::BI__builtin_ia32_addss_round_mask:
1905 case X86::BI__builtin_ia32_addsd_round_mask:
1906 case X86::BI__builtin_ia32_divss_round_mask:
1907 case X86::BI__builtin_ia32_divsd_round_mask:
1908 case X86::BI__builtin_ia32_mulss_round_mask:
1909 case X86::BI__builtin_ia32_mulsd_round_mask:
1910 case X86::BI__builtin_ia32_subss_round_mask:
1911 case X86::BI__builtin_ia32_subsd_round_mask:
1912 case X86::BI__builtin_ia32_scalefpd512_mask:
1913 case X86::BI__builtin_ia32_scalefps512_mask:
1914 case X86::BI__builtin_ia32_scalefsd_round_mask:
1915 case X86::BI__builtin_ia32_scalefss_round_mask:
1916 case X86::BI__builtin_ia32_getmantpd512_mask:
1917 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001918 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
1919 case X86::BI__builtin_ia32_sqrtsd_round_mask:
1920 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001921 case X86::BI__builtin_ia32_vfmaddpd512_mask:
1922 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1923 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1924 case X86::BI__builtin_ia32_vfmaddps512_mask:
1925 case X86::BI__builtin_ia32_vfmaddps512_mask3:
1926 case X86::BI__builtin_ia32_vfmaddps512_maskz:
1927 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1928 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1929 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1930 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1931 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1932 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1933 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1934 case X86::BI__builtin_ia32_vfmsubps512_mask3:
1935 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1936 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1937 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1938 case X86::BI__builtin_ia32_vfnmaddps512_mask:
1939 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1940 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1941 case X86::BI__builtin_ia32_vfnmsubps512_mask:
1942 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1943 case X86::BI__builtin_ia32_vfmaddsd3_mask:
1944 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1945 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1946 case X86::BI__builtin_ia32_vfmaddss3_mask:
1947 case X86::BI__builtin_ia32_vfmaddss3_maskz:
1948 case X86::BI__builtin_ia32_vfmaddss3_mask3:
1949 ArgNum = 4;
1950 HasRC = true;
1951 break;
1952 case X86::BI__builtin_ia32_getmantsd_round_mask:
1953 case X86::BI__builtin_ia32_getmantss_round_mask:
1954 ArgNum = 5;
1955 HasRC = true;
1956 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00001957 }
1958
1959 llvm::APSInt Result;
1960
1961 // We can't check the value of a dependent argument.
1962 Expr *Arg = TheCall->getArg(ArgNum);
1963 if (Arg->isTypeDependent() || Arg->isValueDependent())
1964 return false;
1965
1966 // Check constant-ness first.
1967 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1968 return true;
1969
1970 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1971 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1972 // combined with ROUND_NO_EXC.
1973 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1974 Result == 8/*ROUND_NO_EXC*/ ||
1975 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1976 return false;
1977
1978 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1979 << Arg->getSourceRange();
1980}
1981
Craig Topperf0ddc892016-09-23 04:48:27 +00001982bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1983 if (BuiltinID == X86::BI__builtin_cpu_supports)
1984 return SemaBuiltinCpuSupports(*this, TheCall);
1985
1986 if (BuiltinID == X86::BI__builtin_ms_va_start)
1987 return SemaBuiltinMSVAStart(TheCall);
1988
Craig Toppera7e253e2016-09-23 04:48:31 +00001989 // If the intrinsic has rounding or SAE make sure its valid.
1990 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
1991 return true;
1992
Craig Topperf0ddc892016-09-23 04:48:27 +00001993 // For intrinsics which take an immediate value as part of the instruction,
1994 // range check them here.
1995 int i = 0, l = 0, u = 0;
1996 switch (BuiltinID) {
1997 default:
1998 return false;
Richard Trieucc3949d2016-02-18 22:34:54 +00001999 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00002000 i = 1; l = 0; u = 3;
2001 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002002 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00002003 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2004 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2005 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2006 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002007 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002008 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002009 case X86::BI__builtin_ia32_vpermil2pd:
2010 case X86::BI__builtin_ia32_vpermil2pd256:
2011 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002012 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002013 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002014 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002015 case X86::BI__builtin_ia32_cmpb128_mask:
2016 case X86::BI__builtin_ia32_cmpw128_mask:
2017 case X86::BI__builtin_ia32_cmpd128_mask:
2018 case X86::BI__builtin_ia32_cmpq128_mask:
2019 case X86::BI__builtin_ia32_cmpb256_mask:
2020 case X86::BI__builtin_ia32_cmpw256_mask:
2021 case X86::BI__builtin_ia32_cmpd256_mask:
2022 case X86::BI__builtin_ia32_cmpq256_mask:
2023 case X86::BI__builtin_ia32_cmpb512_mask:
2024 case X86::BI__builtin_ia32_cmpw512_mask:
2025 case X86::BI__builtin_ia32_cmpd512_mask:
2026 case X86::BI__builtin_ia32_cmpq512_mask:
2027 case X86::BI__builtin_ia32_ucmpb128_mask:
2028 case X86::BI__builtin_ia32_ucmpw128_mask:
2029 case X86::BI__builtin_ia32_ucmpd128_mask:
2030 case X86::BI__builtin_ia32_ucmpq128_mask:
2031 case X86::BI__builtin_ia32_ucmpb256_mask:
2032 case X86::BI__builtin_ia32_ucmpw256_mask:
2033 case X86::BI__builtin_ia32_ucmpd256_mask:
2034 case X86::BI__builtin_ia32_ucmpq256_mask:
2035 case X86::BI__builtin_ia32_ucmpb512_mask:
2036 case X86::BI__builtin_ia32_ucmpw512_mask:
2037 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002038 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002039 case X86::BI__builtin_ia32_vpcomub:
2040 case X86::BI__builtin_ia32_vpcomuw:
2041 case X86::BI__builtin_ia32_vpcomud:
2042 case X86::BI__builtin_ia32_vpcomuq:
2043 case X86::BI__builtin_ia32_vpcomb:
2044 case X86::BI__builtin_ia32_vpcomw:
2045 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002046 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00002047 i = 2; l = 0; u = 7;
2048 break;
2049 case X86::BI__builtin_ia32_roundps:
2050 case X86::BI__builtin_ia32_roundpd:
2051 case X86::BI__builtin_ia32_roundps256:
2052 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002053 i = 1; l = 0; u = 15;
2054 break;
2055 case X86::BI__builtin_ia32_roundss:
2056 case X86::BI__builtin_ia32_roundsd:
2057 case X86::BI__builtin_ia32_rangepd128_mask:
2058 case X86::BI__builtin_ia32_rangepd256_mask:
2059 case X86::BI__builtin_ia32_rangepd512_mask:
2060 case X86::BI__builtin_ia32_rangeps128_mask:
2061 case X86::BI__builtin_ia32_rangeps256_mask:
2062 case X86::BI__builtin_ia32_rangeps512_mask:
2063 case X86::BI__builtin_ia32_getmantsd_round_mask:
2064 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002065 i = 2; l = 0; u = 15;
2066 break;
2067 case X86::BI__builtin_ia32_cmpps:
2068 case X86::BI__builtin_ia32_cmpss:
2069 case X86::BI__builtin_ia32_cmppd:
2070 case X86::BI__builtin_ia32_cmpsd:
2071 case X86::BI__builtin_ia32_cmpps256:
2072 case X86::BI__builtin_ia32_cmppd256:
2073 case X86::BI__builtin_ia32_cmpps128_mask:
2074 case X86::BI__builtin_ia32_cmppd128_mask:
2075 case X86::BI__builtin_ia32_cmpps256_mask:
2076 case X86::BI__builtin_ia32_cmppd256_mask:
2077 case X86::BI__builtin_ia32_cmpps512_mask:
2078 case X86::BI__builtin_ia32_cmppd512_mask:
2079 case X86::BI__builtin_ia32_cmpsd_mask:
2080 case X86::BI__builtin_ia32_cmpss_mask:
2081 i = 2; l = 0; u = 31;
2082 break;
2083 case X86::BI__builtin_ia32_xabort:
2084 i = 0; l = -128; u = 255;
2085 break;
2086 case X86::BI__builtin_ia32_pshufw:
2087 case X86::BI__builtin_ia32_aeskeygenassist128:
2088 i = 1; l = -128; u = 255;
2089 break;
2090 case X86::BI__builtin_ia32_vcvtps2ph:
2091 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper39c87102016-05-18 03:18:12 +00002092 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2093 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2094 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2095 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2096 case X86::BI__builtin_ia32_rndscaleps_mask:
2097 case X86::BI__builtin_ia32_rndscalepd_mask:
2098 case X86::BI__builtin_ia32_reducepd128_mask:
2099 case X86::BI__builtin_ia32_reducepd256_mask:
2100 case X86::BI__builtin_ia32_reducepd512_mask:
2101 case X86::BI__builtin_ia32_reduceps128_mask:
2102 case X86::BI__builtin_ia32_reduceps256_mask:
2103 case X86::BI__builtin_ia32_reduceps512_mask:
2104 case X86::BI__builtin_ia32_prold512_mask:
2105 case X86::BI__builtin_ia32_prolq512_mask:
2106 case X86::BI__builtin_ia32_prold128_mask:
2107 case X86::BI__builtin_ia32_prold256_mask:
2108 case X86::BI__builtin_ia32_prolq128_mask:
2109 case X86::BI__builtin_ia32_prolq256_mask:
2110 case X86::BI__builtin_ia32_prord128_mask:
2111 case X86::BI__builtin_ia32_prord256_mask:
2112 case X86::BI__builtin_ia32_prorq128_mask:
2113 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002114 case X86::BI__builtin_ia32_fpclasspd128_mask:
2115 case X86::BI__builtin_ia32_fpclasspd256_mask:
2116 case X86::BI__builtin_ia32_fpclassps128_mask:
2117 case X86::BI__builtin_ia32_fpclassps256_mask:
2118 case X86::BI__builtin_ia32_fpclassps512_mask:
2119 case X86::BI__builtin_ia32_fpclasspd512_mask:
2120 case X86::BI__builtin_ia32_fpclasssd_mask:
2121 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002122 i = 1; l = 0; u = 255;
2123 break;
2124 case X86::BI__builtin_ia32_palignr:
2125 case X86::BI__builtin_ia32_insertps128:
2126 case X86::BI__builtin_ia32_dpps:
2127 case X86::BI__builtin_ia32_dppd:
2128 case X86::BI__builtin_ia32_dpps256:
2129 case X86::BI__builtin_ia32_mpsadbw128:
2130 case X86::BI__builtin_ia32_mpsadbw256:
2131 case X86::BI__builtin_ia32_pcmpistrm128:
2132 case X86::BI__builtin_ia32_pcmpistri128:
2133 case X86::BI__builtin_ia32_pcmpistria128:
2134 case X86::BI__builtin_ia32_pcmpistric128:
2135 case X86::BI__builtin_ia32_pcmpistrio128:
2136 case X86::BI__builtin_ia32_pcmpistris128:
2137 case X86::BI__builtin_ia32_pcmpistriz128:
2138 case X86::BI__builtin_ia32_pclmulqdq128:
2139 case X86::BI__builtin_ia32_vperm2f128_pd256:
2140 case X86::BI__builtin_ia32_vperm2f128_ps256:
2141 case X86::BI__builtin_ia32_vperm2f128_si256:
2142 case X86::BI__builtin_ia32_permti256:
2143 i = 2; l = -128; u = 255;
2144 break;
2145 case X86::BI__builtin_ia32_palignr128:
2146 case X86::BI__builtin_ia32_palignr256:
Craig Topper39c87102016-05-18 03:18:12 +00002147 case X86::BI__builtin_ia32_palignr512_mask:
2148 case X86::BI__builtin_ia32_alignq512_mask:
2149 case X86::BI__builtin_ia32_alignd512_mask:
2150 case X86::BI__builtin_ia32_alignd128_mask:
2151 case X86::BI__builtin_ia32_alignd256_mask:
2152 case X86::BI__builtin_ia32_alignq128_mask:
2153 case X86::BI__builtin_ia32_alignq256_mask:
2154 case X86::BI__builtin_ia32_vcomisd:
2155 case X86::BI__builtin_ia32_vcomiss:
2156 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2157 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2158 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2159 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002160 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2161 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2162 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2163 i = 2; l = 0; u = 255;
2164 break;
2165 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2166 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2167 case X86::BI__builtin_ia32_fixupimmps512_mask:
2168 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2169 case X86::BI__builtin_ia32_fixupimmsd_mask:
2170 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2171 case X86::BI__builtin_ia32_fixupimmss_mask:
2172 case X86::BI__builtin_ia32_fixupimmss_maskz:
2173 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2174 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2175 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2176 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2177 case X86::BI__builtin_ia32_fixupimmps128_mask:
2178 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2179 case X86::BI__builtin_ia32_fixupimmps256_mask:
2180 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2181 case X86::BI__builtin_ia32_pternlogd512_mask:
2182 case X86::BI__builtin_ia32_pternlogd512_maskz:
2183 case X86::BI__builtin_ia32_pternlogq512_mask:
2184 case X86::BI__builtin_ia32_pternlogq512_maskz:
2185 case X86::BI__builtin_ia32_pternlogd128_mask:
2186 case X86::BI__builtin_ia32_pternlogd128_maskz:
2187 case X86::BI__builtin_ia32_pternlogd256_mask:
2188 case X86::BI__builtin_ia32_pternlogd256_maskz:
2189 case X86::BI__builtin_ia32_pternlogq128_mask:
2190 case X86::BI__builtin_ia32_pternlogq128_maskz:
2191 case X86::BI__builtin_ia32_pternlogq256_mask:
2192 case X86::BI__builtin_ia32_pternlogq256_maskz:
2193 i = 3; l = 0; u = 255;
2194 break;
2195 case X86::BI__builtin_ia32_pcmpestrm128:
2196 case X86::BI__builtin_ia32_pcmpestri128:
2197 case X86::BI__builtin_ia32_pcmpestria128:
2198 case X86::BI__builtin_ia32_pcmpestric128:
2199 case X86::BI__builtin_ia32_pcmpestrio128:
2200 case X86::BI__builtin_ia32_pcmpestris128:
2201 case X86::BI__builtin_ia32_pcmpestriz128:
2202 i = 4; l = -128; u = 255;
2203 break;
2204 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2205 case X86::BI__builtin_ia32_rndscaless_round_mask:
2206 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002207 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002208 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002209 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002210}
2211
Richard Smith55ce3522012-06-25 20:30:08 +00002212/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2213/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2214/// Returns true when the format fits the function and the FormatStringInfo has
2215/// been populated.
2216bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2217 FormatStringInfo *FSI) {
2218 FSI->HasVAListArg = Format->getFirstArg() == 0;
2219 FSI->FormatIdx = Format->getFormatIdx() - 1;
2220 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002221
Richard Smith55ce3522012-06-25 20:30:08 +00002222 // The way the format attribute works in GCC, the implicit this argument
2223 // of member functions is counted. However, it doesn't appear in our own
2224 // lists, so decrement format_idx in that case.
2225 if (IsCXXMember) {
2226 if(FSI->FormatIdx == 0)
2227 return false;
2228 --FSI->FormatIdx;
2229 if (FSI->FirstDataArg != 0)
2230 --FSI->FirstDataArg;
2231 }
2232 return true;
2233}
Mike Stump11289f42009-09-09 15:08:12 +00002234
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002235/// Checks if a the given expression evaluates to null.
2236///
2237/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002238static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002239 // If the expression has non-null type, it doesn't evaluate to null.
2240 if (auto nullability
2241 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2242 if (*nullability == NullabilityKind::NonNull)
2243 return false;
2244 }
2245
Ted Kremeneka146db32014-01-17 06:24:47 +00002246 // As a special case, transparent unions initialized with zero are
2247 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002248 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002249 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2250 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002251 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002252 if (const InitListExpr *ILE =
2253 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002254 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002255 }
2256
2257 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002258 return (!Expr->isValueDependent() &&
2259 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2260 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002261}
2262
2263static void CheckNonNullArgument(Sema &S,
2264 const Expr *ArgExpr,
2265 SourceLocation CallSiteLoc) {
2266 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002267 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2268 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002269}
2270
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002271bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2272 FormatStringInfo FSI;
2273 if ((GetFormatStringType(Format) == FST_NSString) &&
2274 getFormatStringInfo(Format, false, &FSI)) {
2275 Idx = FSI.FormatIdx;
2276 return true;
2277 }
2278 return false;
2279}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002280/// \brief Diagnose use of %s directive in an NSString which is being passed
2281/// as formatting string to formatting method.
2282static void
2283DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2284 const NamedDecl *FDecl,
2285 Expr **Args,
2286 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002287 unsigned Idx = 0;
2288 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002289 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2290 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002291 Idx = 2;
2292 Format = true;
2293 }
2294 else
2295 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2296 if (S.GetFormatNSStringIdx(I, Idx)) {
2297 Format = true;
2298 break;
2299 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002300 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002301 if (!Format || NumArgs <= Idx)
2302 return;
2303 const Expr *FormatExpr = Args[Idx];
2304 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2305 FormatExpr = CSCE->getSubExpr();
2306 const StringLiteral *FormatString;
2307 if (const ObjCStringLiteral *OSL =
2308 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2309 FormatString = OSL->getString();
2310 else
2311 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2312 if (!FormatString)
2313 return;
2314 if (S.FormatStringHasSArg(FormatString)) {
2315 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2316 << "%s" << 1 << 1;
2317 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2318 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002319 }
2320}
2321
Douglas Gregorb4866e82015-06-19 18:13:19 +00002322/// Determine whether the given type has a non-null nullability annotation.
2323static bool isNonNullType(ASTContext &ctx, QualType type) {
2324 if (auto nullability = type->getNullability(ctx))
2325 return *nullability == NullabilityKind::NonNull;
2326
2327 return false;
2328}
2329
Ted Kremenek2bc73332014-01-17 06:24:43 +00002330static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002331 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002332 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002333 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002334 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002335 assert((FDecl || Proto) && "Need a function declaration or prototype");
2336
Ted Kremenek9aedc152014-01-17 06:24:56 +00002337 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002338 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002339 if (FDecl) {
2340 // Handle the nonnull attribute on the function/method declaration itself.
2341 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2342 if (!NonNull->args_size()) {
2343 // Easy case: all pointer arguments are nonnull.
2344 for (const auto *Arg : Args)
2345 if (S.isValidPointerAttrType(Arg->getType()))
2346 CheckNonNullArgument(S, Arg, CallSiteLoc);
2347 return;
2348 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002349
Douglas Gregorb4866e82015-06-19 18:13:19 +00002350 for (unsigned Val : NonNull->args()) {
2351 if (Val >= Args.size())
2352 continue;
2353 if (NonNullArgs.empty())
2354 NonNullArgs.resize(Args.size());
2355 NonNullArgs.set(Val);
2356 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002357 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002358 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002359
Douglas Gregorb4866e82015-06-19 18:13:19 +00002360 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2361 // Handle the nonnull attribute on the parameters of the
2362 // function/method.
2363 ArrayRef<ParmVarDecl*> parms;
2364 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2365 parms = FD->parameters();
2366 else
2367 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2368
2369 unsigned ParamIndex = 0;
2370 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2371 I != E; ++I, ++ParamIndex) {
2372 const ParmVarDecl *PVD = *I;
2373 if (PVD->hasAttr<NonNullAttr>() ||
2374 isNonNullType(S.Context, PVD->getType())) {
2375 if (NonNullArgs.empty())
2376 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002377
Douglas Gregorb4866e82015-06-19 18:13:19 +00002378 NonNullArgs.set(ParamIndex);
2379 }
2380 }
2381 } else {
2382 // If we have a non-function, non-method declaration but no
2383 // function prototype, try to dig out the function prototype.
2384 if (!Proto) {
2385 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2386 QualType type = VD->getType().getNonReferenceType();
2387 if (auto pointerType = type->getAs<PointerType>())
2388 type = pointerType->getPointeeType();
2389 else if (auto blockType = type->getAs<BlockPointerType>())
2390 type = blockType->getPointeeType();
2391 // FIXME: data member pointers?
2392
2393 // Dig out the function prototype, if there is one.
2394 Proto = type->getAs<FunctionProtoType>();
2395 }
2396 }
2397
2398 // Fill in non-null argument information from the nullability
2399 // information on the parameter types (if we have them).
2400 if (Proto) {
2401 unsigned Index = 0;
2402 for (auto paramType : Proto->getParamTypes()) {
2403 if (isNonNullType(S.Context, paramType)) {
2404 if (NonNullArgs.empty())
2405 NonNullArgs.resize(Args.size());
2406
2407 NonNullArgs.set(Index);
2408 }
2409
2410 ++Index;
2411 }
2412 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002413 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002414
Douglas Gregorb4866e82015-06-19 18:13:19 +00002415 // Check for non-null arguments.
2416 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2417 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002418 if (NonNullArgs[ArgIndex])
2419 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002420 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002421}
2422
Richard Smith55ce3522012-06-25 20:30:08 +00002423/// Handles the checks for format strings, non-POD arguments to vararg
2424/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002425void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2426 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00002427 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00002428 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002429 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002430 if (CurContext->isDependentContext())
2431 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002432
Ted Kremenekb8176da2010-09-09 04:33:05 +00002433 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002434 llvm::SmallBitVector CheckedVarArgs;
2435 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002436 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002437 // Only create vector if there are format attributes.
2438 CheckedVarArgs.resize(Args.size());
2439
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002440 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002441 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002442 }
Richard Smithd7293d72013-08-05 18:49:43 +00002443 }
Richard Smith55ce3522012-06-25 20:30:08 +00002444
2445 // Refuse POD arguments that weren't caught by the format string
2446 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00002447 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002448 unsigned NumParams = Proto ? Proto->getNumParams()
2449 : FDecl && isa<FunctionDecl>(FDecl)
2450 ? cast<FunctionDecl>(FDecl)->getNumParams()
2451 : FDecl && isa<ObjCMethodDecl>(FDecl)
2452 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2453 : 0;
2454
Alp Toker9cacbab2014-01-20 20:26:09 +00002455 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002456 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002457 if (const Expr *Arg = Args[ArgIdx]) {
2458 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2459 checkVariadicArgument(Arg, CallType);
2460 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002461 }
Richard Smithd7293d72013-08-05 18:49:43 +00002462 }
Mike Stump11289f42009-09-09 15:08:12 +00002463
Douglas Gregorb4866e82015-06-19 18:13:19 +00002464 if (FDecl || Proto) {
2465 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002466
Richard Trieu41bc0992013-06-22 00:20:41 +00002467 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002468 if (FDecl) {
2469 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2470 CheckArgumentWithTypeTag(I, Args.data());
2471 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002472 }
Richard Smith55ce3522012-06-25 20:30:08 +00002473}
2474
2475/// CheckConstructorCall - Check a constructor call for correctness and safety
2476/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002477void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2478 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002479 const FunctionProtoType *Proto,
2480 SourceLocation Loc) {
2481 VariadicCallType CallType =
2482 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002483 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
2484 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002485}
2486
2487/// CheckFunctionCall - Check a direct function call for various correctness
2488/// and safety properties not strictly enforced by the C type system.
2489bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2490 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002491 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2492 isa<CXXMethodDecl>(FDecl);
2493 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2494 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002495 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2496 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002497 Expr** Args = TheCall->getArgs();
2498 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00002499 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002500 // If this is a call to a member operator, hide the first argument
2501 // from checkCall.
2502 // FIXME: Our choice of AST representation here is less than ideal.
2503 ++Args;
2504 --NumArgs;
2505 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00002506 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002507 IsMemberFunction, TheCall->getRParenLoc(),
2508 TheCall->getCallee()->getSourceRange(), CallType);
2509
2510 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2511 // None of the checks below are needed for functions that don't have
2512 // simple names (e.g., C++ conversion functions).
2513 if (!FnInfo)
2514 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002515
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002516 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002517 if (getLangOpts().ObjC1)
2518 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002519
Anna Zaks22122702012-01-17 00:37:07 +00002520 unsigned CMId = FDecl->getMemoryFunctionKind();
2521 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002522 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002523
Anna Zaks201d4892012-01-13 21:52:01 +00002524 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002525 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002526 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002527 else if (CMId == Builtin::BIstrncat)
2528 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002529 else
Anna Zaks22122702012-01-17 00:37:07 +00002530 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002531
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002532 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002533}
2534
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002535bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002536 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002537 VariadicCallType CallType =
2538 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002539
Douglas Gregorb4866e82015-06-19 18:13:19 +00002540 checkCall(Method, nullptr, Args,
2541 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2542 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002543
2544 return false;
2545}
2546
Richard Trieu664c4c62013-06-20 21:03:13 +00002547bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2548 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002549 QualType Ty;
2550 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002551 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002552 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002553 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002554 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002555 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002556
Douglas Gregorb4866e82015-06-19 18:13:19 +00002557 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2558 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002559 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002560
Richard Trieu664c4c62013-06-20 21:03:13 +00002561 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002562 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002563 CallType = VariadicDoesNotApply;
2564 } else if (Ty->isBlockPointerType()) {
2565 CallType = VariadicBlock;
2566 } else { // Ty->isFunctionPointerType()
2567 CallType = VariadicFunction;
2568 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002569
Douglas Gregorb4866e82015-06-19 18:13:19 +00002570 checkCall(NDecl, Proto,
2571 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2572 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002573 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002574
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002575 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002576}
2577
Richard Trieu41bc0992013-06-22 00:20:41 +00002578/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2579/// such as function pointers returned from functions.
2580bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002581 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002582 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00002583 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002584 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002585 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002586 TheCall->getCallee()->getSourceRange(), CallType);
2587
2588 return false;
2589}
2590
Tim Northovere94a34c2014-03-11 10:49:14 +00002591static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002592 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002593 return false;
2594
JF Bastiendda2cb12016-04-18 18:01:49 +00002595 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002596 switch (Op) {
2597 case AtomicExpr::AO__c11_atomic_init:
2598 llvm_unreachable("There is no ordering argument for an init");
2599
2600 case AtomicExpr::AO__c11_atomic_load:
2601 case AtomicExpr::AO__atomic_load_n:
2602 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002603 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2604 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002605
2606 case AtomicExpr::AO__c11_atomic_store:
2607 case AtomicExpr::AO__atomic_store:
2608 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002609 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2610 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2611 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002612
2613 default:
2614 return true;
2615 }
2616}
2617
Richard Smithfeea8832012-04-12 05:08:17 +00002618ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2619 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002620 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2621 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002622
Richard Smithfeea8832012-04-12 05:08:17 +00002623 // All these operations take one of the following forms:
2624 enum {
2625 // C __c11_atomic_init(A *, C)
2626 Init,
2627 // C __c11_atomic_load(A *, int)
2628 Load,
2629 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002630 LoadCopy,
2631 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002632 Copy,
2633 // C __c11_atomic_add(A *, M, int)
2634 Arithmetic,
2635 // C __atomic_exchange_n(A *, CP, int)
2636 Xchg,
2637 // void __atomic_exchange(A *, C *, CP, int)
2638 GNUXchg,
2639 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2640 C11CmpXchg,
2641 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2642 GNUCmpXchg
2643 } Form = Init;
Eric Fiselier8d662442016-03-30 23:39:56 +00002644 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2645 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002646 // where:
2647 // C is an appropriate type,
2648 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2649 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2650 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2651 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002652
Gabor Horvath98bd0982015-03-16 09:59:54 +00002653 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2654 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2655 AtomicExpr::AO__atomic_load,
2656 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00002657 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2658 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2659 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2660 Op == AtomicExpr::AO__atomic_store_n ||
2661 Op == AtomicExpr::AO__atomic_exchange_n ||
2662 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2663 bool IsAddSub = false;
2664
2665 switch (Op) {
2666 case AtomicExpr::AO__c11_atomic_init:
2667 Form = Init;
2668 break;
2669
2670 case AtomicExpr::AO__c11_atomic_load:
2671 case AtomicExpr::AO__atomic_load_n:
2672 Form = Load;
2673 break;
2674
Richard Smithfeea8832012-04-12 05:08:17 +00002675 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002676 Form = LoadCopy;
2677 break;
2678
2679 case AtomicExpr::AO__c11_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002680 case AtomicExpr::AO__atomic_store:
2681 case AtomicExpr::AO__atomic_store_n:
2682 Form = Copy;
2683 break;
2684
2685 case AtomicExpr::AO__c11_atomic_fetch_add:
2686 case AtomicExpr::AO__c11_atomic_fetch_sub:
2687 case AtomicExpr::AO__atomic_fetch_add:
2688 case AtomicExpr::AO__atomic_fetch_sub:
2689 case AtomicExpr::AO__atomic_add_fetch:
2690 case AtomicExpr::AO__atomic_sub_fetch:
2691 IsAddSub = true;
2692 // Fall through.
2693 case AtomicExpr::AO__c11_atomic_fetch_and:
2694 case AtomicExpr::AO__c11_atomic_fetch_or:
2695 case AtomicExpr::AO__c11_atomic_fetch_xor:
2696 case AtomicExpr::AO__atomic_fetch_and:
2697 case AtomicExpr::AO__atomic_fetch_or:
2698 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00002699 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00002700 case AtomicExpr::AO__atomic_and_fetch:
2701 case AtomicExpr::AO__atomic_or_fetch:
2702 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00002703 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00002704 Form = Arithmetic;
2705 break;
2706
2707 case AtomicExpr::AO__c11_atomic_exchange:
2708 case AtomicExpr::AO__atomic_exchange_n:
2709 Form = Xchg;
2710 break;
2711
2712 case AtomicExpr::AO__atomic_exchange:
2713 Form = GNUXchg;
2714 break;
2715
2716 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2717 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2718 Form = C11CmpXchg;
2719 break;
2720
2721 case AtomicExpr::AO__atomic_compare_exchange:
2722 case AtomicExpr::AO__atomic_compare_exchange_n:
2723 Form = GNUCmpXchg;
2724 break;
2725 }
2726
2727 // Check we have the right number of arguments.
2728 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002729 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002730 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002731 << TheCall->getCallee()->getSourceRange();
2732 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00002733 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2734 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002735 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002736 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002737 << TheCall->getCallee()->getSourceRange();
2738 return ExprError();
2739 }
2740
Richard Smithfeea8832012-04-12 05:08:17 +00002741 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002742 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00002743 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2744 if (ConvertedPtr.isInvalid())
2745 return ExprError();
2746
2747 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002748 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2749 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00002750 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002751 << Ptr->getType() << Ptr->getSourceRange();
2752 return ExprError();
2753 }
2754
Richard Smithfeea8832012-04-12 05:08:17 +00002755 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2756 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2757 QualType ValType = AtomTy; // 'C'
2758 if (IsC11) {
2759 if (!AtomTy->isAtomicType()) {
2760 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2761 << Ptr->getType() << Ptr->getSourceRange();
2762 return ExprError();
2763 }
Richard Smithe00921a2012-09-15 06:09:58 +00002764 if (AtomTy.isConstQualified()) {
2765 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2766 << Ptr->getType() << Ptr->getSourceRange();
2767 return ExprError();
2768 }
Richard Smithfeea8832012-04-12 05:08:17 +00002769 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00002770 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002771 if (ValType.isConstQualified()) {
2772 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2773 << Ptr->getType() << Ptr->getSourceRange();
2774 return ExprError();
2775 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002776 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002777
Richard Smithfeea8832012-04-12 05:08:17 +00002778 // For an arithmetic operation, the implied arithmetic must be well-formed.
2779 if (Form == Arithmetic) {
2780 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2781 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2782 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2783 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2784 return ExprError();
2785 }
2786 if (!IsAddSub && !ValType->isIntegerType()) {
2787 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2788 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2789 return ExprError();
2790 }
David Majnemere85cff82015-01-28 05:48:06 +00002791 if (IsC11 && ValType->isPointerType() &&
2792 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2793 diag::err_incomplete_type)) {
2794 return ExprError();
2795 }
Richard Smithfeea8832012-04-12 05:08:17 +00002796 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2797 // For __atomic_*_n operations, the value type must be a scalar integral or
2798 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002799 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00002800 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2801 return ExprError();
2802 }
2803
Eli Friedmanaa769812013-09-11 03:49:34 +00002804 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2805 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00002806 // For GNU atomics, require a trivially-copyable type. This is not part of
2807 // the GNU atomics specification, but we enforce it for sanity.
2808 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002809 << Ptr->getType() << Ptr->getSourceRange();
2810 return ExprError();
2811 }
2812
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002813 switch (ValType.getObjCLifetime()) {
2814 case Qualifiers::OCL_None:
2815 case Qualifiers::OCL_ExplicitNone:
2816 // okay
2817 break;
2818
2819 case Qualifiers::OCL_Weak:
2820 case Qualifiers::OCL_Strong:
2821 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002822 // FIXME: Can this happen? By this point, ValType should be known
2823 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002824 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2825 << ValType << Ptr->getSourceRange();
2826 return ExprError();
2827 }
2828
David Majnemerc6eb6502015-06-03 00:26:35 +00002829 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2830 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00002831 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00002832 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00002833 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002834 QualType ResultType = ValType;
Eric Fiselier8d662442016-03-30 23:39:56 +00002835 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002836 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002837 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002838 ResultType = Context.BoolTy;
2839
Richard Smithfeea8832012-04-12 05:08:17 +00002840 // The type of a parameter passed 'by value'. In the GNU atomics, such
2841 // arguments are actually passed as pointers.
2842 QualType ByValType = ValType; // 'CP'
2843 if (!IsC11 && !IsN)
2844 ByValType = Ptr->getType();
2845
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002846 // The first argument --- the pointer --- has a fixed type; we
2847 // deduce the types of the rest of the arguments accordingly. Walk
2848 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002849 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002850 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002851 if (i < NumVals[Form] + 1) {
2852 switch (i) {
2853 case 1:
2854 // The second argument is the non-atomic operand. For arithmetic, this
2855 // is always passed by value, and for a compare_exchange it is always
2856 // passed by address. For the rest, GNU uses by-address and C11 uses
2857 // by-value.
2858 assert(Form != Load);
2859 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2860 Ty = ValType;
2861 else if (Form == Copy || Form == Xchg)
2862 Ty = ByValType;
2863 else if (Form == Arithmetic)
2864 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002865 else {
2866 Expr *ValArg = TheCall->getArg(i);
2867 unsigned AS = 0;
2868 // Keep address space of non-atomic pointer type.
2869 if (const PointerType *PtrTy =
2870 ValArg->getType()->getAs<PointerType>()) {
2871 AS = PtrTy->getPointeeType().getAddressSpace();
2872 }
2873 Ty = Context.getPointerType(
2874 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2875 }
Richard Smithfeea8832012-04-12 05:08:17 +00002876 break;
2877 case 2:
2878 // The third argument to compare_exchange / GNU exchange is a
2879 // (pointer to a) desired value.
2880 Ty = ByValType;
2881 break;
2882 case 3:
2883 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2884 Ty = Context.BoolTy;
2885 break;
2886 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002887 } else {
2888 // The order(s) are always converted to int.
2889 Ty = Context.IntTy;
2890 }
Richard Smithfeea8832012-04-12 05:08:17 +00002891
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002892 InitializedEntity Entity =
2893 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00002894 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002895 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2896 if (Arg.isInvalid())
2897 return true;
2898 TheCall->setArg(i, Arg.get());
2899 }
2900
Richard Smithfeea8832012-04-12 05:08:17 +00002901 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002902 SmallVector<Expr*, 5> SubExprs;
2903 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00002904 switch (Form) {
2905 case Init:
2906 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00002907 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002908 break;
2909 case Load:
2910 SubExprs.push_back(TheCall->getArg(1)); // Order
2911 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00002912 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00002913 case Copy:
2914 case Arithmetic:
2915 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002916 SubExprs.push_back(TheCall->getArg(2)); // Order
2917 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002918 break;
2919 case GNUXchg:
2920 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2921 SubExprs.push_back(TheCall->getArg(3)); // Order
2922 SubExprs.push_back(TheCall->getArg(1)); // Val1
2923 SubExprs.push_back(TheCall->getArg(2)); // Val2
2924 break;
2925 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002926 SubExprs.push_back(TheCall->getArg(3)); // Order
2927 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002928 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00002929 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00002930 break;
2931 case GNUCmpXchg:
2932 SubExprs.push_back(TheCall->getArg(4)); // Order
2933 SubExprs.push_back(TheCall->getArg(1)); // Val1
2934 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2935 SubExprs.push_back(TheCall->getArg(2)); // Val2
2936 SubExprs.push_back(TheCall->getArg(3)); // Weak
2937 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002938 }
Tim Northovere94a34c2014-03-11 10:49:14 +00002939
2940 if (SubExprs.size() >= 2 && Form != Init) {
2941 llvm::APSInt Result(32);
2942 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2943 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00002944 Diag(SubExprs[1]->getLocStart(),
2945 diag::warn_atomic_op_has_invalid_memory_order)
2946 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00002947 }
2948
Fariborz Jahanian615de762013-05-28 17:37:39 +00002949 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2950 SubExprs, ResultType, Op,
2951 TheCall->getRParenLoc());
2952
2953 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2954 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2955 Context.AtomicUsesUnsupportedLibcall(AE))
2956 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2957 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002958
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002959 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002960}
2961
John McCall29ad95b2011-08-27 01:09:30 +00002962/// checkBuiltinArgument - Given a call to a builtin function, perform
2963/// normal type-checking on the given argument, updating the call in
2964/// place. This is useful when a builtin function requires custom
2965/// type-checking for some of its arguments but not necessarily all of
2966/// them.
2967///
2968/// Returns true on error.
2969static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2970 FunctionDecl *Fn = E->getDirectCallee();
2971 assert(Fn && "builtin call without direct callee!");
2972
2973 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2974 InitializedEntity Entity =
2975 InitializedEntity::InitializeParameter(S.Context, Param);
2976
2977 ExprResult Arg = E->getArg(0);
2978 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2979 if (Arg.isInvalid())
2980 return true;
2981
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002982 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00002983 return false;
2984}
2985
Chris Lattnerdc046542009-05-08 06:58:22 +00002986/// SemaBuiltinAtomicOverloaded - We have a call to a function like
2987/// __sync_fetch_and_add, which is an overloaded function based on the pointer
2988/// type of its first argument. The main ActOnCallExpr routines have already
2989/// promoted the types of arguments because all of these calls are prototyped as
2990/// void(...).
2991///
2992/// This function goes through and does final semantic checking for these
2993/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00002994ExprResult
2995Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002996 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00002997 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2998 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2999
3000 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003001 if (TheCall->getNumArgs() < 1) {
3002 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3003 << 0 << 1 << TheCall->getNumArgs()
3004 << TheCall->getCallee()->getSourceRange();
3005 return ExprError();
3006 }
Mike Stump11289f42009-09-09 15:08:12 +00003007
Chris Lattnerdc046542009-05-08 06:58:22 +00003008 // Inspect the first argument of the atomic builtin. This should always be
3009 // a pointer type, whose element is an integral scalar or pointer type.
3010 // Because it is a pointer type, we don't have to worry about any implicit
3011 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003012 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003013 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003014 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3015 if (FirstArgResult.isInvalid())
3016 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003017 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003018 TheCall->setArg(0, FirstArg);
3019
John McCall31168b02011-06-15 23:02:42 +00003020 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3021 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003022 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3023 << FirstArg->getType() << FirstArg->getSourceRange();
3024 return ExprError();
3025 }
Mike Stump11289f42009-09-09 15:08:12 +00003026
John McCall31168b02011-06-15 23:02:42 +00003027 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003028 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003029 !ValType->isBlockPointerType()) {
3030 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3031 << FirstArg->getType() << FirstArg->getSourceRange();
3032 return ExprError();
3033 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003034
John McCall31168b02011-06-15 23:02:42 +00003035 switch (ValType.getObjCLifetime()) {
3036 case Qualifiers::OCL_None:
3037 case Qualifiers::OCL_ExplicitNone:
3038 // okay
3039 break;
3040
3041 case Qualifiers::OCL_Weak:
3042 case Qualifiers::OCL_Strong:
3043 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003044 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003045 << ValType << FirstArg->getSourceRange();
3046 return ExprError();
3047 }
3048
John McCallb50451a2011-10-05 07:41:44 +00003049 // Strip any qualifiers off ValType.
3050 ValType = ValType.getUnqualifiedType();
3051
Chandler Carruth3973af72010-07-18 20:54:12 +00003052 // The majority of builtins return a value, but a few have special return
3053 // types, so allow them to override appropriately below.
3054 QualType ResultType = ValType;
3055
Chris Lattnerdc046542009-05-08 06:58:22 +00003056 // We need to figure out which concrete builtin this maps onto. For example,
3057 // __sync_fetch_and_add with a 2 byte object turns into
3058 // __sync_fetch_and_add_2.
3059#define BUILTIN_ROW(x) \
3060 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3061 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003062
Chris Lattnerdc046542009-05-08 06:58:22 +00003063 static const unsigned BuiltinIndices[][5] = {
3064 BUILTIN_ROW(__sync_fetch_and_add),
3065 BUILTIN_ROW(__sync_fetch_and_sub),
3066 BUILTIN_ROW(__sync_fetch_and_or),
3067 BUILTIN_ROW(__sync_fetch_and_and),
3068 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003069 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003070
Chris Lattnerdc046542009-05-08 06:58:22 +00003071 BUILTIN_ROW(__sync_add_and_fetch),
3072 BUILTIN_ROW(__sync_sub_and_fetch),
3073 BUILTIN_ROW(__sync_and_and_fetch),
3074 BUILTIN_ROW(__sync_or_and_fetch),
3075 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003076 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003077
Chris Lattnerdc046542009-05-08 06:58:22 +00003078 BUILTIN_ROW(__sync_val_compare_and_swap),
3079 BUILTIN_ROW(__sync_bool_compare_and_swap),
3080 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003081 BUILTIN_ROW(__sync_lock_release),
3082 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003083 };
Mike Stump11289f42009-09-09 15:08:12 +00003084#undef BUILTIN_ROW
3085
Chris Lattnerdc046542009-05-08 06:58:22 +00003086 // Determine the index of the size.
3087 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003088 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003089 case 1: SizeIndex = 0; break;
3090 case 2: SizeIndex = 1; break;
3091 case 4: SizeIndex = 2; break;
3092 case 8: SizeIndex = 3; break;
3093 case 16: SizeIndex = 4; break;
3094 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003095 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3096 << FirstArg->getType() << FirstArg->getSourceRange();
3097 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003098 }
Mike Stump11289f42009-09-09 15:08:12 +00003099
Chris Lattnerdc046542009-05-08 06:58:22 +00003100 // Each of these builtins has one pointer argument, followed by some number of
3101 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3102 // that we ignore. Find out which row of BuiltinIndices to read from as well
3103 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003104 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003105 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003106 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003107 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003108 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003109 case Builtin::BI__sync_fetch_and_add:
3110 case Builtin::BI__sync_fetch_and_add_1:
3111 case Builtin::BI__sync_fetch_and_add_2:
3112 case Builtin::BI__sync_fetch_and_add_4:
3113 case Builtin::BI__sync_fetch_and_add_8:
3114 case Builtin::BI__sync_fetch_and_add_16:
3115 BuiltinIndex = 0;
3116 break;
3117
3118 case Builtin::BI__sync_fetch_and_sub:
3119 case Builtin::BI__sync_fetch_and_sub_1:
3120 case Builtin::BI__sync_fetch_and_sub_2:
3121 case Builtin::BI__sync_fetch_and_sub_4:
3122 case Builtin::BI__sync_fetch_and_sub_8:
3123 case Builtin::BI__sync_fetch_and_sub_16:
3124 BuiltinIndex = 1;
3125 break;
3126
3127 case Builtin::BI__sync_fetch_and_or:
3128 case Builtin::BI__sync_fetch_and_or_1:
3129 case Builtin::BI__sync_fetch_and_or_2:
3130 case Builtin::BI__sync_fetch_and_or_4:
3131 case Builtin::BI__sync_fetch_and_or_8:
3132 case Builtin::BI__sync_fetch_and_or_16:
3133 BuiltinIndex = 2;
3134 break;
3135
3136 case Builtin::BI__sync_fetch_and_and:
3137 case Builtin::BI__sync_fetch_and_and_1:
3138 case Builtin::BI__sync_fetch_and_and_2:
3139 case Builtin::BI__sync_fetch_and_and_4:
3140 case Builtin::BI__sync_fetch_and_and_8:
3141 case Builtin::BI__sync_fetch_and_and_16:
3142 BuiltinIndex = 3;
3143 break;
Mike Stump11289f42009-09-09 15:08:12 +00003144
Douglas Gregor73722482011-11-28 16:30:08 +00003145 case Builtin::BI__sync_fetch_and_xor:
3146 case Builtin::BI__sync_fetch_and_xor_1:
3147 case Builtin::BI__sync_fetch_and_xor_2:
3148 case Builtin::BI__sync_fetch_and_xor_4:
3149 case Builtin::BI__sync_fetch_and_xor_8:
3150 case Builtin::BI__sync_fetch_and_xor_16:
3151 BuiltinIndex = 4;
3152 break;
3153
Hal Finkeld2208b52014-10-02 20:53:50 +00003154 case Builtin::BI__sync_fetch_and_nand:
3155 case Builtin::BI__sync_fetch_and_nand_1:
3156 case Builtin::BI__sync_fetch_and_nand_2:
3157 case Builtin::BI__sync_fetch_and_nand_4:
3158 case Builtin::BI__sync_fetch_and_nand_8:
3159 case Builtin::BI__sync_fetch_and_nand_16:
3160 BuiltinIndex = 5;
3161 WarnAboutSemanticsChange = true;
3162 break;
3163
Douglas Gregor73722482011-11-28 16:30:08 +00003164 case Builtin::BI__sync_add_and_fetch:
3165 case Builtin::BI__sync_add_and_fetch_1:
3166 case Builtin::BI__sync_add_and_fetch_2:
3167 case Builtin::BI__sync_add_and_fetch_4:
3168 case Builtin::BI__sync_add_and_fetch_8:
3169 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003170 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003171 break;
3172
3173 case Builtin::BI__sync_sub_and_fetch:
3174 case Builtin::BI__sync_sub_and_fetch_1:
3175 case Builtin::BI__sync_sub_and_fetch_2:
3176 case Builtin::BI__sync_sub_and_fetch_4:
3177 case Builtin::BI__sync_sub_and_fetch_8:
3178 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003179 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003180 break;
3181
3182 case Builtin::BI__sync_and_and_fetch:
3183 case Builtin::BI__sync_and_and_fetch_1:
3184 case Builtin::BI__sync_and_and_fetch_2:
3185 case Builtin::BI__sync_and_and_fetch_4:
3186 case Builtin::BI__sync_and_and_fetch_8:
3187 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003188 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003189 break;
3190
3191 case Builtin::BI__sync_or_and_fetch:
3192 case Builtin::BI__sync_or_and_fetch_1:
3193 case Builtin::BI__sync_or_and_fetch_2:
3194 case Builtin::BI__sync_or_and_fetch_4:
3195 case Builtin::BI__sync_or_and_fetch_8:
3196 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003197 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003198 break;
3199
3200 case Builtin::BI__sync_xor_and_fetch:
3201 case Builtin::BI__sync_xor_and_fetch_1:
3202 case Builtin::BI__sync_xor_and_fetch_2:
3203 case Builtin::BI__sync_xor_and_fetch_4:
3204 case Builtin::BI__sync_xor_and_fetch_8:
3205 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003206 BuiltinIndex = 10;
3207 break;
3208
3209 case Builtin::BI__sync_nand_and_fetch:
3210 case Builtin::BI__sync_nand_and_fetch_1:
3211 case Builtin::BI__sync_nand_and_fetch_2:
3212 case Builtin::BI__sync_nand_and_fetch_4:
3213 case Builtin::BI__sync_nand_and_fetch_8:
3214 case Builtin::BI__sync_nand_and_fetch_16:
3215 BuiltinIndex = 11;
3216 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003217 break;
Mike Stump11289f42009-09-09 15:08:12 +00003218
Chris Lattnerdc046542009-05-08 06:58:22 +00003219 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003220 case Builtin::BI__sync_val_compare_and_swap_1:
3221 case Builtin::BI__sync_val_compare_and_swap_2:
3222 case Builtin::BI__sync_val_compare_and_swap_4:
3223 case Builtin::BI__sync_val_compare_and_swap_8:
3224 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003225 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003226 NumFixed = 2;
3227 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003228
Chris Lattnerdc046542009-05-08 06:58:22 +00003229 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003230 case Builtin::BI__sync_bool_compare_and_swap_1:
3231 case Builtin::BI__sync_bool_compare_and_swap_2:
3232 case Builtin::BI__sync_bool_compare_and_swap_4:
3233 case Builtin::BI__sync_bool_compare_and_swap_8:
3234 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003235 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003236 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003237 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003238 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003239
3240 case Builtin::BI__sync_lock_test_and_set:
3241 case Builtin::BI__sync_lock_test_and_set_1:
3242 case Builtin::BI__sync_lock_test_and_set_2:
3243 case Builtin::BI__sync_lock_test_and_set_4:
3244 case Builtin::BI__sync_lock_test_and_set_8:
3245 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003246 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003247 break;
3248
Chris Lattnerdc046542009-05-08 06:58:22 +00003249 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003250 case Builtin::BI__sync_lock_release_1:
3251 case Builtin::BI__sync_lock_release_2:
3252 case Builtin::BI__sync_lock_release_4:
3253 case Builtin::BI__sync_lock_release_8:
3254 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003255 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003256 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003257 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003258 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003259
3260 case Builtin::BI__sync_swap:
3261 case Builtin::BI__sync_swap_1:
3262 case Builtin::BI__sync_swap_2:
3263 case Builtin::BI__sync_swap_4:
3264 case Builtin::BI__sync_swap_8:
3265 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003266 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003267 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003268 }
Mike Stump11289f42009-09-09 15:08:12 +00003269
Chris Lattnerdc046542009-05-08 06:58:22 +00003270 // Now that we know how many fixed arguments we expect, first check that we
3271 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003272 if (TheCall->getNumArgs() < 1+NumFixed) {
3273 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3274 << 0 << 1+NumFixed << TheCall->getNumArgs()
3275 << TheCall->getCallee()->getSourceRange();
3276 return ExprError();
3277 }
Mike Stump11289f42009-09-09 15:08:12 +00003278
Hal Finkeld2208b52014-10-02 20:53:50 +00003279 if (WarnAboutSemanticsChange) {
3280 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3281 << TheCall->getCallee()->getSourceRange();
3282 }
3283
Chris Lattner5b9241b2009-05-08 15:36:58 +00003284 // Get the decl for the concrete builtin from this, we can tell what the
3285 // concrete integer type we should convert to is.
3286 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003287 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003288 FunctionDecl *NewBuiltinDecl;
3289 if (NewBuiltinID == BuiltinID)
3290 NewBuiltinDecl = FDecl;
3291 else {
3292 // Perform builtin lookup to avoid redeclaring it.
3293 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3294 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3295 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3296 assert(Res.getFoundDecl());
3297 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003298 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003299 return ExprError();
3300 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003301
John McCallcf142162010-08-07 06:22:56 +00003302 // The first argument --- the pointer --- has a fixed type; we
3303 // deduce the types of the rest of the arguments accordingly. Walk
3304 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003305 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003306 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003307
Chris Lattnerdc046542009-05-08 06:58:22 +00003308 // GCC does an implicit conversion to the pointer or integer ValType. This
3309 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003310 // Initialize the argument.
3311 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3312 ValType, /*consume*/ false);
3313 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003314 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003315 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003316
Chris Lattnerdc046542009-05-08 06:58:22 +00003317 // Okay, we have something that *can* be converted to the right type. Check
3318 // to see if there is a potentially weird extension going on here. This can
3319 // happen when you do an atomic operation on something like an char* and
3320 // pass in 42. The 42 gets converted to char. This is even more strange
3321 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003322 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003323 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003324 }
Mike Stump11289f42009-09-09 15:08:12 +00003325
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003326 ASTContext& Context = this->getASTContext();
3327
3328 // Create a new DeclRefExpr to refer to the new decl.
3329 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3330 Context,
3331 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003332 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003333 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003334 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003335 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003336 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003337 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003338
Chris Lattnerdc046542009-05-08 06:58:22 +00003339 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003340 // FIXME: This loses syntactic information.
3341 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3342 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3343 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003344 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003345
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003346 // Change the result type of the call to match the original value type. This
3347 // is arbitrary, but the codegen for these builtins ins design to handle it
3348 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003349 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003350
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003351 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003352}
3353
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003354/// SemaBuiltinNontemporalOverloaded - We have a call to
3355/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3356/// overloaded function based on the pointer type of its last argument.
3357///
3358/// This function goes through and does final semantic checking for these
3359/// builtins.
3360ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3361 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3362 DeclRefExpr *DRE =
3363 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3364 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3365 unsigned BuiltinID = FDecl->getBuiltinID();
3366 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3367 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3368 "Unexpected nontemporal load/store builtin!");
3369 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3370 unsigned numArgs = isStore ? 2 : 1;
3371
3372 // Ensure that we have the proper number of arguments.
3373 if (checkArgCount(*this, TheCall, numArgs))
3374 return ExprError();
3375
3376 // Inspect the last argument of the nontemporal builtin. This should always
3377 // be a pointer type, from which we imply the type of the memory access.
3378 // Because it is a pointer type, we don't have to worry about any implicit
3379 // casts here.
3380 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3381 ExprResult PointerArgResult =
3382 DefaultFunctionArrayLvalueConversion(PointerArg);
3383
3384 if (PointerArgResult.isInvalid())
3385 return ExprError();
3386 PointerArg = PointerArgResult.get();
3387 TheCall->setArg(numArgs - 1, PointerArg);
3388
3389 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3390 if (!pointerType) {
3391 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3392 << PointerArg->getType() << PointerArg->getSourceRange();
3393 return ExprError();
3394 }
3395
3396 QualType ValType = pointerType->getPointeeType();
3397
3398 // Strip any qualifiers off ValType.
3399 ValType = ValType.getUnqualifiedType();
3400 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3401 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3402 !ValType->isVectorType()) {
3403 Diag(DRE->getLocStart(),
3404 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3405 << PointerArg->getType() << PointerArg->getSourceRange();
3406 return ExprError();
3407 }
3408
3409 if (!isStore) {
3410 TheCall->setType(ValType);
3411 return TheCallResult;
3412 }
3413
3414 ExprResult ValArg = TheCall->getArg(0);
3415 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3416 Context, ValType, /*consume*/ false);
3417 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3418 if (ValArg.isInvalid())
3419 return ExprError();
3420
3421 TheCall->setArg(0, ValArg.get());
3422 TheCall->setType(Context.VoidTy);
3423 return TheCallResult;
3424}
3425
Chris Lattner6436fb62009-02-18 06:01:06 +00003426/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003427/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003428/// Note: It might also make sense to do the UTF-16 conversion here (would
3429/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003430bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003431 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003432 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3433
Douglas Gregorfb65e592011-07-27 05:40:30 +00003434 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003435 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3436 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003437 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003438 }
Mike Stump11289f42009-09-09 15:08:12 +00003439
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003440 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003441 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003442 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00003443 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3444 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3445 llvm::UTF16 *ToPtr = &ToBuf[0];
3446
3447 llvm::ConversionResult Result =
3448 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3449 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003450 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00003451 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003452 Diag(Arg->getLocStart(),
3453 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3454 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003455 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003456}
3457
Mehdi Amini06d367c2016-10-24 20:39:34 +00003458/// CheckObjCString - Checks that the format string argument to the os_log()
3459/// and os_trace() functions is correct, and converts it to const char *.
3460ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3461 Arg = Arg->IgnoreParenCasts();
3462 auto *Literal = dyn_cast<StringLiteral>(Arg);
3463 if (!Literal) {
3464 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3465 Literal = ObjcLiteral->getString();
3466 }
3467 }
3468
3469 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3470 return ExprError(
3471 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3472 << Arg->getSourceRange());
3473 }
3474
3475 ExprResult Result(Literal);
3476 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3477 InitializedEntity Entity =
3478 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3479 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3480 return Result;
3481}
3482
Charles Davisc7d5c942015-09-17 20:55:33 +00003483/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3484/// for validity. Emit an error and return true on failure; return false
3485/// on success.
3486bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003487 Expr *Fn = TheCall->getCallee();
3488 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003489 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003490 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003491 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3492 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003493 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003494 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003495 return true;
3496 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003497
3498 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003499 return Diag(TheCall->getLocEnd(),
3500 diag::err_typecheck_call_too_few_args_at_least)
3501 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003502 }
3503
John McCall29ad95b2011-08-27 01:09:30 +00003504 // Type-check the first argument normally.
3505 if (checkBuiltinArgument(*this, TheCall, 0))
3506 return true;
3507
Chris Lattnere202e6a2007-12-20 00:05:45 +00003508 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00003509 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00003510 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00003511 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00003512 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00003513 else if (FunctionDecl *FD = getCurFunctionDecl())
3514 isVariadic = FD->isVariadic();
3515 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00003516 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00003517
Chris Lattnere202e6a2007-12-20 00:05:45 +00003518 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003519 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3520 return true;
3521 }
Mike Stump11289f42009-09-09 15:08:12 +00003522
Chris Lattner43be2e62007-12-19 23:59:04 +00003523 // Verify that the second argument to the builtin is the last argument of the
3524 // current function or method.
3525 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003526 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003527
Nico Weber9eea7642013-05-24 23:31:57 +00003528 // These are valid if SecondArgIsLastNamedArgument is false after the next
3529 // block.
3530 QualType Type;
3531 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003532 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003533
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003534 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3535 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003536 // FIXME: This isn't correct for methods (results in bogus warning).
3537 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003538 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00003539 if (CurBlock)
David Majnemera3debed2016-06-24 05:33:44 +00003540 LastArg = CurBlock->TheDecl->parameters().back();
Steve Naroff439a3e42009-04-15 19:33:47 +00003541 else if (FunctionDecl *FD = getCurFunctionDecl())
David Majnemera3debed2016-06-24 05:33:44 +00003542 LastArg = FD->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003543 else
David Majnemera3debed2016-06-24 05:33:44 +00003544 LastArg = getCurMethodDecl()->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003545 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00003546
3547 Type = PV->getType();
3548 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003549 IsCRegister =
3550 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003551 }
3552 }
Mike Stump11289f42009-09-09 15:08:12 +00003553
Chris Lattner43be2e62007-12-19 23:59:04 +00003554 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003555 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003556 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003557 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00003558 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3559 // Promotable integers are UB, but enumerations need a bit of
3560 // extra checking to see what their promotable type actually is.
3561 if (!Type->isPromotableIntegerType())
3562 return false;
3563 if (!Type->isEnumeralType())
3564 return true;
3565 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3566 return !(ED &&
3567 Context.typesAreCompatible(ED->getPromotionType(), Type));
3568 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00003569 unsigned Reason = 0;
3570 if (Type->isReferenceType()) Reason = 1;
3571 else if (IsCRegister) Reason = 2;
3572 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003573 Diag(ParamLoc, diag::note_parameter_type) << Type;
3574 }
3575
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003576 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003577 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003578}
Chris Lattner43be2e62007-12-19 23:59:04 +00003579
Charles Davisc7d5c942015-09-17 20:55:33 +00003580/// Check the arguments to '__builtin_va_start' for validity, and that
3581/// it was called from a function of the native ABI.
3582/// Emit an error and return true on failure; return false on success.
3583bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3584 // On x86-64 Unix, don't allow this in Win64 ABI functions.
3585 // On x64 Windows, don't allow this in System V ABI functions.
3586 // (Yes, that means there's no corresponding way to support variadic
3587 // System V ABI functions on Windows.)
3588 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3589 unsigned OS = Context.getTargetInfo().getTriple().getOS();
3590 clang::CallingConv CC = CC_C;
3591 if (const FunctionDecl *FD = getCurFunctionDecl())
3592 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3593 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3594 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3595 return Diag(TheCall->getCallee()->getLocStart(),
3596 diag::err_va_start_used_in_wrong_abi_function)
3597 << (OS != llvm::Triple::Win32);
3598 }
3599 return SemaBuiltinVAStartImpl(TheCall);
3600}
3601
3602/// Check the arguments to '__builtin_ms_va_start' for validity, and that
3603/// it was called from a Win64 ABI function.
3604/// Emit an error and return true on failure; return false on success.
3605bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3606 // This only makes sense for x86-64.
3607 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3608 Expr *Callee = TheCall->getCallee();
3609 if (TT.getArch() != llvm::Triple::x86_64)
3610 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3611 // Don't allow this in System V ABI functions.
3612 clang::CallingConv CC = CC_C;
3613 if (const FunctionDecl *FD = getCurFunctionDecl())
3614 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3615 if (CC == CC_X86_64SysV ||
3616 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3617 return Diag(Callee->getLocStart(),
3618 diag::err_ms_va_start_used_in_sysv_function);
3619 return SemaBuiltinVAStartImpl(TheCall);
3620}
3621
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003622bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3623 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3624 // const char *named_addr);
3625
3626 Expr *Func = Call->getCallee();
3627
3628 if (Call->getNumArgs() < 3)
3629 return Diag(Call->getLocEnd(),
3630 diag::err_typecheck_call_too_few_args_at_least)
3631 << 0 /*function call*/ << 3 << Call->getNumArgs();
3632
3633 // Determine whether the current function is variadic or not.
3634 bool IsVariadic;
3635 if (BlockScopeInfo *CurBlock = getCurBlock())
3636 IsVariadic = CurBlock->TheDecl->isVariadic();
3637 else if (FunctionDecl *FD = getCurFunctionDecl())
3638 IsVariadic = FD->isVariadic();
3639 else if (ObjCMethodDecl *MD = getCurMethodDecl())
3640 IsVariadic = MD->isVariadic();
3641 else
3642 llvm_unreachable("unexpected statement type");
3643
3644 if (!IsVariadic) {
3645 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3646 return true;
3647 }
3648
3649 // Type-check the first argument normally.
3650 if (checkBuiltinArgument(*this, Call, 0))
3651 return true;
3652
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003653 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003654 unsigned ArgNo;
3655 QualType Type;
3656 } ArgumentTypes[] = {
3657 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3658 { 2, Context.getSizeType() },
3659 };
3660
3661 for (const auto &AT : ArgumentTypes) {
3662 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3663 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3664 continue;
3665 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3666 << Arg->getType() << AT.Type << 1 /* different class */
3667 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3668 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3669 }
3670
3671 return false;
3672}
3673
Chris Lattner2da14fb2007-12-20 00:26:33 +00003674/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3675/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003676bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3677 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003678 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003679 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003680 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003681 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003682 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003683 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003684 << SourceRange(TheCall->getArg(2)->getLocStart(),
3685 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003686
John Wiegley01296292011-04-08 18:41:53 +00003687 ExprResult OrigArg0 = TheCall->getArg(0);
3688 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003689
Chris Lattner2da14fb2007-12-20 00:26:33 +00003690 // Do standard promotions between the two arguments, returning their common
3691 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003692 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003693 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3694 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003695
3696 // Make sure any conversions are pushed back into the call; this is
3697 // type safe since unordered compare builtins are declared as "_Bool
3698 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003699 TheCall->setArg(0, OrigArg0.get());
3700 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003701
John Wiegley01296292011-04-08 18:41:53 +00003702 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003703 return false;
3704
Chris Lattner2da14fb2007-12-20 00:26:33 +00003705 // If the common type isn't a real floating type, then the arguments were
3706 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003707 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00003708 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003709 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00003710 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3711 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003712
Chris Lattner2da14fb2007-12-20 00:26:33 +00003713 return false;
3714}
3715
Benjamin Kramer634fc102010-02-15 22:42:31 +00003716/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3717/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00003718/// to check everything. We expect the last argument to be a floating point
3719/// value.
3720bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3721 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00003722 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003723 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00003724 if (TheCall->getNumArgs() > NumArgs)
3725 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003726 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003727 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00003728 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003729 (*(TheCall->arg_end()-1))->getLocEnd());
3730
Benjamin Kramer64aae502010-02-16 10:07:31 +00003731 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00003732
Eli Friedman7e4faac2009-08-31 20:06:00 +00003733 if (OrigArg->isTypeDependent())
3734 return false;
3735
Chris Lattner68784ef2010-05-06 05:50:07 +00003736 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00003737 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00003738 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003739 diag::err_typecheck_call_invalid_unary_fp)
3740 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003741
Chris Lattner68784ef2010-05-06 05:50:07 +00003742 // If this is an implicit conversion from float -> double, remove it.
3743 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3744 Expr *CastArg = Cast->getSubExpr();
3745 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3746 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
3747 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00003748 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00003749 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00003750 }
3751 }
3752
Eli Friedman7e4faac2009-08-31 20:06:00 +00003753 return false;
3754}
3755
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003756/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3757// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00003758ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00003759 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003760 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00003761 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00003762 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3763 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003764
Nate Begemana0110022010-06-08 00:16:34 +00003765 // Determine which of the following types of shufflevector we're checking:
3766 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00003767 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00003768 QualType resType = TheCall->getArg(0)->getType();
3769 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00003770
Douglas Gregorc25f7662009-05-19 22:10:17 +00003771 if (!TheCall->getArg(0)->isTypeDependent() &&
3772 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00003773 QualType LHSType = TheCall->getArg(0)->getType();
3774 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00003775
Craig Topperbaca3892013-07-29 06:47:04 +00003776 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3777 return ExprError(Diag(TheCall->getLocStart(),
3778 diag::err_shufflevector_non_vector)
3779 << SourceRange(TheCall->getArg(0)->getLocStart(),
3780 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003781
Nate Begemana0110022010-06-08 00:16:34 +00003782 numElements = LHSType->getAs<VectorType>()->getNumElements();
3783 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00003784
Nate Begemana0110022010-06-08 00:16:34 +00003785 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3786 // with mask. If so, verify that RHS is an integer vector type with the
3787 // same number of elts as lhs.
3788 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00003789 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00003790 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00003791 return ExprError(Diag(TheCall->getLocStart(),
3792 diag::err_shufflevector_incompatible_vector)
3793 << SourceRange(TheCall->getArg(1)->getLocStart(),
3794 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003795 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00003796 return ExprError(Diag(TheCall->getLocStart(),
3797 diag::err_shufflevector_incompatible_vector)
3798 << SourceRange(TheCall->getArg(0)->getLocStart(),
3799 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00003800 } else if (numElements != numResElements) {
3801 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00003802 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003803 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003804 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003805 }
3806
3807 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00003808 if (TheCall->getArg(i)->isTypeDependent() ||
3809 TheCall->getArg(i)->isValueDependent())
3810 continue;
3811
Nate Begemana0110022010-06-08 00:16:34 +00003812 llvm::APSInt Result(32);
3813 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3814 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003815 diag::err_shufflevector_nonconstant_argument)
3816 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003817
Craig Topper50ad5b72013-08-03 17:40:38 +00003818 // Allow -1 which will be translated to undef in the IR.
3819 if (Result.isSigned() && Result.isAllOnesValue())
3820 continue;
3821
Chris Lattner7ab824e2008-08-10 02:05:13 +00003822 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003823 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003824 diag::err_shufflevector_argument_too_large)
3825 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003826 }
3827
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003828 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003829
Chris Lattner7ab824e2008-08-10 02:05:13 +00003830 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003831 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00003832 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003833 }
3834
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003835 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3836 TheCall->getCallee()->getLocStart(),
3837 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003838}
Chris Lattner43be2e62007-12-19 23:59:04 +00003839
Hal Finkelc4d7c822013-09-18 03:29:45 +00003840/// SemaConvertVectorExpr - Handle __builtin_convertvector
3841ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3842 SourceLocation BuiltinLoc,
3843 SourceLocation RParenLoc) {
3844 ExprValueKind VK = VK_RValue;
3845 ExprObjectKind OK = OK_Ordinary;
3846 QualType DstTy = TInfo->getType();
3847 QualType SrcTy = E->getType();
3848
3849 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3850 return ExprError(Diag(BuiltinLoc,
3851 diag::err_convertvector_non_vector)
3852 << E->getSourceRange());
3853 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3854 return ExprError(Diag(BuiltinLoc,
3855 diag::err_convertvector_non_vector_type));
3856
3857 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3858 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3859 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3860 if (SrcElts != DstElts)
3861 return ExprError(Diag(BuiltinLoc,
3862 diag::err_convertvector_incompatible_vector)
3863 << E->getSourceRange());
3864 }
3865
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003866 return new (Context)
3867 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003868}
3869
Daniel Dunbarb7257262008-07-21 22:59:13 +00003870/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3871// This is declared to take (const void*, ...) and can take two
3872// optional constant int args.
3873bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003874 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003875
Chris Lattner3b054132008-11-19 05:08:23 +00003876 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003877 return Diag(TheCall->getLocEnd(),
3878 diag::err_typecheck_call_too_many_args_at_most)
3879 << 0 /*function call*/ << 3 << NumArgs
3880 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003881
3882 // Argument 0 is checked for us and the remaining arguments must be
3883 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003884 for (unsigned i = 1; i != NumArgs; ++i)
3885 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003886 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003887
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003888 return false;
3889}
3890
Hal Finkelf0417332014-07-17 14:25:55 +00003891/// SemaBuiltinAssume - Handle __assume (MS Extension).
3892// __assume does not evaluate its arguments, and should warn if its argument
3893// has side effects.
3894bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3895 Expr *Arg = TheCall->getArg(0);
3896 if (Arg->isInstantiationDependent()) return false;
3897
3898 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003899 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003900 << Arg->getSourceRange()
3901 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3902
3903 return false;
3904}
3905
David Majnemer86b1bfa2016-10-31 18:07:57 +00003906/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00003907/// as (size_t, size_t) where the second size_t must be a power of 2 greater
3908/// than 8.
3909bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
3910 // The alignment must be a constant integer.
3911 Expr *Arg = TheCall->getArg(1);
3912
3913 // We can't check the value of a dependent argument.
3914 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00003915 if (const auto *UE =
3916 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
3917 if (UE->getKind() == UETT_AlignOf)
3918 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
3919 << Arg->getSourceRange();
3920
David Majnemer51169932016-10-31 05:37:48 +00003921 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
3922
3923 if (!Result.isPowerOf2())
3924 return Diag(TheCall->getLocStart(),
3925 diag::err_alignment_not_power_of_two)
3926 << Arg->getSourceRange();
3927
3928 if (Result < Context.getCharWidth())
3929 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
3930 << (unsigned)Context.getCharWidth()
3931 << Arg->getSourceRange();
3932
3933 if (Result > INT32_MAX)
3934 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
3935 << INT32_MAX
3936 << Arg->getSourceRange();
3937 }
3938
3939 return false;
3940}
3941
3942/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00003943/// as (const void*, size_t, ...) and can take one optional constant int arg.
3944bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3945 unsigned NumArgs = TheCall->getNumArgs();
3946
3947 if (NumArgs > 3)
3948 return Diag(TheCall->getLocEnd(),
3949 diag::err_typecheck_call_too_many_args_at_most)
3950 << 0 /*function call*/ << 3 << NumArgs
3951 << TheCall->getSourceRange();
3952
3953 // The alignment must be a constant integer.
3954 Expr *Arg = TheCall->getArg(1);
3955
3956 // We can't check the value of a dependent argument.
3957 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3958 llvm::APSInt Result;
3959 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3960 return true;
3961
3962 if (!Result.isPowerOf2())
3963 return Diag(TheCall->getLocStart(),
3964 diag::err_alignment_not_power_of_two)
3965 << Arg->getSourceRange();
3966 }
3967
3968 if (NumArgs > 2) {
3969 ExprResult Arg(TheCall->getArg(2));
3970 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3971 Context.getSizeType(), false);
3972 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3973 if (Arg.isInvalid()) return true;
3974 TheCall->setArg(2, Arg.get());
3975 }
Hal Finkelf0417332014-07-17 14:25:55 +00003976
3977 return false;
3978}
3979
Mehdi Amini06d367c2016-10-24 20:39:34 +00003980bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
3981 unsigned BuiltinID =
3982 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
3983 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
3984
3985 unsigned NumArgs = TheCall->getNumArgs();
3986 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
3987 if (NumArgs < NumRequiredArgs) {
3988 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3989 << 0 /* function call */ << NumRequiredArgs << NumArgs
3990 << TheCall->getSourceRange();
3991 }
3992 if (NumArgs >= NumRequiredArgs + 0x100) {
3993 return Diag(TheCall->getLocEnd(),
3994 diag::err_typecheck_call_too_many_args_at_most)
3995 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
3996 << TheCall->getSourceRange();
3997 }
3998 unsigned i = 0;
3999
4000 // For formatting call, check buffer arg.
4001 if (!IsSizeCall) {
4002 ExprResult Arg(TheCall->getArg(i));
4003 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4004 Context, Context.VoidPtrTy, false);
4005 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4006 if (Arg.isInvalid())
4007 return true;
4008 TheCall->setArg(i, Arg.get());
4009 i++;
4010 }
4011
4012 // Check string literal arg.
4013 unsigned FormatIdx = i;
4014 {
4015 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4016 if (Arg.isInvalid())
4017 return true;
4018 TheCall->setArg(i, Arg.get());
4019 i++;
4020 }
4021
4022 // Make sure variadic args are scalar.
4023 unsigned FirstDataArg = i;
4024 while (i < NumArgs) {
4025 ExprResult Arg = DefaultVariadicArgumentPromotion(
4026 TheCall->getArg(i), VariadicFunction, nullptr);
4027 if (Arg.isInvalid())
4028 return true;
4029 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4030 if (ArgSize.getQuantity() >= 0x100) {
4031 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4032 << i << (int)ArgSize.getQuantity() << 0xff
4033 << TheCall->getSourceRange();
4034 }
4035 TheCall->setArg(i, Arg.get());
4036 i++;
4037 }
4038
4039 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4040 // call to avoid duplicate diagnostics.
4041 if (!IsSizeCall) {
4042 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4043 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4044 bool Success = CheckFormatArguments(
4045 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4046 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4047 CheckedVarArgs);
4048 if (!Success)
4049 return true;
4050 }
4051
4052 if (IsSizeCall) {
4053 TheCall->setType(Context.getSizeType());
4054 } else {
4055 TheCall->setType(Context.VoidPtrTy);
4056 }
4057 return false;
4058}
4059
Eric Christopher8d0c6212010-04-17 02:26:23 +00004060/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4061/// TheCall is a constant expression.
4062bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4063 llvm::APSInt &Result) {
4064 Expr *Arg = TheCall->getArg(ArgNum);
4065 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4066 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4067
4068 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4069
4070 if (!Arg->isIntegerConstantExpr(Result, Context))
4071 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004072 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004073
Chris Lattnerd545ad12009-09-23 06:06:36 +00004074 return false;
4075}
4076
Richard Sandiford28940af2014-04-16 08:47:51 +00004077/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4078/// TheCall is a constant expression in the range [Low, High].
4079bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4080 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004081 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004082
4083 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004084 Expr *Arg = TheCall->getArg(ArgNum);
4085 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004086 return false;
4087
Eric Christopher8d0c6212010-04-17 02:26:23 +00004088 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004089 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004090 return true;
4091
Richard Sandiford28940af2014-04-16 08:47:51 +00004092 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004093 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004094 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004095
4096 return false;
4097}
4098
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004099/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4100/// TheCall is a constant expression is a multiple of Num..
4101bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4102 unsigned Num) {
4103 llvm::APSInt Result;
4104
4105 // We can't check the value of a dependent argument.
4106 Expr *Arg = TheCall->getArg(ArgNum);
4107 if (Arg->isTypeDependent() || Arg->isValueDependent())
4108 return false;
4109
4110 // Check constant-ness first.
4111 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4112 return true;
4113
4114 if (Result.getSExtValue() % Num != 0)
4115 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4116 << Num << Arg->getSourceRange();
4117
4118 return false;
4119}
4120
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004121/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4122/// TheCall is an ARM/AArch64 special register string literal.
4123bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4124 int ArgNum, unsigned ExpectedFieldNum,
4125 bool AllowName) {
4126 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4127 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4128 BuiltinID == ARM::BI__builtin_arm_rsr ||
4129 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4130 BuiltinID == ARM::BI__builtin_arm_wsr ||
4131 BuiltinID == ARM::BI__builtin_arm_wsrp;
4132 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4133 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4134 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4135 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4136 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4137 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4138 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4139
4140 // We can't check the value of a dependent argument.
4141 Expr *Arg = TheCall->getArg(ArgNum);
4142 if (Arg->isTypeDependent() || Arg->isValueDependent())
4143 return false;
4144
4145 // Check if the argument is a string literal.
4146 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4147 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4148 << Arg->getSourceRange();
4149
4150 // Check the type of special register given.
4151 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4152 SmallVector<StringRef, 6> Fields;
4153 Reg.split(Fields, ":");
4154
4155 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4156 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4157 << Arg->getSourceRange();
4158
4159 // If the string is the name of a register then we cannot check that it is
4160 // valid here but if the string is of one the forms described in ACLE then we
4161 // can check that the supplied fields are integers and within the valid
4162 // ranges.
4163 if (Fields.size() > 1) {
4164 bool FiveFields = Fields.size() == 5;
4165
4166 bool ValidString = true;
4167 if (IsARMBuiltin) {
4168 ValidString &= Fields[0].startswith_lower("cp") ||
4169 Fields[0].startswith_lower("p");
4170 if (ValidString)
4171 Fields[0] =
4172 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4173
4174 ValidString &= Fields[2].startswith_lower("c");
4175 if (ValidString)
4176 Fields[2] = Fields[2].drop_front(1);
4177
4178 if (FiveFields) {
4179 ValidString &= Fields[3].startswith_lower("c");
4180 if (ValidString)
4181 Fields[3] = Fields[3].drop_front(1);
4182 }
4183 }
4184
4185 SmallVector<int, 5> Ranges;
4186 if (FiveFields)
4187 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
4188 else
4189 Ranges.append({15, 7, 15});
4190
4191 for (unsigned i=0; i<Fields.size(); ++i) {
4192 int IntField;
4193 ValidString &= !Fields[i].getAsInteger(10, IntField);
4194 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4195 }
4196
4197 if (!ValidString)
4198 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4199 << Arg->getSourceRange();
4200
4201 } else if (IsAArch64Builtin && Fields.size() == 1) {
4202 // If the register name is one of those that appear in the condition below
4203 // and the special register builtin being used is one of the write builtins,
4204 // then we require that the argument provided for writing to the register
4205 // is an integer constant expression. This is because it will be lowered to
4206 // an MSR (immediate) instruction, so we need to know the immediate at
4207 // compile time.
4208 if (TheCall->getNumArgs() != 2)
4209 return false;
4210
4211 std::string RegLower = Reg.lower();
4212 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4213 RegLower != "pan" && RegLower != "uao")
4214 return false;
4215
4216 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4217 }
4218
4219 return false;
4220}
4221
Eli Friedmanc97d0142009-05-03 06:04:26 +00004222/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004223/// This checks that the target supports __builtin_longjmp and
4224/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004225bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004226 if (!Context.getTargetInfo().hasSjLjLowering())
4227 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4228 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4229
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004230 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004231 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004232
Eric Christopher8d0c6212010-04-17 02:26:23 +00004233 // TODO: This is less than ideal. Overload this to take a value.
4234 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4235 return true;
4236
4237 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004238 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4239 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4240
4241 return false;
4242}
4243
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004244/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4245/// This checks that the target supports __builtin_setjmp.
4246bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4247 if (!Context.getTargetInfo().hasSjLjLowering())
4248 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4249 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4250 return false;
4251}
4252
Richard Smithd7293d72013-08-05 18:49:43 +00004253namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004254class UncoveredArgHandler {
4255 enum { Unknown = -1, AllCovered = -2 };
4256 signed FirstUncoveredArg;
4257 SmallVector<const Expr *, 4> DiagnosticExprs;
4258
4259public:
4260 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4261
4262 bool hasUncoveredArg() const {
4263 return (FirstUncoveredArg >= 0);
4264 }
4265
4266 unsigned getUncoveredArg() const {
4267 assert(hasUncoveredArg() && "no uncovered argument");
4268 return FirstUncoveredArg;
4269 }
4270
4271 void setAllCovered() {
4272 // A string has been found with all arguments covered, so clear out
4273 // the diagnostics.
4274 DiagnosticExprs.clear();
4275 FirstUncoveredArg = AllCovered;
4276 }
4277
4278 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4279 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4280
4281 // Don't update if a previous string covers all arguments.
4282 if (FirstUncoveredArg == AllCovered)
4283 return;
4284
4285 // UncoveredArgHandler tracks the highest uncovered argument index
4286 // and with it all the strings that match this index.
4287 if (NewFirstUncoveredArg == FirstUncoveredArg)
4288 DiagnosticExprs.push_back(StrExpr);
4289 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4290 DiagnosticExprs.clear();
4291 DiagnosticExprs.push_back(StrExpr);
4292 FirstUncoveredArg = NewFirstUncoveredArg;
4293 }
4294 }
4295
4296 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4297};
4298
Richard Smithd7293d72013-08-05 18:49:43 +00004299enum StringLiteralCheckType {
4300 SLCT_NotALiteral,
4301 SLCT_UncheckedLiteral,
4302 SLCT_CheckedLiteral
4303};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004304} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00004305
Stephen Hines648c3692016-09-16 01:07:04 +00004306static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4307 BinaryOperatorKind BinOpKind,
4308 bool AddendIsRight) {
4309 unsigned BitWidth = Offset.getBitWidth();
4310 unsigned AddendBitWidth = Addend.getBitWidth();
4311 // There might be negative interim results.
4312 if (Addend.isUnsigned()) {
4313 Addend = Addend.zext(++AddendBitWidth);
4314 Addend.setIsSigned(true);
4315 }
4316 // Adjust the bit width of the APSInts.
4317 if (AddendBitWidth > BitWidth) {
4318 Offset = Offset.sext(AddendBitWidth);
4319 BitWidth = AddendBitWidth;
4320 } else if (BitWidth > AddendBitWidth) {
4321 Addend = Addend.sext(BitWidth);
4322 }
4323
4324 bool Ov = false;
4325 llvm::APSInt ResOffset = Offset;
4326 if (BinOpKind == BO_Add)
4327 ResOffset = Offset.sadd_ov(Addend, Ov);
4328 else {
4329 assert(AddendIsRight && BinOpKind == BO_Sub &&
4330 "operator must be add or sub with addend on the right");
4331 ResOffset = Offset.ssub_ov(Addend, Ov);
4332 }
4333
4334 // We add an offset to a pointer here so we should support an offset as big as
4335 // possible.
4336 if (Ov) {
4337 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00004338 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00004339 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4340 return;
4341 }
4342
4343 Offset = ResOffset;
4344}
4345
4346namespace {
4347// This is a wrapper class around StringLiteral to support offsetted string
4348// literals as format strings. It takes the offset into account when returning
4349// the string and its length or the source locations to display notes correctly.
4350class FormatStringLiteral {
4351 const StringLiteral *FExpr;
4352 int64_t Offset;
4353
4354 public:
4355 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4356 : FExpr(fexpr), Offset(Offset) {}
4357
4358 StringRef getString() const {
4359 return FExpr->getString().drop_front(Offset);
4360 }
4361
4362 unsigned getByteLength() const {
4363 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4364 }
4365 unsigned getLength() const { return FExpr->getLength() - Offset; }
4366 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4367
4368 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4369
4370 QualType getType() const { return FExpr->getType(); }
4371
4372 bool isAscii() const { return FExpr->isAscii(); }
4373 bool isWide() const { return FExpr->isWide(); }
4374 bool isUTF8() const { return FExpr->isUTF8(); }
4375 bool isUTF16() const { return FExpr->isUTF16(); }
4376 bool isUTF32() const { return FExpr->isUTF32(); }
4377 bool isPascal() const { return FExpr->isPascal(); }
4378
4379 SourceLocation getLocationOfByte(
4380 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4381 const TargetInfo &Target, unsigned *StartToken = nullptr,
4382 unsigned *StartTokenByteOffset = nullptr) const {
4383 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4384 StartToken, StartTokenByteOffset);
4385 }
4386
4387 SourceLocation getLocStart() const LLVM_READONLY {
4388 return FExpr->getLocStart().getLocWithOffset(Offset);
4389 }
4390 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4391};
4392} // end anonymous namespace
4393
4394static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004395 const Expr *OrigFormatExpr,
4396 ArrayRef<const Expr *> Args,
4397 bool HasVAListArg, unsigned format_idx,
4398 unsigned firstDataArg,
4399 Sema::FormatStringType Type,
4400 bool inFunctionCall,
4401 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004402 llvm::SmallBitVector &CheckedVarArgs,
4403 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004404
Richard Smith55ce3522012-06-25 20:30:08 +00004405// Determine if an expression is a string literal or constant string.
4406// If this function returns false on the arguments to a function expecting a
4407// format string, we will usually need to emit a warning.
4408// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00004409static StringLiteralCheckType
4410checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4411 bool HasVAListArg, unsigned format_idx,
4412 unsigned firstDataArg, Sema::FormatStringType Type,
4413 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004414 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004415 UncoveredArgHandler &UncoveredArg,
4416 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00004417 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00004418 assert(Offset.isSigned() && "invalid offset");
4419
Douglas Gregorc25f7662009-05-19 22:10:17 +00004420 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00004421 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004422
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004423 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00004424
Richard Smithd7293d72013-08-05 18:49:43 +00004425 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00004426 // Technically -Wformat-nonliteral does not warn about this case.
4427 // The behavior of printf and friends in this case is implementation
4428 // dependent. Ideally if the format string cannot be null then
4429 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00004430 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00004431
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004432 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00004433 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004434 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00004435 // The expression is a literal if both sub-expressions were, and it was
4436 // completely checked only if both sub-expressions were checked.
4437 const AbstractConditionalOperator *C =
4438 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004439
4440 // Determine whether it is necessary to check both sub-expressions, for
4441 // example, because the condition expression is a constant that can be
4442 // evaluated at compile time.
4443 bool CheckLeft = true, CheckRight = true;
4444
4445 bool Cond;
4446 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4447 if (Cond)
4448 CheckRight = false;
4449 else
4450 CheckLeft = false;
4451 }
4452
Stephen Hines648c3692016-09-16 01:07:04 +00004453 // We need to maintain the offsets for the right and the left hand side
4454 // separately to check if every possible indexed expression is a valid
4455 // string literal. They might have different offsets for different string
4456 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004457 StringLiteralCheckType Left;
4458 if (!CheckLeft)
4459 Left = SLCT_UncheckedLiteral;
4460 else {
4461 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4462 HasVAListArg, format_idx, firstDataArg,
4463 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004464 CheckedVarArgs, UncoveredArg, Offset);
4465 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004466 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004467 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004468 }
4469
Richard Smith55ce3522012-06-25 20:30:08 +00004470 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004471 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004472 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004473 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004474 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004475
4476 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004477 }
4478
4479 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00004480 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4481 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004482 }
4483
John McCallc07a0c72011-02-17 10:25:35 +00004484 case Stmt::OpaqueValueExprClass:
4485 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4486 E = src;
4487 goto tryAgain;
4488 }
Richard Smith55ce3522012-06-25 20:30:08 +00004489 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004490
Ted Kremeneka8890832011-02-24 23:03:04 +00004491 case Stmt::PredefinedExprClass:
4492 // While __func__, etc., are technically not string literals, they
4493 // cannot contain format specifiers and thus are not a security
4494 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004495 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004496
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004497 case Stmt::DeclRefExprClass: {
4498 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004499
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004500 // As an exception, do not flag errors for variables binding to
4501 // const string literals.
4502 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4503 bool isConstant = false;
4504 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004505
Richard Smithd7293d72013-08-05 18:49:43 +00004506 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4507 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004508 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004509 isConstant = T.isConstant(S.Context) &&
4510 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004511 } else if (T->isObjCObjectPointerType()) {
4512 // In ObjC, there is usually no "const ObjectPointer" type,
4513 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004514 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004515 }
Mike Stump11289f42009-09-09 15:08:12 +00004516
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004517 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004518 if (const Expr *Init = VD->getAnyInitializer()) {
4519 // Look through initializers like const char c[] = { "foo" }
4520 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4521 if (InitList->isStringLiteralInit())
4522 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4523 }
Richard Smithd7293d72013-08-05 18:49:43 +00004524 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004525 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004526 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004527 /*InFunctionCall*/ false, CheckedVarArgs,
4528 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004529 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004530 }
Mike Stump11289f42009-09-09 15:08:12 +00004531
Anders Carlssonb012ca92009-06-28 19:55:58 +00004532 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4533 // special check to see if the format string is a function parameter
4534 // of the function calling the printf function. If the function
4535 // has an attribute indicating it is a printf-like function, then we
4536 // should suppress warnings concerning non-literals being used in a call
4537 // to a vprintf function. For example:
4538 //
4539 // void
4540 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4541 // va_list ap;
4542 // va_start(ap, fmt);
4543 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4544 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00004545 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004546 if (HasVAListArg) {
4547 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4548 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4549 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004550 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004551 // adjust for implicit parameter
4552 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4553 if (MD->isInstance())
4554 ++PVIndex;
4555 // We also check if the formats are compatible.
4556 // We can't pass a 'scanf' string to a 'printf' function.
4557 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00004558 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00004559 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004560 }
4561 }
4562 }
4563 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004564 }
Mike Stump11289f42009-09-09 15:08:12 +00004565
Richard Smith55ce3522012-06-25 20:30:08 +00004566 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004567 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004568
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004569 case Stmt::CallExprClass:
4570 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004571 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004572 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4573 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4574 unsigned ArgIndex = FA->getFormatIdx();
4575 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4576 if (MD->isInstance())
4577 --ArgIndex;
4578 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00004579
Richard Smithd7293d72013-08-05 18:49:43 +00004580 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004581 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00004582 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004583 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004584 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4585 unsigned BuiltinID = FD->getBuiltinID();
4586 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4587 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4588 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00004589 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004590 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004591 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004592 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004593 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004594 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004595 }
4596 }
Mike Stump11289f42009-09-09 15:08:12 +00004597
Richard Smith55ce3522012-06-25 20:30:08 +00004598 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004599 }
Alex Lorenzd9007142016-10-24 09:42:34 +00004600 case Stmt::ObjCMessageExprClass: {
4601 const auto *ME = cast<ObjCMessageExpr>(E);
4602 if (const auto *ND = ME->getMethodDecl()) {
4603 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4604 unsigned ArgIndex = FA->getFormatIdx();
4605 const Expr *Arg = ME->getArg(ArgIndex - 1);
4606 return checkFormatStringExpr(
4607 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4608 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4609 }
4610 }
4611
4612 return SLCT_NotALiteral;
4613 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004614 case Stmt::ObjCStringLiteralClass:
4615 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00004616 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004617
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004618 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004619 StrE = ObjCFExpr->getString();
4620 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004621 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004622
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004623 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00004624 if (Offset.isNegative() || Offset > StrE->getLength()) {
4625 // TODO: It would be better to have an explicit warning for out of
4626 // bounds literals.
4627 return SLCT_NotALiteral;
4628 }
4629 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4630 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004631 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004632 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00004633 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004634 }
Mike Stump11289f42009-09-09 15:08:12 +00004635
Richard Smith55ce3522012-06-25 20:30:08 +00004636 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004637 }
Stephen Hines648c3692016-09-16 01:07:04 +00004638 case Stmt::BinaryOperatorClass: {
4639 llvm::APSInt LResult;
4640 llvm::APSInt RResult;
4641
4642 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4643
4644 // A string literal + an int offset is still a string literal.
4645 if (BinOp->isAdditiveOp()) {
4646 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4647 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4648
4649 if (LIsInt != RIsInt) {
4650 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4651
4652 if (LIsInt) {
4653 if (BinOpKind == BO_Add) {
4654 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4655 E = BinOp->getRHS();
4656 goto tryAgain;
4657 }
4658 } else {
4659 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4660 E = BinOp->getLHS();
4661 goto tryAgain;
4662 }
4663 }
Stephen Hines648c3692016-09-16 01:07:04 +00004664 }
George Burgess IVd273aab2016-09-22 00:00:26 +00004665
4666 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00004667 }
4668 case Stmt::UnaryOperatorClass: {
4669 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4670 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4671 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4672 llvm::APSInt IndexResult;
4673 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4674 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4675 E = ASE->getBase();
4676 goto tryAgain;
4677 }
4678 }
4679
4680 return SLCT_NotALiteral;
4681 }
Mike Stump11289f42009-09-09 15:08:12 +00004682
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004683 default:
Richard Smith55ce3522012-06-25 20:30:08 +00004684 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004685 }
4686}
4687
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004688Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00004689 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00004690 .Case("scanf", FST_Scanf)
4691 .Cases("printf", "printf0", FST_Printf)
4692 .Cases("NSString", "CFString", FST_NSString)
4693 .Case("strftime", FST_Strftime)
4694 .Case("strfmon", FST_Strfmon)
4695 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4696 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4697 .Case("os_trace", FST_OSLog)
4698 .Case("os_log", FST_OSLog)
4699 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004700}
4701
Jordan Rose3e0ec582012-07-19 18:10:23 +00004702/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00004703/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00004704/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004705bool Sema::CheckFormatArguments(const FormatAttr *Format,
4706 ArrayRef<const Expr *> Args,
4707 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004708 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004709 SourceLocation Loc, SourceRange Range,
4710 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00004711 FormatStringInfo FSI;
4712 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004713 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00004714 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00004715 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00004716 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004717}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00004718
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004719bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004720 bool HasVAListArg, unsigned format_idx,
4721 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004722 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004723 SourceLocation Loc, SourceRange Range,
4724 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004725 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004726 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004727 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00004728 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004729 }
Mike Stump11289f42009-09-09 15:08:12 +00004730
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004731 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004732
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004733 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00004734 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004735 // Dynamically generated format strings are difficult to
4736 // automatically vet at compile time. Requiring that format strings
4737 // are string literals: (1) permits the checking of format strings by
4738 // the compiler and thereby (2) can practically remove the source of
4739 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00004740
Mike Stump11289f42009-09-09 15:08:12 +00004741 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00004742 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00004743 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00004744 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004745 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00004746 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00004747 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4748 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004749 /*IsFunctionCall*/ true, CheckedVarArgs,
4750 UncoveredArg,
4751 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004752
4753 // Generate a diagnostic where an uncovered argument is detected.
4754 if (UncoveredArg.hasUncoveredArg()) {
4755 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4756 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4757 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4758 }
4759
Richard Smith55ce3522012-06-25 20:30:08 +00004760 if (CT != SLCT_NotALiteral)
4761 // Literal format string found, check done!
4762 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00004763
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004764 // Strftime is particular as it always uses a single 'time' argument,
4765 // so it is safe to pass a non-literal string.
4766 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00004767 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004768
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004769 // Do not emit diag when the string param is a macro expansion and the
4770 // format is either NSString or CFString. This is a hack to prevent
4771 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4772 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004773 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4774 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00004775 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004776
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004777 // If there are no arguments specified, warn with -Wformat-security, otherwise
4778 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004779 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00004780 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4781 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004782 switch (Type) {
4783 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004784 break;
4785 case FST_Kprintf:
4786 case FST_FreeBSDKPrintf:
4787 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00004788 Diag(FormatLoc, diag::note_format_security_fixit)
4789 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004790 break;
4791 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00004792 Diag(FormatLoc, diag::note_format_security_fixit)
4793 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004794 break;
4795 }
4796 } else {
4797 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004798 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004799 }
Richard Smith55ce3522012-06-25 20:30:08 +00004800 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004801}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004802
Ted Kremenekab278de2010-01-28 23:39:18 +00004803namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00004804class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4805protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00004806 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00004807 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00004808 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00004809 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00004810 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00004811 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00004812 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00004813 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004814 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00004815 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00004816 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00004817 bool usesPositionalArgs;
4818 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004819 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00004820 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00004821 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004822 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004823
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004824public:
Stephen Hines648c3692016-09-16 01:07:04 +00004825 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00004826 const Expr *origFormatExpr,
4827 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004828 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00004829 ArrayRef<const Expr *> Args, unsigned formatIdx,
4830 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004831 llvm::SmallBitVector &CheckedVarArgs,
4832 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00004833 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
4834 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
4835 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
4836 usesPositionalArgs(false), atFirstArg(true),
4837 inFunctionCall(inFunctionCall), CallType(callType),
4838 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00004839 CoveredArgs.resize(numDataArgs);
4840 CoveredArgs.reset();
4841 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004842
Ted Kremenek019d2242010-01-29 01:50:07 +00004843 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004844
Ted Kremenek02087932010-07-16 02:11:22 +00004845 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004846 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004847
Jordan Rose92303592012-09-08 04:00:03 +00004848 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004849 const analyze_format_string::FormatSpecifier &FS,
4850 const analyze_format_string::ConversionSpecifier &CS,
4851 const char *startSpecifier, unsigned specifierLen,
4852 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00004853
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004854 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004855 const analyze_format_string::FormatSpecifier &FS,
4856 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004857
4858 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004859 const analyze_format_string::ConversionSpecifier &CS,
4860 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004861
Craig Toppere14c0f82014-03-12 04:55:44 +00004862 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004863
Craig Toppere14c0f82014-03-12 04:55:44 +00004864 void HandleInvalidPosition(const char *startSpecifier,
4865 unsigned specifierLen,
4866 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004867
Craig Toppere14c0f82014-03-12 04:55:44 +00004868 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004869
Craig Toppere14c0f82014-03-12 04:55:44 +00004870 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004871
Richard Trieu03cf7b72011-10-28 00:41:25 +00004872 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00004873 static void
4874 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4875 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4876 bool IsStringLocation, Range StringRange,
4877 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004878
Ted Kremenek02087932010-07-16 02:11:22 +00004879protected:
Ted Kremenekce815422010-07-19 21:25:57 +00004880 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4881 const char *startSpec,
4882 unsigned specifierLen,
4883 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004884
4885 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4886 const char *startSpec,
4887 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00004888
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004889 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00004890 CharSourceRange getSpecifierRange(const char *startSpecifier,
4891 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00004892 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004893
Ted Kremenek5739de72010-01-29 01:06:55 +00004894 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004895
4896 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4897 const analyze_format_string::ConversionSpecifier &CS,
4898 const char *startSpecifier, unsigned specifierLen,
4899 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004900
4901 template <typename Range>
4902 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4903 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004904 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00004905};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004906} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004907
Ted Kremenek02087932010-07-16 02:11:22 +00004908SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00004909 return OrigFormatExpr->getSourceRange();
4910}
4911
Ted Kremenek02087932010-07-16 02:11:22 +00004912CharSourceRange CheckFormatHandler::
4913getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00004914 SourceLocation Start = getLocationOfByte(startSpecifier);
4915 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
4916
4917 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004918 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00004919
4920 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004921}
4922
Ted Kremenek02087932010-07-16 02:11:22 +00004923SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00004924 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
4925 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00004926}
4927
Ted Kremenek02087932010-07-16 02:11:22 +00004928void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4929 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00004930 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4931 getLocationOfByte(startSpecifier),
4932 /*IsStringLocation*/true,
4933 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00004934}
4935
Jordan Rose92303592012-09-08 04:00:03 +00004936void CheckFormatHandler::HandleInvalidLengthModifier(
4937 const analyze_format_string::FormatSpecifier &FS,
4938 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00004939 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00004940 using namespace analyze_format_string;
4941
4942 const LengthModifier &LM = FS.getLengthModifier();
4943 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4944
4945 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004946 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00004947 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004948 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004949 getLocationOfByte(LM.getStart()),
4950 /*IsStringLocation*/true,
4951 getSpecifierRange(startSpecifier, specifierLen));
4952
4953 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4954 << FixedLM->toString()
4955 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4956
4957 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004958 FixItHint Hint;
4959 if (DiagID == diag::warn_format_nonsensical_length)
4960 Hint = FixItHint::CreateRemoval(LMRange);
4961
4962 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004963 getLocationOfByte(LM.getStart()),
4964 /*IsStringLocation*/true,
4965 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00004966 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00004967 }
4968}
4969
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004970void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00004971 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004972 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004973 using namespace analyze_format_string;
4974
4975 const LengthModifier &LM = FS.getLengthModifier();
4976 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4977
4978 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004979 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00004980 if (FixedLM) {
4981 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4982 << LM.toString() << 0,
4983 getLocationOfByte(LM.getStart()),
4984 /*IsStringLocation*/true,
4985 getSpecifierRange(startSpecifier, specifierLen));
4986
4987 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4988 << FixedLM->toString()
4989 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4990
4991 } else {
4992 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4993 << LM.toString() << 0,
4994 getLocationOfByte(LM.getStart()),
4995 /*IsStringLocation*/true,
4996 getSpecifierRange(startSpecifier, specifierLen));
4997 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004998}
4999
5000void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5001 const analyze_format_string::ConversionSpecifier &CS,
5002 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005003 using namespace analyze_format_string;
5004
5005 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005006 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005007 if (FixedCS) {
5008 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5009 << CS.toString() << /*conversion specifier*/1,
5010 getLocationOfByte(CS.getStart()),
5011 /*IsStringLocation*/true,
5012 getSpecifierRange(startSpecifier, specifierLen));
5013
5014 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5015 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5016 << FixedCS->toString()
5017 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5018 } else {
5019 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5020 << CS.toString() << /*conversion specifier*/1,
5021 getLocationOfByte(CS.getStart()),
5022 /*IsStringLocation*/true,
5023 getSpecifierRange(startSpecifier, specifierLen));
5024 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005025}
5026
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005027void CheckFormatHandler::HandlePosition(const char *startPos,
5028 unsigned posLen) {
5029 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5030 getLocationOfByte(startPos),
5031 /*IsStringLocation*/true,
5032 getSpecifierRange(startPos, posLen));
5033}
5034
Ted Kremenekd1668192010-02-27 01:41:03 +00005035void
Ted Kremenek02087932010-07-16 02:11:22 +00005036CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5037 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005038 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5039 << (unsigned) p,
5040 getLocationOfByte(startPos), /*IsStringLocation*/true,
5041 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005042}
5043
Ted Kremenek02087932010-07-16 02:11:22 +00005044void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005045 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005046 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5047 getLocationOfByte(startPos),
5048 /*IsStringLocation*/true,
5049 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005050}
5051
Ted Kremenek02087932010-07-16 02:11:22 +00005052void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005053 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005054 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005055 EmitFormatDiagnostic(
5056 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5057 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5058 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005059 }
Ted Kremenek02087932010-07-16 02:11:22 +00005060}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005061
Jordan Rose58bbe422012-07-19 18:10:08 +00005062// Note that this may return NULL if there was an error parsing or building
5063// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005064const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005065 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005066}
5067
5068void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005069 // Does the number of data arguments exceed the number of
5070 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005071 if (!HasVAListArg) {
5072 // Find any arguments that weren't covered.
5073 CoveredArgs.flip();
5074 signed notCoveredArg = CoveredArgs.find_first();
5075 if (notCoveredArg >= 0) {
5076 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005077 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5078 } else {
5079 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005080 }
5081 }
5082}
5083
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005084void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5085 const Expr *ArgExpr) {
5086 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5087 "Invalid state");
5088
5089 if (!ArgExpr)
5090 return;
5091
5092 SourceLocation Loc = ArgExpr->getLocStart();
5093
5094 if (S.getSourceManager().isInSystemMacro(Loc))
5095 return;
5096
5097 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5098 for (auto E : DiagnosticExprs)
5099 PDiag << E->getSourceRange();
5100
5101 CheckFormatHandler::EmitFormatDiagnostic(
5102 S, IsFunctionCall, DiagnosticExprs[0],
5103 PDiag, Loc, /*IsStringLocation*/false,
5104 DiagnosticExprs[0]->getSourceRange());
5105}
5106
Ted Kremenekce815422010-07-19 21:25:57 +00005107bool
5108CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5109 SourceLocation Loc,
5110 const char *startSpec,
5111 unsigned specifierLen,
5112 const char *csStart,
5113 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005114 bool keepGoing = true;
5115 if (argIndex < NumDataArgs) {
5116 // Consider the argument coverered, even though the specifier doesn't
5117 // make sense.
5118 CoveredArgs.set(argIndex);
5119 }
5120 else {
5121 // If argIndex exceeds the number of data arguments we
5122 // don't issue a warning because that is just a cascade of warnings (and
5123 // they may have intended '%%' anyway). We don't want to continue processing
5124 // the format string after this point, however, as we will like just get
5125 // gibberish when trying to match arguments.
5126 keepGoing = false;
5127 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005128
5129 StringRef Specifier(csStart, csLen);
5130
5131 // If the specifier in non-printable, it could be the first byte of a UTF-8
5132 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5133 // hex value.
5134 std::string CodePointStr;
5135 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005136 llvm::UTF32 CodePoint;
5137 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5138 const llvm::UTF8 *E =
5139 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5140 llvm::ConversionResult Result =
5141 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005142
Justin Lebar90910552016-09-30 00:38:45 +00005143 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005144 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005145 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005146 }
5147
5148 llvm::raw_string_ostream OS(CodePointStr);
5149 if (CodePoint < 256)
5150 OS << "\\x" << llvm::format("%02x", CodePoint);
5151 else if (CodePoint <= 0xFFFF)
5152 OS << "\\u" << llvm::format("%04x", CodePoint);
5153 else
5154 OS << "\\U" << llvm::format("%08x", CodePoint);
5155 OS.flush();
5156 Specifier = CodePointStr;
5157 }
5158
5159 EmitFormatDiagnostic(
5160 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5161 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5162
Ted Kremenekce815422010-07-19 21:25:57 +00005163 return keepGoing;
5164}
5165
Richard Trieu03cf7b72011-10-28 00:41:25 +00005166void
5167CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5168 const char *startSpec,
5169 unsigned specifierLen) {
5170 EmitFormatDiagnostic(
5171 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5172 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5173}
5174
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005175bool
5176CheckFormatHandler::CheckNumArgs(
5177 const analyze_format_string::FormatSpecifier &FS,
5178 const analyze_format_string::ConversionSpecifier &CS,
5179 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5180
5181 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005182 PartialDiagnostic PDiag = FS.usesPositionalArg()
5183 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5184 << (argIndex+1) << NumDataArgs)
5185 : S.PDiag(diag::warn_printf_insufficient_data_args);
5186 EmitFormatDiagnostic(
5187 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5188 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005189
5190 // Since more arguments than conversion tokens are given, by extension
5191 // all arguments are covered, so mark this as so.
5192 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005193 return false;
5194 }
5195 return true;
5196}
5197
Richard Trieu03cf7b72011-10-28 00:41:25 +00005198template<typename Range>
5199void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5200 SourceLocation Loc,
5201 bool IsStringLocation,
5202 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005203 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005204 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005205 Loc, IsStringLocation, StringRange, FixIt);
5206}
5207
5208/// \brief If the format string is not within the funcion call, emit a note
5209/// so that the function call and string are in diagnostic messages.
5210///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005211/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005212/// call and only one diagnostic message will be produced. Otherwise, an
5213/// extra note will be emitted pointing to location of the format string.
5214///
5215/// \param ArgumentExpr the expression that is passed as the format string
5216/// argument in the function call. Used for getting locations when two
5217/// diagnostics are emitted.
5218///
5219/// \param PDiag the callee should already have provided any strings for the
5220/// diagnostic message. This function only adds locations and fixits
5221/// to diagnostics.
5222///
5223/// \param Loc primary location for diagnostic. If two diagnostics are
5224/// required, one will be at Loc and a new SourceLocation will be created for
5225/// the other one.
5226///
5227/// \param IsStringLocation if true, Loc points to the format string should be
5228/// used for the note. Otherwise, Loc points to the argument list and will
5229/// be used with PDiag.
5230///
5231/// \param StringRange some or all of the string to highlight. This is
5232/// templated so it can accept either a CharSourceRange or a SourceRange.
5233///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005234/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005235template <typename Range>
5236void CheckFormatHandler::EmitFormatDiagnostic(
5237 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5238 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5239 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005240 if (InFunctionCall) {
5241 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5242 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005243 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00005244 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005245 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5246 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00005247
5248 const Sema::SemaDiagnosticBuilder &Note =
5249 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5250 diag::note_format_string_defined);
5251
5252 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005253 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005254 }
5255}
5256
Ted Kremenek02087932010-07-16 02:11:22 +00005257//===--- CHECK: Printf format string checking ------------------------------===//
5258
5259namespace {
5260class CheckPrintfHandler : public CheckFormatHandler {
5261public:
Stephen Hines648c3692016-09-16 01:07:04 +00005262 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005263 const Expr *origFormatExpr,
5264 const Sema::FormatStringType type, unsigned firstDataArg,
5265 unsigned numDataArgs, bool isObjC, const char *beg,
5266 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005267 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005268 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005269 llvm::SmallBitVector &CheckedVarArgs,
5270 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005271 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5272 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5273 inFunctionCall, CallType, CheckedVarArgs,
5274 UncoveredArg) {}
5275
5276 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5277
5278 /// Returns true if '%@' specifiers are allowed in the format string.
5279 bool allowsObjCArg() const {
5280 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5281 FSType == Sema::FST_OSTrace;
5282 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00005283
Ted Kremenek02087932010-07-16 02:11:22 +00005284 bool HandleInvalidPrintfConversionSpecifier(
5285 const analyze_printf::PrintfSpecifier &FS,
5286 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005287 unsigned specifierLen) override;
5288
Ted Kremenek02087932010-07-16 02:11:22 +00005289 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5290 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005291 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005292 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5293 const char *StartSpecifier,
5294 unsigned SpecifierLen,
5295 const Expr *E);
5296
Ted Kremenek02087932010-07-16 02:11:22 +00005297 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5298 const char *startSpecifier, unsigned specifierLen);
5299 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5300 const analyze_printf::OptionalAmount &Amt,
5301 unsigned type,
5302 const char *startSpecifier, unsigned specifierLen);
5303 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5304 const analyze_printf::OptionalFlag &flag,
5305 const char *startSpecifier, unsigned specifierLen);
5306 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5307 const analyze_printf::OptionalFlag &ignoredFlag,
5308 const analyze_printf::OptionalFlag &flag,
5309 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005310 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00005311 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00005312
5313 void HandleEmptyObjCModifierFlag(const char *startFlag,
5314 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005315
Ted Kremenek2b417712015-07-02 05:39:16 +00005316 void HandleInvalidObjCModifierFlag(const char *startFlag,
5317 unsigned flagLen) override;
5318
5319 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5320 const char *flagsEnd,
5321 const char *conversionPosition)
5322 override;
5323};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005324} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00005325
5326bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5327 const analyze_printf::PrintfSpecifier &FS,
5328 const char *startSpecifier,
5329 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005330 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005331 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005332
Ted Kremenekce815422010-07-19 21:25:57 +00005333 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5334 getLocationOfByte(CS.getStart()),
5335 startSpecifier, specifierLen,
5336 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00005337}
5338
Ted Kremenek02087932010-07-16 02:11:22 +00005339bool CheckPrintfHandler::HandleAmount(
5340 const analyze_format_string::OptionalAmount &Amt,
5341 unsigned k, const char *startSpecifier,
5342 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005343 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005344 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00005345 unsigned argIndex = Amt.getArgIndex();
5346 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005347 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5348 << k,
5349 getLocationOfByte(Amt.getStart()),
5350 /*IsStringLocation*/true,
5351 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005352 // Don't do any more checking. We will just emit
5353 // spurious errors.
5354 return false;
5355 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005356
Ted Kremenek5739de72010-01-29 01:06:55 +00005357 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00005358 // Although not in conformance with C99, we also allow the argument to be
5359 // an 'unsigned int' as that is a reasonably safe case. GCC also
5360 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00005361 CoveredArgs.set(argIndex);
5362 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005363 if (!Arg)
5364 return false;
5365
Ted Kremenek5739de72010-01-29 01:06:55 +00005366 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005367
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005368 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5369 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005370
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005371 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005372 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005373 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00005374 << T << Arg->getSourceRange(),
5375 getLocationOfByte(Amt.getStart()),
5376 /*IsStringLocation*/true,
5377 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005378 // Don't do any more checking. We will just emit
5379 // spurious errors.
5380 return false;
5381 }
5382 }
5383 }
5384 return true;
5385}
Ted Kremenek5739de72010-01-29 01:06:55 +00005386
Tom Careb49ec692010-06-17 19:00:27 +00005387void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00005388 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005389 const analyze_printf::OptionalAmount &Amt,
5390 unsigned type,
5391 const char *startSpecifier,
5392 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005393 const analyze_printf::PrintfConversionSpecifier &CS =
5394 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00005395
Richard Trieu03cf7b72011-10-28 00:41:25 +00005396 FixItHint fixit =
5397 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5398 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5399 Amt.getConstantLength()))
5400 : FixItHint();
5401
5402 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5403 << type << CS.toString(),
5404 getLocationOfByte(Amt.getStart()),
5405 /*IsStringLocation*/true,
5406 getSpecifierRange(startSpecifier, specifierLen),
5407 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00005408}
5409
Ted Kremenek02087932010-07-16 02:11:22 +00005410void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005411 const analyze_printf::OptionalFlag &flag,
5412 const char *startSpecifier,
5413 unsigned specifierLen) {
5414 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005415 const analyze_printf::PrintfConversionSpecifier &CS =
5416 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00005417 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5418 << flag.toString() << CS.toString(),
5419 getLocationOfByte(flag.getPosition()),
5420 /*IsStringLocation*/true,
5421 getSpecifierRange(startSpecifier, specifierLen),
5422 FixItHint::CreateRemoval(
5423 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005424}
5425
5426void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00005427 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005428 const analyze_printf::OptionalFlag &ignoredFlag,
5429 const analyze_printf::OptionalFlag &flag,
5430 const char *startSpecifier,
5431 unsigned specifierLen) {
5432 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005433 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5434 << ignoredFlag.toString() << flag.toString(),
5435 getLocationOfByte(ignoredFlag.getPosition()),
5436 /*IsStringLocation*/true,
5437 getSpecifierRange(startSpecifier, specifierLen),
5438 FixItHint::CreateRemoval(
5439 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005440}
5441
Ted Kremenek2b417712015-07-02 05:39:16 +00005442// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5443// bool IsStringLocation, Range StringRange,
5444// ArrayRef<FixItHint> Fixit = None);
5445
5446void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5447 unsigned flagLen) {
5448 // Warn about an empty flag.
5449 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5450 getLocationOfByte(startFlag),
5451 /*IsStringLocation*/true,
5452 getSpecifierRange(startFlag, flagLen));
5453}
5454
5455void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5456 unsigned flagLen) {
5457 // Warn about an invalid flag.
5458 auto Range = getSpecifierRange(startFlag, flagLen);
5459 StringRef flag(startFlag, flagLen);
5460 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5461 getLocationOfByte(startFlag),
5462 /*IsStringLocation*/true,
5463 Range, FixItHint::CreateRemoval(Range));
5464}
5465
5466void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5467 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5468 // Warn about using '[...]' without a '@' conversion.
5469 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5470 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5471 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5472 getLocationOfByte(conversionPosition),
5473 /*IsStringLocation*/true,
5474 Range, FixItHint::CreateRemoval(Range));
5475}
5476
Richard Smith55ce3522012-06-25 20:30:08 +00005477// Determines if the specified is a C++ class or struct containing
5478// a member with the specified name and kind (e.g. a CXXMethodDecl named
5479// "c_str()").
5480template<typename MemberKind>
5481static llvm::SmallPtrSet<MemberKind*, 1>
5482CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5483 const RecordType *RT = Ty->getAs<RecordType>();
5484 llvm::SmallPtrSet<MemberKind*, 1> Results;
5485
5486 if (!RT)
5487 return Results;
5488 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005489 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005490 return Results;
5491
Alp Tokerb6cc5922014-05-03 03:45:55 +00005492 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005493 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005494 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005495
5496 // We just need to include all members of the right kind turned up by the
5497 // filter, at this point.
5498 if (S.LookupQualifiedName(R, RT->getDecl()))
5499 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5500 NamedDecl *decl = (*I)->getUnderlyingDecl();
5501 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5502 Results.insert(FK);
5503 }
5504 return Results;
5505}
5506
Richard Smith2868a732014-02-28 01:36:39 +00005507/// Check if we could call '.c_str()' on an object.
5508///
5509/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5510/// allow the call, or if it would be ambiguous).
5511bool Sema::hasCStrMethod(const Expr *E) {
5512 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5513 MethodSet Results =
5514 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5515 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5516 MI != ME; ++MI)
5517 if ((*MI)->getMinRequiredArguments() == 0)
5518 return true;
5519 return false;
5520}
5521
Richard Smith55ce3522012-06-25 20:30:08 +00005522// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005523// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00005524// Returns true when a c_str() conversion method is found.
5525bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00005526 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00005527 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5528
5529 MethodSet Results =
5530 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5531
5532 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5533 MI != ME; ++MI) {
5534 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00005535 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00005536 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00005537 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00005538 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00005539 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5540 << "c_str()"
5541 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5542 return true;
5543 }
5544 }
5545
5546 return false;
5547}
5548
Ted Kremenekab278de2010-01-28 23:39:18 +00005549bool
Ted Kremenek02087932010-07-16 02:11:22 +00005550CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00005551 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00005552 const char *startSpecifier,
5553 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005554 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00005555 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005556 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00005557
Ted Kremenek6cd69422010-07-19 22:01:06 +00005558 if (FS.consumesDataArgument()) {
5559 if (atFirstArg) {
5560 atFirstArg = false;
5561 usesPositionalArgs = FS.usesPositionalArg();
5562 }
5563 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005564 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5565 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005566 return false;
5567 }
Ted Kremenek5739de72010-01-29 01:06:55 +00005568 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005569
Ted Kremenekd1668192010-02-27 01:41:03 +00005570 // First check if the field width, precision, and conversion specifier
5571 // have matching data arguments.
5572 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5573 startSpecifier, specifierLen)) {
5574 return false;
5575 }
5576
5577 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5578 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005579 return false;
5580 }
5581
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005582 if (!CS.consumesDataArgument()) {
5583 // FIXME: Technically specifying a precision or field width here
5584 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00005585 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005586 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005587
Ted Kremenek4a49d982010-02-26 19:18:41 +00005588 // Consume the argument.
5589 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00005590 if (argIndex < NumDataArgs) {
5591 // The check to see if the argIndex is valid will come later.
5592 // We set the bit here because we may exit early from this
5593 // function if we encounter some other error.
5594 CoveredArgs.set(argIndex);
5595 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00005596
Dimitry Andric6b5ed342015-02-19 22:32:33 +00005597 // FreeBSD kernel extensions.
5598 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5599 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5600 // We need at least two arguments.
5601 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5602 return false;
5603
5604 // Claim the second argument.
5605 CoveredArgs.set(argIndex + 1);
5606
5607 // Type check the first argument (int for %b, pointer for %D)
5608 const Expr *Ex = getDataArg(argIndex);
5609 const analyze_printf::ArgType &AT =
5610 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5611 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5612 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5613 EmitFormatDiagnostic(
5614 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5615 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5616 << false << Ex->getSourceRange(),
5617 Ex->getLocStart(), /*IsStringLocation*/false,
5618 getSpecifierRange(startSpecifier, specifierLen));
5619
5620 // Type check the second argument (char * for both %b and %D)
5621 Ex = getDataArg(argIndex + 1);
5622 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5623 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5624 EmitFormatDiagnostic(
5625 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5626 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5627 << false << Ex->getSourceRange(),
5628 Ex->getLocStart(), /*IsStringLocation*/false,
5629 getSpecifierRange(startSpecifier, specifierLen));
5630
5631 return true;
5632 }
5633
Ted Kremenek4a49d982010-02-26 19:18:41 +00005634 // Check for using an Objective-C specific conversion specifier
5635 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00005636 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00005637 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5638 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00005639 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005640
Mehdi Amini06d367c2016-10-24 20:39:34 +00005641 // %P can only be used with os_log.
5642 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
5643 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5644 specifierLen);
5645 }
5646
5647 // %n is not allowed with os_log.
5648 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
5649 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
5650 getLocationOfByte(CS.getStart()),
5651 /*IsStringLocation*/ false,
5652 getSpecifierRange(startSpecifier, specifierLen));
5653
5654 return true;
5655 }
5656
5657 // Only scalars are allowed for os_trace.
5658 if (FSType == Sema::FST_OSTrace &&
5659 (CS.getKind() == ConversionSpecifier::PArg ||
5660 CS.getKind() == ConversionSpecifier::sArg ||
5661 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
5662 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5663 specifierLen);
5664 }
5665
5666 // Check for use of public/private annotation outside of os_log().
5667 if (FSType != Sema::FST_OSLog) {
5668 if (FS.isPublic().isSet()) {
5669 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5670 << "public",
5671 getLocationOfByte(FS.isPublic().getPosition()),
5672 /*IsStringLocation*/ false,
5673 getSpecifierRange(startSpecifier, specifierLen));
5674 }
5675 if (FS.isPrivate().isSet()) {
5676 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5677 << "private",
5678 getLocationOfByte(FS.isPrivate().getPosition()),
5679 /*IsStringLocation*/ false,
5680 getSpecifierRange(startSpecifier, specifierLen));
5681 }
5682 }
5683
Tom Careb49ec692010-06-17 19:00:27 +00005684 // Check for invalid use of field width
5685 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00005686 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00005687 startSpecifier, specifierLen);
5688 }
5689
5690 // Check for invalid use of precision
5691 if (!FS.hasValidPrecision()) {
5692 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5693 startSpecifier, specifierLen);
5694 }
5695
Mehdi Amini06d367c2016-10-24 20:39:34 +00005696 // Precision is mandatory for %P specifier.
5697 if (CS.getKind() == ConversionSpecifier::PArg &&
5698 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
5699 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
5700 getLocationOfByte(startSpecifier),
5701 /*IsStringLocation*/ false,
5702 getSpecifierRange(startSpecifier, specifierLen));
5703 }
5704
Tom Careb49ec692010-06-17 19:00:27 +00005705 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00005706 if (!FS.hasValidThousandsGroupingPrefix())
5707 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005708 if (!FS.hasValidLeadingZeros())
5709 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5710 if (!FS.hasValidPlusPrefix())
5711 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00005712 if (!FS.hasValidSpacePrefix())
5713 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005714 if (!FS.hasValidAlternativeForm())
5715 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5716 if (!FS.hasValidLeftJustified())
5717 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5718
5719 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00005720 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5721 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5722 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005723 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5724 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5725 startSpecifier, specifierLen);
5726
5727 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005728 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005729 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5730 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005731 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005732 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005733 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005734 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5735 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00005736
Jordan Rose92303592012-09-08 04:00:03 +00005737 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5738 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5739
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005740 // The remaining checks depend on the data arguments.
5741 if (HasVAListArg)
5742 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005743
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005744 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005745 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005746
Jordan Rose58bbe422012-07-19 18:10:08 +00005747 const Expr *Arg = getDataArg(argIndex);
5748 if (!Arg)
5749 return true;
5750
5751 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00005752}
5753
Jordan Roseaee34382012-09-05 22:56:26 +00005754static bool requiresParensToAddCast(const Expr *E) {
5755 // FIXME: We should have a general way to reason about operator
5756 // precedence and whether parens are actually needed here.
5757 // Take care of a few common cases where they aren't.
5758 const Expr *Inside = E->IgnoreImpCasts();
5759 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5760 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5761
5762 switch (Inside->getStmtClass()) {
5763 case Stmt::ArraySubscriptExprClass:
5764 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005765 case Stmt::CharacterLiteralClass:
5766 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005767 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005768 case Stmt::FloatingLiteralClass:
5769 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005770 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005771 case Stmt::ObjCArrayLiteralClass:
5772 case Stmt::ObjCBoolLiteralExprClass:
5773 case Stmt::ObjCBoxedExprClass:
5774 case Stmt::ObjCDictionaryLiteralClass:
5775 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005776 case Stmt::ObjCIvarRefExprClass:
5777 case Stmt::ObjCMessageExprClass:
5778 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005779 case Stmt::ObjCStringLiteralClass:
5780 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005781 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005782 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005783 case Stmt::UnaryOperatorClass:
5784 return false;
5785 default:
5786 return true;
5787 }
5788}
5789
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005790static std::pair<QualType, StringRef>
5791shouldNotPrintDirectly(const ASTContext &Context,
5792 QualType IntendedTy,
5793 const Expr *E) {
5794 // Use a 'while' to peel off layers of typedefs.
5795 QualType TyTy = IntendedTy;
5796 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5797 StringRef Name = UserTy->getDecl()->getName();
5798 QualType CastTy = llvm::StringSwitch<QualType>(Name)
5799 .Case("NSInteger", Context.LongTy)
5800 .Case("NSUInteger", Context.UnsignedLongTy)
5801 .Case("SInt32", Context.IntTy)
5802 .Case("UInt32", Context.UnsignedIntTy)
5803 .Default(QualType());
5804
5805 if (!CastTy.isNull())
5806 return std::make_pair(CastTy, Name);
5807
5808 TyTy = UserTy->desugar();
5809 }
5810
5811 // Strip parens if necessary.
5812 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5813 return shouldNotPrintDirectly(Context,
5814 PE->getSubExpr()->getType(),
5815 PE->getSubExpr());
5816
5817 // If this is a conditional expression, then its result type is constructed
5818 // via usual arithmetic conversions and thus there might be no necessary
5819 // typedef sugar there. Recurse to operands to check for NSInteger &
5820 // Co. usage condition.
5821 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5822 QualType TrueTy, FalseTy;
5823 StringRef TrueName, FalseName;
5824
5825 std::tie(TrueTy, TrueName) =
5826 shouldNotPrintDirectly(Context,
5827 CO->getTrueExpr()->getType(),
5828 CO->getTrueExpr());
5829 std::tie(FalseTy, FalseName) =
5830 shouldNotPrintDirectly(Context,
5831 CO->getFalseExpr()->getType(),
5832 CO->getFalseExpr());
5833
5834 if (TrueTy == FalseTy)
5835 return std::make_pair(TrueTy, TrueName);
5836 else if (TrueTy.isNull())
5837 return std::make_pair(FalseTy, FalseName);
5838 else if (FalseTy.isNull())
5839 return std::make_pair(TrueTy, TrueName);
5840 }
5841
5842 return std::make_pair(QualType(), StringRef());
5843}
5844
Richard Smith55ce3522012-06-25 20:30:08 +00005845bool
5846CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5847 const char *StartSpecifier,
5848 unsigned SpecifierLen,
5849 const Expr *E) {
5850 using namespace analyze_format_string;
5851 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005852 // Now type check the data expression that matches the
5853 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00005854 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00005855 if (!AT.isValid())
5856 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00005857
Jordan Rose598ec092012-12-05 18:44:40 +00005858 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00005859 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5860 ExprTy = TET->getUnderlyingExpr()->getType();
5861 }
5862
Seth Cantrellb4802962015-03-04 03:12:10 +00005863 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5864
5865 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00005866 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005867 }
Jordan Rose98709982012-06-04 22:48:57 +00005868
Jordan Rose22b74712012-09-05 22:56:19 +00005869 // Look through argument promotions for our error message's reported type.
5870 // This includes the integral and floating promotions, but excludes array
5871 // and function pointer decay; seeing that an argument intended to be a
5872 // string has type 'char [6]' is probably more confusing than 'char *'.
5873 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5874 if (ICE->getCastKind() == CK_IntegralCast ||
5875 ICE->getCastKind() == CK_FloatingCast) {
5876 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00005877 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00005878
5879 // Check if we didn't match because of an implicit cast from a 'char'
5880 // or 'short' to an 'int'. This is done because printf is a varargs
5881 // function.
5882 if (ICE->getType() == S.Context.IntTy ||
5883 ICE->getType() == S.Context.UnsignedIntTy) {
5884 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00005885 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00005886 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00005887 }
Jordan Rose98709982012-06-04 22:48:57 +00005888 }
Jordan Rose598ec092012-12-05 18:44:40 +00005889 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5890 // Special case for 'a', which has type 'int' in C.
5891 // Note, however, that we do /not/ want to treat multibyte constants like
5892 // 'MooV' as characters! This form is deprecated but still exists.
5893 if (ExprTy == S.Context.IntTy)
5894 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5895 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00005896 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005897
Jordan Rosebc53ed12014-05-31 04:12:14 +00005898 // Look through enums to their underlying type.
5899 bool IsEnum = false;
5900 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5901 ExprTy = EnumTy->getDecl()->getIntegerType();
5902 IsEnum = true;
5903 }
5904
Jordan Rose0e5badd2012-12-05 18:44:49 +00005905 // %C in an Objective-C context prints a unichar, not a wchar_t.
5906 // If the argument is an integer of some kind, believe the %C and suggest
5907 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00005908 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005909 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00005910 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5911 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5912 !ExprTy->isCharType()) {
5913 // 'unichar' is defined as a typedef of unsigned short, but we should
5914 // prefer using the typedef if it is visible.
5915 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00005916
5917 // While we are here, check if the value is an IntegerLiteral that happens
5918 // to be within the valid range.
5919 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5920 const llvm::APInt &V = IL->getValue();
5921 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5922 return true;
5923 }
5924
Jordan Rose0e5badd2012-12-05 18:44:49 +00005925 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5926 Sema::LookupOrdinaryName);
5927 if (S.LookupName(Result, S.getCurScope())) {
5928 NamedDecl *ND = Result.getFoundDecl();
5929 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5930 if (TD->getUnderlyingType() == IntendedTy)
5931 IntendedTy = S.Context.getTypedefType(TD);
5932 }
5933 }
5934 }
5935
5936 // Special-case some of Darwin's platform-independence types by suggesting
5937 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005938 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00005939 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005940 QualType CastTy;
5941 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5942 if (!CastTy.isNull()) {
5943 IntendedTy = CastTy;
5944 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00005945 }
5946 }
5947
Jordan Rose22b74712012-09-05 22:56:19 +00005948 // We may be able to offer a FixItHint if it is a supported type.
5949 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005950 bool success =
5951 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005952
Jordan Rose22b74712012-09-05 22:56:19 +00005953 if (success) {
5954 // Get the fix string from the fixed format specifier
5955 SmallString<16> buf;
5956 llvm::raw_svector_ostream os(buf);
5957 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005958
Jordan Roseaee34382012-09-05 22:56:26 +00005959 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5960
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005961 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00005962 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5963 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5964 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5965 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00005966 // In this case, the specifier is wrong and should be changed to match
5967 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00005968 EmitFormatDiagnostic(S.PDiag(diag)
5969 << AT.getRepresentativeTypeName(S.Context)
5970 << IntendedTy << IsEnum << E->getSourceRange(),
5971 E->getLocStart(),
5972 /*IsStringLocation*/ false, SpecRange,
5973 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00005974 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00005975 // The canonical type for formatting this value is different from the
5976 // actual type of the expression. (This occurs, for example, with Darwin's
5977 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
5978 // should be printed as 'long' for 64-bit compatibility.)
5979 // Rather than emitting a normal format/argument mismatch, we want to
5980 // add a cast to the recommended type (and correct the format string
5981 // if necessary).
5982 SmallString<16> CastBuf;
5983 llvm::raw_svector_ostream CastFix(CastBuf);
5984 CastFix << "(";
5985 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
5986 CastFix << ")";
5987
5988 SmallVector<FixItHint,4> Hints;
5989 if (!AT.matchesType(S.Context, IntendedTy))
5990 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
5991
5992 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
5993 // If there's already a cast present, just replace it.
5994 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
5995 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
5996
5997 } else if (!requiresParensToAddCast(E)) {
5998 // If the expression has high enough precedence,
5999 // just write the C-style cast.
6000 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6001 CastFix.str()));
6002 } else {
6003 // Otherwise, add parens around the expression as well as the cast.
6004 CastFix << "(";
6005 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6006 CastFix.str()));
6007
Alp Tokerb6cc5922014-05-03 03:45:55 +00006008 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006009 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6010 }
6011
Jordan Rose0e5badd2012-12-05 18:44:49 +00006012 if (ShouldNotPrintDirectly) {
6013 // The expression has a type that should not be printed directly.
6014 // We extract the name from the typedef because we don't want to show
6015 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006016 StringRef Name;
6017 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6018 Name = TypedefTy->getDecl()->getName();
6019 else
6020 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006021 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006022 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006023 << E->getSourceRange(),
6024 E->getLocStart(), /*IsStringLocation=*/false,
6025 SpecRange, Hints);
6026 } else {
6027 // In this case, the expression could be printed using a different
6028 // specifier, but we've decided that the specifier is probably correct
6029 // and we should cast instead. Just use the normal warning message.
6030 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006031 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6032 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006033 << E->getSourceRange(),
6034 E->getLocStart(), /*IsStringLocation*/false,
6035 SpecRange, Hints);
6036 }
Jordan Roseaee34382012-09-05 22:56:26 +00006037 }
Jordan Rose22b74712012-09-05 22:56:19 +00006038 } else {
6039 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6040 SpecifierLen);
6041 // Since the warning for passing non-POD types to variadic functions
6042 // was deferred until now, we emit a warning for non-POD
6043 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006044 switch (S.isValidVarArgType(ExprTy)) {
6045 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006046 case Sema::VAK_ValidInCXX11: {
6047 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6048 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6049 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6050 }
Richard Smithd7293d72013-08-05 18:49:43 +00006051
Seth Cantrellb4802962015-03-04 03:12:10 +00006052 EmitFormatDiagnostic(
6053 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6054 << IsEnum << CSR << E->getSourceRange(),
6055 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6056 break;
6057 }
Richard Smithd7293d72013-08-05 18:49:43 +00006058 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006059 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006060 EmitFormatDiagnostic(
6061 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006062 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006063 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006064 << CallType
6065 << AT.getRepresentativeTypeName(S.Context)
6066 << CSR
6067 << E->getSourceRange(),
6068 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006069 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006070 break;
6071
6072 case Sema::VAK_Invalid:
6073 if (ExprTy->isObjCObjectType())
6074 EmitFormatDiagnostic(
6075 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6076 << S.getLangOpts().CPlusPlus11
6077 << ExprTy
6078 << CallType
6079 << AT.getRepresentativeTypeName(S.Context)
6080 << CSR
6081 << E->getSourceRange(),
6082 E->getLocStart(), /*IsStringLocation*/false, CSR);
6083 else
6084 // FIXME: If this is an initializer list, suggest removing the braces
6085 // or inserting a cast to the target type.
6086 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6087 << isa<InitListExpr>(E) << ExprTy << CallType
6088 << AT.getRepresentativeTypeName(S.Context)
6089 << E->getSourceRange();
6090 break;
6091 }
6092
6093 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6094 "format string specifier index out of range");
6095 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006096 }
6097
Ted Kremenekab278de2010-01-28 23:39:18 +00006098 return true;
6099}
6100
Ted Kremenek02087932010-07-16 02:11:22 +00006101//===--- CHECK: Scanf format string checking ------------------------------===//
6102
6103namespace {
6104class CheckScanfHandler : public CheckFormatHandler {
6105public:
Stephen Hines648c3692016-09-16 01:07:04 +00006106 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006107 const Expr *origFormatExpr, Sema::FormatStringType type,
6108 unsigned firstDataArg, unsigned numDataArgs,
6109 const char *beg, bool hasVAListArg,
6110 ArrayRef<const Expr *> Args, unsigned formatIdx,
6111 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006112 llvm::SmallBitVector &CheckedVarArgs,
6113 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006114 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6115 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6116 inFunctionCall, CallType, CheckedVarArgs,
6117 UncoveredArg) {}
6118
Ted Kremenek02087932010-07-16 02:11:22 +00006119 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6120 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006121 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006122
6123 bool HandleInvalidScanfConversionSpecifier(
6124 const analyze_scanf::ScanfSpecifier &FS,
6125 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006126 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006127
Craig Toppere14c0f82014-03-12 04:55:44 +00006128 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006129};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006130} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006131
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006132void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6133 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006134 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6135 getLocationOfByte(end), /*IsStringLocation*/true,
6136 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006137}
6138
Ted Kremenekce815422010-07-19 21:25:57 +00006139bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6140 const analyze_scanf::ScanfSpecifier &FS,
6141 const char *startSpecifier,
6142 unsigned specifierLen) {
6143
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006144 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006145 FS.getConversionSpecifier();
6146
6147 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6148 getLocationOfByte(CS.getStart()),
6149 startSpecifier, specifierLen,
6150 CS.getStart(), CS.getLength());
6151}
6152
Ted Kremenek02087932010-07-16 02:11:22 +00006153bool CheckScanfHandler::HandleScanfSpecifier(
6154 const analyze_scanf::ScanfSpecifier &FS,
6155 const char *startSpecifier,
6156 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006157 using namespace analyze_scanf;
6158 using namespace analyze_format_string;
6159
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006160 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006161
Ted Kremenek6cd69422010-07-19 22:01:06 +00006162 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6163 // be used to decide if we are using positional arguments consistently.
6164 if (FS.consumesDataArgument()) {
6165 if (atFirstArg) {
6166 atFirstArg = false;
6167 usesPositionalArgs = FS.usesPositionalArg();
6168 }
6169 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006170 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6171 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006172 return false;
6173 }
Ted Kremenek02087932010-07-16 02:11:22 +00006174 }
6175
6176 // Check if the field with is non-zero.
6177 const OptionalAmount &Amt = FS.getFieldWidth();
6178 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6179 if (Amt.getConstantAmount() == 0) {
6180 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6181 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006182 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6183 getLocationOfByte(Amt.getStart()),
6184 /*IsStringLocation*/true, R,
6185 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006186 }
6187 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006188
Ted Kremenek02087932010-07-16 02:11:22 +00006189 if (!FS.consumesDataArgument()) {
6190 // FIXME: Technically specifying a precision or field width here
6191 // makes no sense. Worth issuing a warning at some point.
6192 return true;
6193 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006194
Ted Kremenek02087932010-07-16 02:11:22 +00006195 // Consume the argument.
6196 unsigned argIndex = FS.getArgIndex();
6197 if (argIndex < NumDataArgs) {
6198 // The check to see if the argIndex is valid will come later.
6199 // We set the bit here because we may exit early from this
6200 // function if we encounter some other error.
6201 CoveredArgs.set(argIndex);
6202 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006203
Ted Kremenek4407ea42010-07-20 20:04:47 +00006204 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006205 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006206 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6207 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006208 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006209 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006210 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006211 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6212 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006213
Jordan Rose92303592012-09-08 04:00:03 +00006214 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6215 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6216
Ted Kremenek02087932010-07-16 02:11:22 +00006217 // The remaining checks depend on the data arguments.
6218 if (HasVAListArg)
6219 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006220
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006221 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006222 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006223
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006224 // Check that the argument type matches the format specifier.
6225 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006226 if (!Ex)
6227 return true;
6228
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006229 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006230
6231 if (!AT.isValid()) {
6232 return true;
6233 }
6234
Seth Cantrellb4802962015-03-04 03:12:10 +00006235 analyze_format_string::ArgType::MatchKind match =
6236 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006237 if (match == analyze_format_string::ArgType::Match) {
6238 return true;
6239 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006240
Seth Cantrell79340072015-03-04 05:58:08 +00006241 ScanfSpecifier fixedFS = FS;
6242 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6243 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006244
Seth Cantrell79340072015-03-04 05:58:08 +00006245 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6246 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6247 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6248 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006249
Seth Cantrell79340072015-03-04 05:58:08 +00006250 if (success) {
6251 // Get the fix string from the fixed format specifier.
6252 SmallString<128> buf;
6253 llvm::raw_svector_ostream os(buf);
6254 fixedFS.toString(os);
6255
6256 EmitFormatDiagnostic(
6257 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6258 << Ex->getType() << false << Ex->getSourceRange(),
6259 Ex->getLocStart(),
6260 /*IsStringLocation*/ false,
6261 getSpecifierRange(startSpecifier, specifierLen),
6262 FixItHint::CreateReplacement(
6263 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6264 } else {
6265 EmitFormatDiagnostic(S.PDiag(diag)
6266 << AT.getRepresentativeTypeName(S.Context)
6267 << Ex->getType() << false << Ex->getSourceRange(),
6268 Ex->getLocStart(),
6269 /*IsStringLocation*/ false,
6270 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006271 }
6272
Ted Kremenek02087932010-07-16 02:11:22 +00006273 return true;
6274}
6275
Stephen Hines648c3692016-09-16 01:07:04 +00006276static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006277 const Expr *OrigFormatExpr,
6278 ArrayRef<const Expr *> Args,
6279 bool HasVAListArg, unsigned format_idx,
6280 unsigned firstDataArg,
6281 Sema::FormatStringType Type,
6282 bool inFunctionCall,
6283 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006284 llvm::SmallBitVector &CheckedVarArgs,
6285 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00006286 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00006287 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006288 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006289 S, inFunctionCall, Args[format_idx],
6290 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006291 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006292 return;
6293 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006294
Ted Kremenekab278de2010-01-28 23:39:18 +00006295 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006296 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00006297 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006298 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006299 const ConstantArrayType *T =
6300 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006301 assert(T && "String literal not of constant array type!");
6302 size_t TypeSize = T->getSize().getZExtValue();
6303 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006304 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006305
6306 // Emit a warning if the string literal is truncated and does not contain an
6307 // embedded null character.
6308 if (TypeSize <= StrRef.size() &&
6309 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6310 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006311 S, inFunctionCall, Args[format_idx],
6312 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006313 FExpr->getLocStart(),
6314 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6315 return;
6316 }
6317
Ted Kremenekab278de2010-01-28 23:39:18 +00006318 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006319 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006320 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006321 S, inFunctionCall, Args[format_idx],
6322 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006323 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006324 return;
6325 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006326
6327 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00006328 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6329 Type == Sema::FST_OSTrace) {
6330 CheckPrintfHandler H(
6331 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6332 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6333 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6334 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006335
Hans Wennborg23926bd2011-12-15 10:25:47 +00006336 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006337 S.getLangOpts(),
6338 S.Context.getTargetInfo(),
6339 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006340 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006341 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00006342 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6343 numDataArgs, Str, HasVAListArg, Args, format_idx,
6344 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006345
Hans Wennborg23926bd2011-12-15 10:25:47 +00006346 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006347 S.getLangOpts(),
6348 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006349 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006350 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006351}
6352
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006353bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6354 // Str - The format string. NOTE: this is NOT null-terminated!
6355 StringRef StrRef = FExpr->getString();
6356 const char *Str = StrRef.data();
6357 // Account for cases where the string literal is truncated in a declaration.
6358 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6359 assert(T && "String literal not of constant array type!");
6360 size_t TypeSize = T->getSize().getZExtValue();
6361 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6362 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6363 getLangOpts(),
6364 Context.getTargetInfo());
6365}
6366
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006367//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6368
6369// Returns the related absolute value function that is larger, of 0 if one
6370// does not exist.
6371static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6372 switch (AbsFunction) {
6373 default:
6374 return 0;
6375
6376 case Builtin::BI__builtin_abs:
6377 return Builtin::BI__builtin_labs;
6378 case Builtin::BI__builtin_labs:
6379 return Builtin::BI__builtin_llabs;
6380 case Builtin::BI__builtin_llabs:
6381 return 0;
6382
6383 case Builtin::BI__builtin_fabsf:
6384 return Builtin::BI__builtin_fabs;
6385 case Builtin::BI__builtin_fabs:
6386 return Builtin::BI__builtin_fabsl;
6387 case Builtin::BI__builtin_fabsl:
6388 return 0;
6389
6390 case Builtin::BI__builtin_cabsf:
6391 return Builtin::BI__builtin_cabs;
6392 case Builtin::BI__builtin_cabs:
6393 return Builtin::BI__builtin_cabsl;
6394 case Builtin::BI__builtin_cabsl:
6395 return 0;
6396
6397 case Builtin::BIabs:
6398 return Builtin::BIlabs;
6399 case Builtin::BIlabs:
6400 return Builtin::BIllabs;
6401 case Builtin::BIllabs:
6402 return 0;
6403
6404 case Builtin::BIfabsf:
6405 return Builtin::BIfabs;
6406 case Builtin::BIfabs:
6407 return Builtin::BIfabsl;
6408 case Builtin::BIfabsl:
6409 return 0;
6410
6411 case Builtin::BIcabsf:
6412 return Builtin::BIcabs;
6413 case Builtin::BIcabs:
6414 return Builtin::BIcabsl;
6415 case Builtin::BIcabsl:
6416 return 0;
6417 }
6418}
6419
6420// Returns the argument type of the absolute value function.
6421static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6422 unsigned AbsType) {
6423 if (AbsType == 0)
6424 return QualType();
6425
6426 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6427 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6428 if (Error != ASTContext::GE_None)
6429 return QualType();
6430
6431 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6432 if (!FT)
6433 return QualType();
6434
6435 if (FT->getNumParams() != 1)
6436 return QualType();
6437
6438 return FT->getParamType(0);
6439}
6440
6441// Returns the best absolute value function, or zero, based on type and
6442// current absolute value function.
6443static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6444 unsigned AbsFunctionKind) {
6445 unsigned BestKind = 0;
6446 uint64_t ArgSize = Context.getTypeSize(ArgType);
6447 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6448 Kind = getLargerAbsoluteValueFunction(Kind)) {
6449 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6450 if (Context.getTypeSize(ParamType) >= ArgSize) {
6451 if (BestKind == 0)
6452 BestKind = Kind;
6453 else if (Context.hasSameType(ParamType, ArgType)) {
6454 BestKind = Kind;
6455 break;
6456 }
6457 }
6458 }
6459 return BestKind;
6460}
6461
6462enum AbsoluteValueKind {
6463 AVK_Integer,
6464 AVK_Floating,
6465 AVK_Complex
6466};
6467
6468static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6469 if (T->isIntegralOrEnumerationType())
6470 return AVK_Integer;
6471 if (T->isRealFloatingType())
6472 return AVK_Floating;
6473 if (T->isAnyComplexType())
6474 return AVK_Complex;
6475
6476 llvm_unreachable("Type not integer, floating, or complex");
6477}
6478
6479// Changes the absolute value function to a different type. Preserves whether
6480// the function is a builtin.
6481static unsigned changeAbsFunction(unsigned AbsKind,
6482 AbsoluteValueKind ValueKind) {
6483 switch (ValueKind) {
6484 case AVK_Integer:
6485 switch (AbsKind) {
6486 default:
6487 return 0;
6488 case Builtin::BI__builtin_fabsf:
6489 case Builtin::BI__builtin_fabs:
6490 case Builtin::BI__builtin_fabsl:
6491 case Builtin::BI__builtin_cabsf:
6492 case Builtin::BI__builtin_cabs:
6493 case Builtin::BI__builtin_cabsl:
6494 return Builtin::BI__builtin_abs;
6495 case Builtin::BIfabsf:
6496 case Builtin::BIfabs:
6497 case Builtin::BIfabsl:
6498 case Builtin::BIcabsf:
6499 case Builtin::BIcabs:
6500 case Builtin::BIcabsl:
6501 return Builtin::BIabs;
6502 }
6503 case AVK_Floating:
6504 switch (AbsKind) {
6505 default:
6506 return 0;
6507 case Builtin::BI__builtin_abs:
6508 case Builtin::BI__builtin_labs:
6509 case Builtin::BI__builtin_llabs:
6510 case Builtin::BI__builtin_cabsf:
6511 case Builtin::BI__builtin_cabs:
6512 case Builtin::BI__builtin_cabsl:
6513 return Builtin::BI__builtin_fabsf;
6514 case Builtin::BIabs:
6515 case Builtin::BIlabs:
6516 case Builtin::BIllabs:
6517 case Builtin::BIcabsf:
6518 case Builtin::BIcabs:
6519 case Builtin::BIcabsl:
6520 return Builtin::BIfabsf;
6521 }
6522 case AVK_Complex:
6523 switch (AbsKind) {
6524 default:
6525 return 0;
6526 case Builtin::BI__builtin_abs:
6527 case Builtin::BI__builtin_labs:
6528 case Builtin::BI__builtin_llabs:
6529 case Builtin::BI__builtin_fabsf:
6530 case Builtin::BI__builtin_fabs:
6531 case Builtin::BI__builtin_fabsl:
6532 return Builtin::BI__builtin_cabsf;
6533 case Builtin::BIabs:
6534 case Builtin::BIlabs:
6535 case Builtin::BIllabs:
6536 case Builtin::BIfabsf:
6537 case Builtin::BIfabs:
6538 case Builtin::BIfabsl:
6539 return Builtin::BIcabsf;
6540 }
6541 }
6542 llvm_unreachable("Unable to convert function");
6543}
6544
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006545static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006546 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6547 if (!FnInfo)
6548 return 0;
6549
6550 switch (FDecl->getBuiltinID()) {
6551 default:
6552 return 0;
6553 case Builtin::BI__builtin_abs:
6554 case Builtin::BI__builtin_fabs:
6555 case Builtin::BI__builtin_fabsf:
6556 case Builtin::BI__builtin_fabsl:
6557 case Builtin::BI__builtin_labs:
6558 case Builtin::BI__builtin_llabs:
6559 case Builtin::BI__builtin_cabs:
6560 case Builtin::BI__builtin_cabsf:
6561 case Builtin::BI__builtin_cabsl:
6562 case Builtin::BIabs:
6563 case Builtin::BIlabs:
6564 case Builtin::BIllabs:
6565 case Builtin::BIfabs:
6566 case Builtin::BIfabsf:
6567 case Builtin::BIfabsl:
6568 case Builtin::BIcabs:
6569 case Builtin::BIcabsf:
6570 case Builtin::BIcabsl:
6571 return FDecl->getBuiltinID();
6572 }
6573 llvm_unreachable("Unknown Builtin type");
6574}
6575
6576// If the replacement is valid, emit a note with replacement function.
6577// Additionally, suggest including the proper header if not already included.
6578static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00006579 unsigned AbsKind, QualType ArgType) {
6580 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006581 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00006582 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006583 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6584 FunctionName = "std::abs";
6585 if (ArgType->isIntegralOrEnumerationType()) {
6586 HeaderName = "cstdlib";
6587 } else if (ArgType->isRealFloatingType()) {
6588 HeaderName = "cmath";
6589 } else {
6590 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006591 }
Richard Trieubeffb832014-04-15 23:47:53 +00006592
6593 // Lookup all std::abs
6594 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00006595 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00006596 R.suppressDiagnostics();
6597 S.LookupQualifiedName(R, Std);
6598
6599 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006600 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006601 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6602 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6603 } else {
6604 FDecl = dyn_cast<FunctionDecl>(I);
6605 }
6606 if (!FDecl)
6607 continue;
6608
6609 // Found std::abs(), check that they are the right ones.
6610 if (FDecl->getNumParams() != 1)
6611 continue;
6612
6613 // Check that the parameter type can handle the argument.
6614 QualType ParamType = FDecl->getParamDecl(0)->getType();
6615 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6616 S.Context.getTypeSize(ArgType) <=
6617 S.Context.getTypeSize(ParamType)) {
6618 // Found a function, don't need the header hint.
6619 EmitHeaderHint = false;
6620 break;
6621 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006622 }
Richard Trieubeffb832014-04-15 23:47:53 +00006623 }
6624 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00006625 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00006626 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6627
6628 if (HeaderName) {
6629 DeclarationName DN(&S.Context.Idents.get(FunctionName));
6630 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6631 R.suppressDiagnostics();
6632 S.LookupName(R, S.getCurScope());
6633
6634 if (R.isSingleResult()) {
6635 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6636 if (FD && FD->getBuiltinID() == AbsKind) {
6637 EmitHeaderHint = false;
6638 } else {
6639 return;
6640 }
6641 } else if (!R.empty()) {
6642 return;
6643 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006644 }
6645 }
6646
6647 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00006648 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006649
Richard Trieubeffb832014-04-15 23:47:53 +00006650 if (!HeaderName)
6651 return;
6652
6653 if (!EmitHeaderHint)
6654 return;
6655
Alp Toker5d96e0a2014-07-11 20:53:51 +00006656 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6657 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00006658}
6659
6660static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
6661 if (!FDecl)
6662 return false;
6663
6664 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
6665 return false;
6666
6667 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
6668
6669 while (ND && ND->isInlineNamespace()) {
6670 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006671 }
Richard Trieubeffb832014-04-15 23:47:53 +00006672
6673 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
6674 return false;
6675
6676 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
6677 return false;
6678
6679 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006680}
6681
6682// Warn when using the wrong abs() function.
6683void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
6684 const FunctionDecl *FDecl,
6685 IdentifierInfo *FnInfo) {
6686 if (Call->getNumArgs() != 1)
6687 return;
6688
6689 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00006690 bool IsStdAbs = IsFunctionStdAbs(FDecl);
6691 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006692 return;
6693
6694 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6695 QualType ParamType = Call->getArg(0)->getType();
6696
Alp Toker5d96e0a2014-07-11 20:53:51 +00006697 // Unsigned types cannot be negative. Suggest removing the absolute value
6698 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006699 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00006700 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00006701 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006702 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6703 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00006704 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006705 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6706 return;
6707 }
6708
David Majnemer7f77eb92015-11-15 03:04:34 +00006709 // Taking the absolute value of a pointer is very suspicious, they probably
6710 // wanted to index into an array, dereference a pointer, call a function, etc.
6711 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6712 unsigned DiagType = 0;
6713 if (ArgType->isFunctionType())
6714 DiagType = 1;
6715 else if (ArgType->isArrayType())
6716 DiagType = 2;
6717
6718 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6719 return;
6720 }
6721
Richard Trieubeffb832014-04-15 23:47:53 +00006722 // std::abs has overloads which prevent most of the absolute value problems
6723 // from occurring.
6724 if (IsStdAbs)
6725 return;
6726
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006727 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6728 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6729
6730 // The argument and parameter are the same kind. Check if they are the right
6731 // size.
6732 if (ArgValueKind == ParamValueKind) {
6733 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6734 return;
6735
6736 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6737 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6738 << FDecl << ArgType << ParamType;
6739
6740 if (NewAbsKind == 0)
6741 return;
6742
6743 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006744 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006745 return;
6746 }
6747
6748 // ArgValueKind != ParamValueKind
6749 // The wrong type of absolute value function was used. Attempt to find the
6750 // proper one.
6751 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6752 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6753 if (NewAbsKind == 0)
6754 return;
6755
6756 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6757 << FDecl << ParamValueKind << ArgValueKind;
6758
6759 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006760 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006761}
6762
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006763//===--- CHECK: Standard memory functions ---------------------------------===//
6764
Nico Weber0e6daef2013-12-26 23:38:39 +00006765/// \brief Takes the expression passed to the size_t parameter of functions
6766/// such as memcmp, strncat, etc and warns if it's a comparison.
6767///
6768/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6769static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6770 IdentifierInfo *FnName,
6771 SourceLocation FnLoc,
6772 SourceLocation RParenLoc) {
6773 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6774 if (!Size)
6775 return false;
6776
6777 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6778 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6779 return false;
6780
Nico Weber0e6daef2013-12-26 23:38:39 +00006781 SourceRange SizeRange = Size->getSourceRange();
6782 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6783 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00006784 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006785 << FnName << FixItHint::CreateInsertion(
6786 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00006787 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00006788 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00006789 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00006790 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6791 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00006792
6793 return true;
6794}
6795
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006796/// \brief Determine whether the given type is or contains a dynamic class type
6797/// (e.g., whether it has a vtable).
6798static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6799 bool &IsContained) {
6800 // Look through array types while ignoring qualifiers.
6801 const Type *Ty = T->getBaseElementTypeUnsafe();
6802 IsContained = false;
6803
6804 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6805 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00006806 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006807 return nullptr;
6808
6809 if (RD->isDynamicClass())
6810 return RD;
6811
6812 // Check all the fields. If any bases were dynamic, the class is dynamic.
6813 // It's impossible for a class to transitively contain itself by value, so
6814 // infinite recursion is impossible.
6815 for (auto *FD : RD->fields()) {
6816 bool SubContained;
6817 if (const CXXRecordDecl *ContainedRD =
6818 getContainedDynamicClass(FD->getType(), SubContained)) {
6819 IsContained = true;
6820 return ContainedRD;
6821 }
6822 }
6823
6824 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00006825}
6826
Chandler Carruth889ed862011-06-21 23:04:20 +00006827/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006828/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00006829static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00006830 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006831 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6832 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6833 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006834
Craig Topperc3ec1492014-05-26 06:22:03 +00006835 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006836}
6837
Chandler Carruth889ed862011-06-21 23:04:20 +00006838/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00006839static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006840 if (const UnaryExprOrTypeTraitExpr *SizeOf =
6841 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6842 if (SizeOf->getKind() == clang::UETT_SizeOf)
6843 return SizeOf->getTypeOfArgument();
6844
6845 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00006846}
6847
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006848/// \brief Check for dangerous or invalid arguments to memset().
6849///
Chandler Carruthac687262011-06-03 06:23:57 +00006850/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006851/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6852/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006853///
6854/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006855void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00006856 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006857 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00006858 assert(BId != 0);
6859
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006860 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00006861 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006862 unsigned ExpectedNumArgs =
6863 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00006864 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006865 return;
6866
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006867 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00006868 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006869 unsigned LenArg =
6870 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00006871 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006872
Nico Weber0e6daef2013-12-26 23:38:39 +00006873 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6874 Call->getLocStart(), Call->getRParenLoc()))
6875 return;
6876
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006877 // We have special checking when the length is a sizeof expression.
6878 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6879 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6880 llvm::FoldingSetNodeID SizeOfArgID;
6881
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00006882 // Although widely used, 'bzero' is not a standard function. Be more strict
6883 // with the argument types before allowing diagnostics and only allow the
6884 // form bzero(ptr, sizeof(...)).
6885 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6886 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
6887 return;
6888
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006889 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6890 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006891 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006892
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006893 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00006894 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006895 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00006896 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00006897
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006898 // Never warn about void type pointers. This can be used to suppress
6899 // false positives.
6900 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006901 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006902
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006903 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6904 // actually comparing the expressions for equality. Because computing the
6905 // expression IDs can be expensive, we only do this if the diagnostic is
6906 // enabled.
6907 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006908 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6909 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006910 // We only compute IDs for expressions if the warning is enabled, and
6911 // cache the sizeof arg's ID.
6912 if (SizeOfArgID == llvm::FoldingSetNodeID())
6913 SizeOfArg->Profile(SizeOfArgID, Context, true);
6914 llvm::FoldingSetNodeID DestID;
6915 Dest->Profile(DestID, Context, true);
6916 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00006917 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6918 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006919 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00006920 StringRef ReadableName = FnName->getName();
6921
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006922 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00006923 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006924 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00006925 if (!PointeeTy->isIncompleteType() &&
6926 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006927 ActionIdx = 2; // If the pointee's size is sizeof(char),
6928 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00006929
6930 // If the function is defined as a builtin macro, do not show macro
6931 // expansion.
6932 SourceLocation SL = SizeOfArg->getExprLoc();
6933 SourceRange DSR = Dest->getSourceRange();
6934 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006935 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00006936
6937 if (SM.isMacroArgExpansion(SL)) {
6938 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
6939 SL = SM.getSpellingLoc(SL);
6940 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
6941 SM.getSpellingLoc(DSR.getEnd()));
6942 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
6943 SM.getSpellingLoc(SSR.getEnd()));
6944 }
6945
Anna Zaksd08d9152012-05-30 23:14:52 +00006946 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006947 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00006948 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00006949 << PointeeTy
6950 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00006951 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00006952 << SSR);
6953 DiagRuntimeBehavior(SL, SizeOfArg,
6954 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
6955 << ActionIdx
6956 << SSR);
6957
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006958 break;
6959 }
6960 }
6961
6962 // Also check for cases where the sizeof argument is the exact same
6963 // type as the memory argument, and where it points to a user-defined
6964 // record type.
6965 if (SizeOfArgTy != QualType()) {
6966 if (PointeeTy->isRecordType() &&
6967 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
6968 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
6969 PDiag(diag::warn_sizeof_pointer_type_memaccess)
6970 << FnName << SizeOfArgTy << ArgIdx
6971 << PointeeTy << Dest->getSourceRange()
6972 << LenExpr->getSourceRange());
6973 break;
6974 }
Nico Weberc5e73862011-06-14 16:14:58 +00006975 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00006976 } else if (DestTy->isArrayType()) {
6977 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00006978 }
Nico Weberc5e73862011-06-14 16:14:58 +00006979
Nico Weberc44b35e2015-03-21 17:37:46 +00006980 if (PointeeTy == QualType())
6981 continue;
Anna Zaks22122702012-01-17 00:37:07 +00006982
Nico Weberc44b35e2015-03-21 17:37:46 +00006983 // Always complain about dynamic classes.
6984 bool IsContained;
6985 if (const CXXRecordDecl *ContainedRD =
6986 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00006987
Nico Weberc44b35e2015-03-21 17:37:46 +00006988 unsigned OperationType = 0;
6989 // "overwritten" if we're warning about the destination for any call
6990 // but memcmp; otherwise a verb appropriate to the call.
6991 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
6992 if (BId == Builtin::BImemcpy)
6993 OperationType = 1;
6994 else if(BId == Builtin::BImemmove)
6995 OperationType = 2;
6996 else if (BId == Builtin::BImemcmp)
6997 OperationType = 3;
6998 }
6999
John McCall31168b02011-06-15 23:02:42 +00007000 DiagRuntimeBehavior(
7001 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007002 PDiag(diag::warn_dyn_class_memaccess)
7003 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7004 << FnName << IsContained << ContainedRD << OperationType
7005 << Call->getCallee()->getSourceRange());
7006 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7007 BId != Builtin::BImemset)
7008 DiagRuntimeBehavior(
7009 Dest->getExprLoc(), Dest,
7010 PDiag(diag::warn_arc_object_memaccess)
7011 << ArgIdx << FnName << PointeeTy
7012 << Call->getCallee()->getSourceRange());
7013 else
7014 continue;
7015
7016 DiagRuntimeBehavior(
7017 Dest->getExprLoc(), Dest,
7018 PDiag(diag::note_bad_memaccess_silence)
7019 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7020 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007021 }
7022}
7023
Ted Kremenek6865f772011-08-18 20:55:45 +00007024// A little helper routine: ignore addition and subtraction of integer literals.
7025// This intentionally does not ignore all integer constant expressions because
7026// we don't want to remove sizeof().
7027static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7028 Ex = Ex->IgnoreParenCasts();
7029
7030 for (;;) {
7031 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7032 if (!BO || !BO->isAdditiveOp())
7033 break;
7034
7035 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7036 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7037
7038 if (isa<IntegerLiteral>(RHS))
7039 Ex = LHS;
7040 else if (isa<IntegerLiteral>(LHS))
7041 Ex = RHS;
7042 else
7043 break;
7044 }
7045
7046 return Ex;
7047}
7048
Anna Zaks13b08572012-08-08 21:42:23 +00007049static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7050 ASTContext &Context) {
7051 // Only handle constant-sized or VLAs, but not flexible members.
7052 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7053 // Only issue the FIXIT for arrays of size > 1.
7054 if (CAT->getSize().getSExtValue() <= 1)
7055 return false;
7056 } else if (!Ty->isVariableArrayType()) {
7057 return false;
7058 }
7059 return true;
7060}
7061
Ted Kremenek6865f772011-08-18 20:55:45 +00007062// Warn if the user has made the 'size' argument to strlcpy or strlcat
7063// be the size of the source, instead of the destination.
7064void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7065 IdentifierInfo *FnName) {
7066
7067 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007068 unsigned NumArgs = Call->getNumArgs();
7069 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007070 return;
7071
7072 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7073 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007074 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007075
7076 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7077 Call->getLocStart(), Call->getRParenLoc()))
7078 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00007079
7080 // Look for 'strlcpy(dst, x, sizeof(x))'
7081 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7082 CompareWithSrc = Ex;
7083 else {
7084 // Look for 'strlcpy(dst, x, strlen(x))'
7085 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00007086 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7087 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00007088 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7089 }
7090 }
7091
7092 if (!CompareWithSrc)
7093 return;
7094
7095 // Determine if the argument to sizeof/strlen is equal to the source
7096 // argument. In principle there's all kinds of things you could do
7097 // here, for instance creating an == expression and evaluating it with
7098 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7099 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7100 if (!SrcArgDRE)
7101 return;
7102
7103 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7104 if (!CompareWithSrcDRE ||
7105 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7106 return;
7107
7108 const Expr *OriginalSizeArg = Call->getArg(2);
7109 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7110 << OriginalSizeArg->getSourceRange() << FnName;
7111
7112 // Output a FIXIT hint if the destination is an array (rather than a
7113 // pointer to an array). This could be enhanced to handle some
7114 // pointers if we know the actual size, like if DstArg is 'array+2'
7115 // we could say 'sizeof(array)-2'.
7116 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00007117 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00007118 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007119
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007120 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007121 llvm::raw_svector_ostream OS(sizeString);
7122 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007123 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00007124 OS << ")";
7125
7126 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7127 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7128 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00007129}
7130
Anna Zaks314cd092012-02-01 19:08:57 +00007131/// Check if two expressions refer to the same declaration.
7132static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7133 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7134 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7135 return D1->getDecl() == D2->getDecl();
7136 return false;
7137}
7138
7139static const Expr *getStrlenExprArg(const Expr *E) {
7140 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7141 const FunctionDecl *FD = CE->getDirectCallee();
7142 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00007143 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007144 return CE->getArg(0)->IgnoreParenCasts();
7145 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007146 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007147}
7148
7149// Warn on anti-patterns as the 'size' argument to strncat.
7150// The correct size argument should look like following:
7151// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7152void Sema::CheckStrncatArguments(const CallExpr *CE,
7153 IdentifierInfo *FnName) {
7154 // Don't crash if the user has the wrong number of arguments.
7155 if (CE->getNumArgs() < 3)
7156 return;
7157 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7158 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7159 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7160
Nico Weber0e6daef2013-12-26 23:38:39 +00007161 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7162 CE->getRParenLoc()))
7163 return;
7164
Anna Zaks314cd092012-02-01 19:08:57 +00007165 // Identify common expressions, which are wrongly used as the size argument
7166 // to strncat and may lead to buffer overflows.
7167 unsigned PatternType = 0;
7168 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7169 // - sizeof(dst)
7170 if (referToTheSameDecl(SizeOfArg, DstArg))
7171 PatternType = 1;
7172 // - sizeof(src)
7173 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7174 PatternType = 2;
7175 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7176 if (BE->getOpcode() == BO_Sub) {
7177 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7178 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7179 // - sizeof(dst) - strlen(dst)
7180 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7181 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7182 PatternType = 1;
7183 // - sizeof(src) - (anything)
7184 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7185 PatternType = 2;
7186 }
7187 }
7188
7189 if (PatternType == 0)
7190 return;
7191
Anna Zaks5069aa32012-02-03 01:27:37 +00007192 // Generate the diagnostic.
7193 SourceLocation SL = LenArg->getLocStart();
7194 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007195 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00007196
7197 // If the function is defined as a builtin macro, do not show macro expansion.
7198 if (SM.isMacroArgExpansion(SL)) {
7199 SL = SM.getSpellingLoc(SL);
7200 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7201 SM.getSpellingLoc(SR.getEnd()));
7202 }
7203
Anna Zaks13b08572012-08-08 21:42:23 +00007204 // Check if the destination is an array (rather than a pointer to an array).
7205 QualType DstTy = DstArg->getType();
7206 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7207 Context);
7208 if (!isKnownSizeArray) {
7209 if (PatternType == 1)
7210 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7211 else
7212 Diag(SL, diag::warn_strncat_src_size) << SR;
7213 return;
7214 }
7215
Anna Zaks314cd092012-02-01 19:08:57 +00007216 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00007217 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007218 else
Anna Zaks5069aa32012-02-03 01:27:37 +00007219 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007220
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007221 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00007222 llvm::raw_svector_ostream OS(sizeString);
7223 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007224 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007225 OS << ") - ";
7226 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007227 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007228 OS << ") - 1";
7229
Anna Zaks5069aa32012-02-03 01:27:37 +00007230 Diag(SL, diag::note_strncat_wrong_size)
7231 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00007232}
7233
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007234//===--- CHECK: Return Address of Stack Variable --------------------------===//
7235
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007236static const Expr *EvalVal(const Expr *E,
7237 SmallVectorImpl<const DeclRefExpr *> &refVars,
7238 const Decl *ParentDecl);
7239static const Expr *EvalAddr(const Expr *E,
7240 SmallVectorImpl<const DeclRefExpr *> &refVars,
7241 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007242
7243/// CheckReturnStackAddr - Check if a return statement returns the address
7244/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007245static void
7246CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7247 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00007248
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007249 const Expr *stackE = nullptr;
7250 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007251
7252 // Perform checking for returned stack addresses, local blocks,
7253 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00007254 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007255 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007256 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00007257 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007258 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007259 }
7260
Craig Topperc3ec1492014-05-26 06:22:03 +00007261 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007262 return; // Nothing suspicious was found.
7263
Richard Trieu81b6c562016-08-05 23:24:47 +00007264 // Parameters are initalized in the calling scope, so taking the address
7265 // of a parameter reference doesn't need a warning.
7266 for (auto *DRE : refVars)
7267 if (isa<ParmVarDecl>(DRE->getDecl()))
7268 return;
7269
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007270 SourceLocation diagLoc;
7271 SourceRange diagRange;
7272 if (refVars.empty()) {
7273 diagLoc = stackE->getLocStart();
7274 diagRange = stackE->getSourceRange();
7275 } else {
7276 // We followed through a reference variable. 'stackE' contains the
7277 // problematic expression but we will warn at the return statement pointing
7278 // at the reference variable. We will later display the "trail" of
7279 // reference variables using notes.
7280 diagLoc = refVars[0]->getLocStart();
7281 diagRange = refVars[0]->getSourceRange();
7282 }
7283
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007284 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7285 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00007286 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007287 << DR->getDecl()->getDeclName() << diagRange;
7288 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007289 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007290 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007291 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007292 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00007293 // If there is an LValue->RValue conversion, then the value of the
7294 // reference type is used, not the reference.
7295 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7296 if (ICE->getCastKind() == CK_LValueToRValue) {
7297 return;
7298 }
7299 }
Craig Topperda7b27f2015-11-17 05:40:09 +00007300 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7301 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007302 }
7303
7304 // Display the "trail" of reference variables that we followed until we
7305 // found the problematic expression using notes.
7306 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007307 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007308 // If this var binds to another reference var, show the range of the next
7309 // var, otherwise the var binds to the problematic expression, in which case
7310 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007311 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7312 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007313 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7314 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007315 }
7316}
7317
7318/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7319/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007320/// to a location on the stack, a local block, an address of a label, or a
7321/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007322/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007323/// encounter a subexpression that (1) clearly does not lead to one of the
7324/// above problematic expressions (2) is something we cannot determine leads to
7325/// a problematic expression based on such local checking.
7326///
7327/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7328/// the expression that they point to. Such variables are added to the
7329/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007330///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007331/// EvalAddr processes expressions that are pointers that are used as
7332/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007333/// At the base case of the recursion is a check for the above problematic
7334/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007335///
7336/// This implementation handles:
7337///
7338/// * pointer-to-pointer casts
7339/// * implicit conversions from array references to pointers
7340/// * taking the address of fields
7341/// * arbitrary interplay between "&" and "*" operators
7342/// * pointer arithmetic from an address of a stack variable
7343/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007344static const Expr *EvalAddr(const Expr *E,
7345 SmallVectorImpl<const DeclRefExpr *> &refVars,
7346 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007347 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00007348 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007349
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007350 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00007351 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00007352 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007353 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00007354 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00007355
Peter Collingbourne91147592011-04-15 00:35:48 +00007356 E = E->IgnoreParens();
7357
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007358 // Our "symbolic interpreter" is just a dispatch off the currently
7359 // viewed AST node. We then recursively traverse the AST by calling
7360 // EvalAddr and EvalVal appropriately.
7361 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007362 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007363 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007364
Richard Smith40f08eb2014-01-30 22:05:38 +00007365 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00007366 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00007367 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00007368
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007369 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007370 // If this is a reference variable, follow through to the expression that
7371 // it points to.
7372 if (V->hasLocalStorage() &&
7373 V->getType()->isReferenceType() && V->hasInit()) {
7374 // Add the reference variable to the "trail".
7375 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007376 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007377 }
7378
Craig Topperc3ec1492014-05-26 06:22:03 +00007379 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007380 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007381
Chris Lattner934edb22007-12-28 05:31:15 +00007382 case Stmt::UnaryOperatorClass: {
7383 // The only unary operator that make sense to handle here
7384 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007385 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007386
John McCalle3027922010-08-25 11:45:40 +00007387 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007388 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007389 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007390 }
Mike Stump11289f42009-09-09 15:08:12 +00007391
Chris Lattner934edb22007-12-28 05:31:15 +00007392 case Stmt::BinaryOperatorClass: {
7393 // Handle pointer arithmetic. All other binary operators are not valid
7394 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007395 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00007396 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00007397
John McCalle3027922010-08-25 11:45:40 +00007398 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00007399 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007400
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007401 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00007402
7403 // Determine which argument is the real pointer base. It could be
7404 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007405 if (!Base->getType()->isPointerType())
7406 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00007407
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007408 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007409 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007410 }
Steve Naroff2752a172008-09-10 19:17:48 +00007411
Chris Lattner934edb22007-12-28 05:31:15 +00007412 // For conditional operators we need to see if either the LHS or RHS are
7413 // valid DeclRefExpr*s. If one of them is valid, we return it.
7414 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007415 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007416
Chris Lattner934edb22007-12-28 05:31:15 +00007417 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007418 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007419 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007420 // In C++, we can have a throw-expression, which has 'void' type.
7421 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007422 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007423 return LHS;
7424 }
Chris Lattner934edb22007-12-28 05:31:15 +00007425
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007426 // In C++, we can have a throw-expression, which has 'void' type.
7427 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00007428 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007429
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007430 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007431 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007432
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007433 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00007434 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007435 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00007436 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007437
7438 case Stmt::AddrLabelExprClass:
7439 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00007440
John McCall28fc7092011-11-10 05:35:25 +00007441 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007442 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7443 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00007444
Ted Kremenekc3b4c522008-08-07 00:49:01 +00007445 // For casts, we need to handle conversions from arrays to
7446 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00007447 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00007448 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007449 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00007450 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00007451 case Stmt::CXXStaticCastExprClass:
7452 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00007453 case Stmt::CXXConstCastExprClass:
7454 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007455 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00007456 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00007457 case CK_LValueToRValue:
7458 case CK_NoOp:
7459 case CK_BaseToDerived:
7460 case CK_DerivedToBase:
7461 case CK_UncheckedDerivedToBase:
7462 case CK_Dynamic:
7463 case CK_CPointerToObjCPointerCast:
7464 case CK_BlockPointerToObjCPointerCast:
7465 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007466 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007467
7468 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007469 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007470
Richard Trieudadefde2014-07-02 04:39:38 +00007471 case CK_BitCast:
7472 if (SubExpr->getType()->isAnyPointerType() ||
7473 SubExpr->getType()->isBlockPointerType() ||
7474 SubExpr->getType()->isObjCQualifiedIdType())
7475 return EvalAddr(SubExpr, refVars, ParentDecl);
7476 else
7477 return nullptr;
7478
Eli Friedman8195ad72012-02-23 23:04:32 +00007479 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007480 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00007481 }
Chris Lattner934edb22007-12-28 05:31:15 +00007482 }
Mike Stump11289f42009-09-09 15:08:12 +00007483
Douglas Gregorfe314812011-06-21 17:03:29 +00007484 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007485 if (const Expr *Result =
7486 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7487 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00007488 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00007489 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007490
Chris Lattner934edb22007-12-28 05:31:15 +00007491 // Everything else: we simply don't reason about them.
7492 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007493 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00007494 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007495}
Mike Stump11289f42009-09-09 15:08:12 +00007496
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007497/// EvalVal - This function is complements EvalAddr in the mutual recursion.
7498/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007499static const Expr *EvalVal(const Expr *E,
7500 SmallVectorImpl<const DeclRefExpr *> &refVars,
7501 const Decl *ParentDecl) {
7502 do {
7503 // We should only be called for evaluating non-pointer expressions, or
7504 // expressions with a pointer type that are not used as references but
7505 // instead
7506 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00007507
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007508 // Our "symbolic interpreter" is just a dispatch off the currently
7509 // viewed AST node. We then recursively traverse the AST by calling
7510 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00007511
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007512 E = E->IgnoreParens();
7513 switch (E->getStmtClass()) {
7514 case Stmt::ImplicitCastExprClass: {
7515 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7516 if (IE->getValueKind() == VK_LValue) {
7517 E = IE->getSubExpr();
7518 continue;
7519 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007520 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007521 }
Richard Smith40f08eb2014-01-30 22:05:38 +00007522
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007523 case Stmt::ExprWithCleanupsClass:
7524 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7525 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007526
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007527 case Stmt::DeclRefExprClass: {
7528 // When we hit a DeclRefExpr we are looking at code that refers to a
7529 // variable's name. If it's not a reference variable we check if it has
7530 // local storage within the function, and if so, return the expression.
7531 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7532
7533 // If we leave the immediate function, the lifetime isn't about to end.
7534 if (DR->refersToEnclosingVariableOrCapture())
7535 return nullptr;
7536
7537 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7538 // Check if it refers to itself, e.g. "int& i = i;".
7539 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007540 return DR;
7541
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007542 if (V->hasLocalStorage()) {
7543 if (!V->getType()->isReferenceType())
7544 return DR;
7545
7546 // Reference variable, follow through to the expression that
7547 // it points to.
7548 if (V->hasInit()) {
7549 // Add the reference variable to the "trail".
7550 refVars.push_back(DR);
7551 return EvalVal(V->getInit(), refVars, V);
7552 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007553 }
7554 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007555
7556 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007557 }
Mike Stump11289f42009-09-09 15:08:12 +00007558
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007559 case Stmt::UnaryOperatorClass: {
7560 // The only unary operator that make sense to handle here
7561 // is Deref. All others don't resolve to a "name." This includes
7562 // handling all sorts of rvalues passed to a unary operator.
7563 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007564
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007565 if (U->getOpcode() == UO_Deref)
7566 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007567
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007568 return nullptr;
7569 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007570
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007571 case Stmt::ArraySubscriptExprClass: {
7572 // Array subscripts are potential references to data on the stack. We
7573 // retrieve the DeclRefExpr* for the array variable if it indeed
7574 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00007575 const auto *ASE = cast<ArraySubscriptExpr>(E);
7576 if (ASE->isTypeDependent())
7577 return nullptr;
7578 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007579 }
Mike Stump11289f42009-09-09 15:08:12 +00007580
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007581 case Stmt::OMPArraySectionExprClass: {
7582 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7583 ParentDecl);
7584 }
Mike Stump11289f42009-09-09 15:08:12 +00007585
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007586 case Stmt::ConditionalOperatorClass: {
7587 // For conditional operators we need to see if either the LHS or RHS are
7588 // non-NULL Expr's. If one is non-NULL, we return it.
7589 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007590
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007591 // Handle the GNU extension for missing LHS.
7592 if (const Expr *LHSExpr = C->getLHS()) {
7593 // In C++, we can have a throw-expression, which has 'void' type.
7594 if (!LHSExpr->getType()->isVoidType())
7595 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7596 return LHS;
7597 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007598
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007599 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007600 if (C->getRHS()->getType()->isVoidType())
7601 return nullptr;
7602
7603 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007604 }
7605
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007606 // Accesses to members are potential references to data on the stack.
7607 case Stmt::MemberExprClass: {
7608 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00007609
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007610 // Check for indirect access. We only want direct field accesses.
7611 if (M->isArrow())
7612 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007613
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007614 // Check whether the member type is itself a reference, in which case
7615 // we're not going to refer to the member, but to what the member refers
7616 // to.
7617 if (M->getMemberDecl()->getType()->isReferenceType())
7618 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007619
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007620 return EvalVal(M->getBase(), refVars, ParentDecl);
7621 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00007622
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007623 case Stmt::MaterializeTemporaryExprClass:
7624 if (const Expr *Result =
7625 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7626 refVars, ParentDecl))
7627 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007628 return E;
7629
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007630 default:
7631 // Check that we don't return or take the address of a reference to a
7632 // temporary. This is only useful in C++.
7633 if (!E->isTypeDependent() && E->isRValue())
7634 return E;
7635
7636 // Everything else: we simply don't reason about them.
7637 return nullptr;
7638 }
7639 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007640}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007641
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007642void
7643Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7644 SourceLocation ReturnLoc,
7645 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00007646 const AttrVec *Attrs,
7647 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007648 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7649
7650 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00007651 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7652 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00007653 CheckNonNullExpr(*this, RetValExp))
7654 Diag(ReturnLoc, diag::warn_null_ret)
7655 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00007656
7657 // C++11 [basic.stc.dynamic.allocation]p4:
7658 // If an allocation function declared with a non-throwing
7659 // exception-specification fails to allocate storage, it shall return
7660 // a null pointer. Any other allocation function that fails to allocate
7661 // storage shall indicate failure only by throwing an exception [...]
7662 if (FD) {
7663 OverloadedOperatorKind Op = FD->getOverloadedOperator();
7664 if (Op == OO_New || Op == OO_Array_New) {
7665 const FunctionProtoType *Proto
7666 = FD->getType()->castAs<FunctionProtoType>();
7667 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7668 CheckNonNullExpr(*this, RetValExp))
7669 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7670 << FD << getLangOpts().CPlusPlus11;
7671 }
7672 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007673}
7674
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007675//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7676
7677/// Check for comparisons of floating point operands using != and ==.
7678/// Issue a warning if these are no self-comparisons, as they are not likely
7679/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00007680void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00007681 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7682 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007683
7684 // Special case: check for x == x (which is OK).
7685 // Do not emit warnings for such cases.
7686 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7687 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7688 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00007689 return;
Mike Stump11289f42009-09-09 15:08:12 +00007690
Ted Kremenekeda40e22007-11-29 00:59:04 +00007691 // Special case: check for comparisons against literals that can be exactly
7692 // represented by APFloat. In such cases, do not emit a warning. This
7693 // is a heuristic: often comparison against such literals are used to
7694 // detect if a value in a variable has not changed. This clearly can
7695 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00007696 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7697 if (FLL->isExact())
7698 return;
7699 } else
7700 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7701 if (FLR->isExact())
7702 return;
Mike Stump11289f42009-09-09 15:08:12 +00007703
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007704 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00007705 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007706 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007707 return;
Mike Stump11289f42009-09-09 15:08:12 +00007708
David Blaikie1f4ff152012-07-16 20:47:22 +00007709 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007710 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007711 return;
Mike Stump11289f42009-09-09 15:08:12 +00007712
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007713 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00007714 Diag(Loc, diag::warn_floatingpoint_eq)
7715 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007716}
John McCallca01b222010-01-04 23:21:16 +00007717
John McCall70aa5392010-01-06 05:24:50 +00007718//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7719//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00007720
John McCall70aa5392010-01-06 05:24:50 +00007721namespace {
John McCallca01b222010-01-04 23:21:16 +00007722
John McCall70aa5392010-01-06 05:24:50 +00007723/// Structure recording the 'active' range of an integer-valued
7724/// expression.
7725struct IntRange {
7726 /// The number of bits active in the int.
7727 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00007728
John McCall70aa5392010-01-06 05:24:50 +00007729 /// True if the int is known not to have negative values.
7730 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00007731
John McCall70aa5392010-01-06 05:24:50 +00007732 IntRange(unsigned Width, bool NonNegative)
7733 : Width(Width), NonNegative(NonNegative)
7734 {}
John McCallca01b222010-01-04 23:21:16 +00007735
John McCall817d4af2010-11-10 23:38:19 +00007736 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00007737 static IntRange forBoolType() {
7738 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00007739 }
7740
John McCall817d4af2010-11-10 23:38:19 +00007741 /// Returns the range of an opaque value of the given integral type.
7742 static IntRange forValueOfType(ASTContext &C, QualType T) {
7743 return forValueOfCanonicalType(C,
7744 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00007745 }
7746
John McCall817d4af2010-11-10 23:38:19 +00007747 /// Returns the range of an opaque value of a canonical integral type.
7748 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00007749 assert(T->isCanonicalUnqualified());
7750
7751 if (const VectorType *VT = dyn_cast<VectorType>(T))
7752 T = VT->getElementType().getTypePtr();
7753 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7754 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007755 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7756 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00007757
David Majnemer6a426652013-06-07 22:07:20 +00007758 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00007759 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00007760 EnumDecl *Enum = ET->getDecl();
7761 if (!Enum->isCompleteDefinition())
7762 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00007763
David Majnemer6a426652013-06-07 22:07:20 +00007764 unsigned NumPositive = Enum->getNumPositiveBits();
7765 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00007766
David Majnemer6a426652013-06-07 22:07:20 +00007767 if (NumNegative == 0)
7768 return IntRange(NumPositive, true/*NonNegative*/);
7769 else
7770 return IntRange(std::max(NumPositive + 1, NumNegative),
7771 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00007772 }
John McCall70aa5392010-01-06 05:24:50 +00007773
7774 const BuiltinType *BT = cast<BuiltinType>(T);
7775 assert(BT->isInteger());
7776
7777 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7778 }
7779
John McCall817d4af2010-11-10 23:38:19 +00007780 /// Returns the "target" range of a canonical integral type, i.e.
7781 /// the range of values expressible in the type.
7782 ///
7783 /// This matches forValueOfCanonicalType except that enums have the
7784 /// full range of their type, not the range of their enumerators.
7785 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7786 assert(T->isCanonicalUnqualified());
7787
7788 if (const VectorType *VT = dyn_cast<VectorType>(T))
7789 T = VT->getElementType().getTypePtr();
7790 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7791 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007792 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7793 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007794 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00007795 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007796
7797 const BuiltinType *BT = cast<BuiltinType>(T);
7798 assert(BT->isInteger());
7799
7800 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7801 }
7802
7803 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00007804 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00007805 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00007806 L.NonNegative && R.NonNegative);
7807 }
7808
John McCall817d4af2010-11-10 23:38:19 +00007809 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00007810 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00007811 return IntRange(std::min(L.Width, R.Width),
7812 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00007813 }
7814};
7815
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007816IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007817 if (value.isSigned() && value.isNegative())
7818 return IntRange(value.getMinSignedBits(), false);
7819
7820 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00007821 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007822
7823 // isNonNegative() just checks the sign bit without considering
7824 // signedness.
7825 return IntRange(value.getActiveBits(), true);
7826}
7827
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007828IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7829 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007830 if (result.isInt())
7831 return GetValueRange(C, result.getInt(), MaxWidth);
7832
7833 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00007834 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7835 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7836 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7837 R = IntRange::join(R, El);
7838 }
John McCall70aa5392010-01-06 05:24:50 +00007839 return R;
7840 }
7841
7842 if (result.isComplexInt()) {
7843 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7844 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7845 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00007846 }
7847
7848 // This can happen with lossless casts to intptr_t of "based" lvalues.
7849 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00007850 // FIXME: The only reason we need to pass the type in here is to get
7851 // the sign right on this one case. It would be nice if APValue
7852 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007853 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00007854 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00007855}
John McCall70aa5392010-01-06 05:24:50 +00007856
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007857QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007858 QualType Ty = E->getType();
7859 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7860 Ty = AtomicRHS->getValueType();
7861 return Ty;
7862}
7863
John McCall70aa5392010-01-06 05:24:50 +00007864/// Pseudo-evaluate the given integer expression, estimating the
7865/// range of values it might take.
7866///
7867/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007868IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007869 E = E->IgnoreParens();
7870
7871 // Try a full evaluation first.
7872 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007873 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00007874 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007875
7876 // I think we only want to look through implicit casts here; if the
7877 // user has an explicit widening cast, we should treat the value as
7878 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007879 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00007880 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00007881 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7882
Eli Friedmane6d33952013-07-08 20:20:06 +00007883 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00007884
George Burgess IVdf1ed002016-01-13 01:52:39 +00007885 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7886 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00007887
John McCall70aa5392010-01-06 05:24:50 +00007888 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00007889 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00007890 return OutputTypeRange;
7891
7892 IntRange SubRange
7893 = GetExprRange(C, CE->getSubExpr(),
7894 std::min(MaxWidth, OutputTypeRange.Width));
7895
7896 // Bail out if the subexpr's range is as wide as the cast type.
7897 if (SubRange.Width >= OutputTypeRange.Width)
7898 return OutputTypeRange;
7899
7900 // Otherwise, we take the smaller width, and we're non-negative if
7901 // either the output type or the subexpr is.
7902 return IntRange(SubRange.Width,
7903 SubRange.NonNegative || OutputTypeRange.NonNegative);
7904 }
7905
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007906 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007907 // If we can fold the condition, just take that operand.
7908 bool CondResult;
7909 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7910 return GetExprRange(C, CondResult ? CO->getTrueExpr()
7911 : CO->getFalseExpr(),
7912 MaxWidth);
7913
7914 // Otherwise, conservatively merge.
7915 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7916 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7917 return IntRange::join(L, R);
7918 }
7919
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007920 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007921 switch (BO->getOpcode()) {
7922
7923 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00007924 case BO_LAnd:
7925 case BO_LOr:
7926 case BO_LT:
7927 case BO_GT:
7928 case BO_LE:
7929 case BO_GE:
7930 case BO_EQ:
7931 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00007932 return IntRange::forBoolType();
7933
John McCallc3688382011-07-13 06:35:24 +00007934 // The type of the assignments is the type of the LHS, so the RHS
7935 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00007936 case BO_MulAssign:
7937 case BO_DivAssign:
7938 case BO_RemAssign:
7939 case BO_AddAssign:
7940 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00007941 case BO_XorAssign:
7942 case BO_OrAssign:
7943 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00007944 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00007945
John McCallc3688382011-07-13 06:35:24 +00007946 // Simple assignments just pass through the RHS, which will have
7947 // been coerced to the LHS type.
7948 case BO_Assign:
7949 // TODO: bitfields?
7950 return GetExprRange(C, BO->getRHS(), MaxWidth);
7951
John McCall70aa5392010-01-06 05:24:50 +00007952 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00007953 case BO_PtrMemD:
7954 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00007955 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007956
John McCall2ce81ad2010-01-06 22:07:33 +00007957 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00007958 case BO_And:
7959 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00007960 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
7961 GetExprRange(C, BO->getRHS(), MaxWidth));
7962
John McCall70aa5392010-01-06 05:24:50 +00007963 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00007964 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00007965 // ...except that we want to treat '1 << (blah)' as logically
7966 // positive. It's an important idiom.
7967 if (IntegerLiteral *I
7968 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
7969 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007970 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00007971 return IntRange(R.Width, /*NonNegative*/ true);
7972 }
7973 }
7974 // fallthrough
7975
John McCalle3027922010-08-25 11:45:40 +00007976 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00007977 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007978
John McCall2ce81ad2010-01-06 22:07:33 +00007979 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00007980 case BO_Shr:
7981 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00007982 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7983
7984 // If the shift amount is a positive constant, drop the width by
7985 // that much.
7986 llvm::APSInt shift;
7987 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
7988 shift.isNonNegative()) {
7989 unsigned zext = shift.getZExtValue();
7990 if (zext >= L.Width)
7991 L.Width = (L.NonNegative ? 0 : 1);
7992 else
7993 L.Width -= zext;
7994 }
7995
7996 return L;
7997 }
7998
7999 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008000 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008001 return GetExprRange(C, BO->getRHS(), MaxWidth);
8002
John McCall2ce81ad2010-01-06 22:07:33 +00008003 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008004 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008005 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008006 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008007 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008008
John McCall51431812011-07-14 22:39:48 +00008009 // The width of a division result is mostly determined by the size
8010 // of the LHS.
8011 case BO_Div: {
8012 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008013 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008014 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8015
8016 // If the divisor is constant, use that.
8017 llvm::APSInt divisor;
8018 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8019 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8020 if (log2 >= L.Width)
8021 L.Width = (L.NonNegative ? 0 : 1);
8022 else
8023 L.Width = std::min(L.Width - log2, MaxWidth);
8024 return L;
8025 }
8026
8027 // Otherwise, just use the LHS's width.
8028 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8029 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8030 }
8031
8032 // The result of a remainder can't be larger than the result of
8033 // either side.
8034 case BO_Rem: {
8035 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008036 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008037 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8038 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8039
8040 IntRange meet = IntRange::meet(L, R);
8041 meet.Width = std::min(meet.Width, MaxWidth);
8042 return meet;
8043 }
8044
8045 // The default behavior is okay for these.
8046 case BO_Mul:
8047 case BO_Add:
8048 case BO_Xor:
8049 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008050 break;
8051 }
8052
John McCall51431812011-07-14 22:39:48 +00008053 // The default case is to treat the operation as if it were closed
8054 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008055 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8056 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8057 return IntRange::join(L, R);
8058 }
8059
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008060 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008061 switch (UO->getOpcode()) {
8062 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008063 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008064 return IntRange::forBoolType();
8065
8066 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008067 case UO_Deref:
8068 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00008069 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008070
8071 default:
8072 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8073 }
8074 }
8075
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008076 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00008077 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8078
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008079 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00008080 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00008081 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00008082
Eli Friedmane6d33952013-07-08 20:20:06 +00008083 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008084}
John McCall263a48b2010-01-04 23:31:57 +00008085
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008086IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008087 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00008088}
8089
John McCall263a48b2010-01-04 23:31:57 +00008090/// Checks whether the given value, which currently has the given
8091/// source semantics, has the same value when coerced through the
8092/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008093bool IsSameFloatAfterCast(const llvm::APFloat &value,
8094 const llvm::fltSemantics &Src,
8095 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008096 llvm::APFloat truncated = value;
8097
8098 bool ignored;
8099 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8100 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8101
8102 return truncated.bitwiseIsEqual(value);
8103}
8104
8105/// Checks whether the given value, which currently has the given
8106/// source semantics, has the same value when coerced through the
8107/// target semantics.
8108///
8109/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008110bool IsSameFloatAfterCast(const APValue &value,
8111 const llvm::fltSemantics &Src,
8112 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008113 if (value.isFloat())
8114 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8115
8116 if (value.isVector()) {
8117 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8118 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8119 return false;
8120 return true;
8121 }
8122
8123 assert(value.isComplexFloat());
8124 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8125 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8126}
8127
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008128void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008129
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008130bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00008131 // Suppress cases where we are comparing against an enum constant.
8132 if (const DeclRefExpr *DR =
8133 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8134 if (isa<EnumConstantDecl>(DR->getDecl()))
8135 return false;
8136
8137 // Suppress cases where the '0' value is expanded from a macro.
8138 if (E->getLocStart().isMacroID())
8139 return false;
8140
John McCallcc7e5bf2010-05-06 08:58:33 +00008141 llvm::APSInt Value;
8142 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8143}
8144
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008145bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00008146 // Strip off implicit integral promotions.
8147 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008148 if (ICE->getCastKind() != CK_IntegralCast &&
8149 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00008150 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008151 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00008152 }
8153
8154 return E->getType()->isEnumeralType();
8155}
8156
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008157void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00008158 // Disable warning in template instantiations.
8159 if (!S.ActiveTemplateInstantiations.empty())
8160 return;
8161
John McCalle3027922010-08-25 11:45:40 +00008162 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00008163 if (E->isValueDependent())
8164 return;
8165
John McCalle3027922010-08-25 11:45:40 +00008166 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008167 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008168 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008169 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008170 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008171 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008172 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008173 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008174 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008175 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008176 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008177 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008178 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008179 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008180 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008181 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8182 }
8183}
8184
Benjamin Kramer7320b992016-06-15 14:20:56 +00008185void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8186 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008187 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00008188 // Disable warning in template instantiations.
8189 if (!S.ActiveTemplateInstantiations.empty())
8190 return;
8191
Richard Trieu0f097742014-04-04 04:13:47 +00008192 // TODO: Investigate using GetExprRange() to get tighter bounds
8193 // on the bit ranges.
8194 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00008195 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00008196 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00008197 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8198 unsigned OtherWidth = OtherRange.Width;
8199
8200 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8201
Richard Trieu560910c2012-11-14 22:50:24 +00008202 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00008203 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00008204 return;
8205
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008206 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00008207 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008208
Richard Trieu0f097742014-04-04 04:13:47 +00008209 // Used for diagnostic printout.
8210 enum {
8211 LiteralConstant = 0,
8212 CXXBoolLiteralTrue,
8213 CXXBoolLiteralFalse
8214 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008215
Richard Trieu0f097742014-04-04 04:13:47 +00008216 if (!OtherIsBooleanType) {
8217 QualType ConstantT = Constant->getType();
8218 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00008219
Richard Trieu0f097742014-04-04 04:13:47 +00008220 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8221 return;
8222 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8223 "comparison with non-integer type");
8224
8225 bool ConstantSigned = ConstantT->isSignedIntegerType();
8226 bool CommonSigned = CommonT->isSignedIntegerType();
8227
8228 bool EqualityOnly = false;
8229
8230 if (CommonSigned) {
8231 // The common type is signed, therefore no signed to unsigned conversion.
8232 if (!OtherRange.NonNegative) {
8233 // Check that the constant is representable in type OtherT.
8234 if (ConstantSigned) {
8235 if (OtherWidth >= Value.getMinSignedBits())
8236 return;
8237 } else { // !ConstantSigned
8238 if (OtherWidth >= Value.getActiveBits() + 1)
8239 return;
8240 }
8241 } else { // !OtherSigned
8242 // Check that the constant is representable in type OtherT.
8243 // Negative values are out of range.
8244 if (ConstantSigned) {
8245 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8246 return;
8247 } else { // !ConstantSigned
8248 if (OtherWidth >= Value.getActiveBits())
8249 return;
8250 }
Richard Trieu560910c2012-11-14 22:50:24 +00008251 }
Richard Trieu0f097742014-04-04 04:13:47 +00008252 } else { // !CommonSigned
8253 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00008254 if (OtherWidth >= Value.getActiveBits())
8255 return;
Craig Toppercf360162014-06-18 05:13:11 +00008256 } else { // OtherSigned
8257 assert(!ConstantSigned &&
8258 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00008259 // Check to see if the constant is representable in OtherT.
8260 if (OtherWidth > Value.getActiveBits())
8261 return;
8262 // Check to see if the constant is equivalent to a negative value
8263 // cast to CommonT.
8264 if (S.Context.getIntWidth(ConstantT) ==
8265 S.Context.getIntWidth(CommonT) &&
8266 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8267 return;
8268 // The constant value rests between values that OtherT can represent
8269 // after conversion. Relational comparison still works, but equality
8270 // comparisons will be tautological.
8271 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008272 }
8273 }
Richard Trieu0f097742014-04-04 04:13:47 +00008274
8275 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8276
8277 if (op == BO_EQ || op == BO_NE) {
8278 IsTrue = op == BO_NE;
8279 } else if (EqualityOnly) {
8280 return;
8281 } else if (RhsConstant) {
8282 if (op == BO_GT || op == BO_GE)
8283 IsTrue = !PositiveConstant;
8284 else // op == BO_LT || op == BO_LE
8285 IsTrue = PositiveConstant;
8286 } else {
8287 if (op == BO_LT || op == BO_LE)
8288 IsTrue = !PositiveConstant;
8289 else // op == BO_GT || op == BO_GE
8290 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008291 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008292 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00008293 // Other isKnownToHaveBooleanValue
8294 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8295 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8296 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8297
8298 static const struct LinkedConditions {
8299 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8300 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8301 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8302 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8303 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8304 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8305
8306 } TruthTable = {
8307 // Constant on LHS. | Constant on RHS. |
8308 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
8309 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8310 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8311 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8312 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8313 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8314 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8315 };
8316
8317 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8318
8319 enum ConstantValue ConstVal = Zero;
8320 if (Value.isUnsigned() || Value.isNonNegative()) {
8321 if (Value == 0) {
8322 LiteralOrBoolConstant =
8323 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8324 ConstVal = Zero;
8325 } else if (Value == 1) {
8326 LiteralOrBoolConstant =
8327 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8328 ConstVal = One;
8329 } else {
8330 LiteralOrBoolConstant = LiteralConstant;
8331 ConstVal = GT_One;
8332 }
8333 } else {
8334 ConstVal = LT_Zero;
8335 }
8336
8337 CompareBoolWithConstantResult CmpRes;
8338
8339 switch (op) {
8340 case BO_LT:
8341 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8342 break;
8343 case BO_GT:
8344 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8345 break;
8346 case BO_LE:
8347 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8348 break;
8349 case BO_GE:
8350 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8351 break;
8352 case BO_EQ:
8353 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8354 break;
8355 case BO_NE:
8356 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8357 break;
8358 default:
8359 CmpRes = Unkwn;
8360 break;
8361 }
8362
8363 if (CmpRes == AFals) {
8364 IsTrue = false;
8365 } else if (CmpRes == ATrue) {
8366 IsTrue = true;
8367 } else {
8368 return;
8369 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008370 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008371
8372 // If this is a comparison to an enum constant, include that
8373 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00008374 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008375 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8376 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8377
8378 SmallString<64> PrettySourceValue;
8379 llvm::raw_svector_ostream OS(PrettySourceValue);
8380 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00008381 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008382 else
8383 OS << Value;
8384
Richard Trieu0f097742014-04-04 04:13:47 +00008385 S.DiagRuntimeBehavior(
8386 E->getOperatorLoc(), E,
8387 S.PDiag(diag::warn_out_of_range_compare)
8388 << OS.str() << LiteralOrBoolConstant
8389 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8390 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008391}
8392
John McCallcc7e5bf2010-05-06 08:58:33 +00008393/// Analyze the operands of the given comparison. Implements the
8394/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008395void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00008396 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8397 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008398}
John McCall263a48b2010-01-04 23:31:57 +00008399
John McCallca01b222010-01-04 23:21:16 +00008400/// \brief Implements -Wsign-compare.
8401///
Richard Trieu82402a02011-09-15 21:56:47 +00008402/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008403void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008404 // The type the comparison is being performed in.
8405 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00008406
8407 // Only analyze comparison operators where both sides have been converted to
8408 // the same type.
8409 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8410 return AnalyzeImpConvsInComparison(S, E);
8411
8412 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00008413 if (E->isValueDependent())
8414 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008415
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008416 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8417 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008418
8419 bool IsComparisonConstant = false;
8420
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008421 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008422 // of 'true' or 'false'.
8423 if (T->isIntegralType(S.Context)) {
8424 llvm::APSInt RHSValue;
8425 bool IsRHSIntegralLiteral =
8426 RHS->isIntegerConstantExpr(RHSValue, S.Context);
8427 llvm::APSInt LHSValue;
8428 bool IsLHSIntegralLiteral =
8429 LHS->isIntegerConstantExpr(LHSValue, S.Context);
8430 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8431 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8432 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8433 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8434 else
8435 IsComparisonConstant =
8436 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008437 } else if (!T->hasUnsignedIntegerRepresentation())
8438 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008439
John McCallcc7e5bf2010-05-06 08:58:33 +00008440 // We don't do anything special if this isn't an unsigned integral
8441 // comparison: we're only interested in integral comparisons, and
8442 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00008443 //
8444 // We also don't care about value-dependent expressions or expressions
8445 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008446 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00008447 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008448
John McCallcc7e5bf2010-05-06 08:58:33 +00008449 // Check to see if one of the (unmodified) operands is of different
8450 // signedness.
8451 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00008452 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8453 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00008454 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00008455 signedOperand = LHS;
8456 unsignedOperand = RHS;
8457 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8458 signedOperand = RHS;
8459 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00008460 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00008461 CheckTrivialUnsignedComparison(S, E);
8462 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008463 }
8464
John McCallcc7e5bf2010-05-06 08:58:33 +00008465 // Otherwise, calculate the effective range of the signed operand.
8466 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00008467
John McCallcc7e5bf2010-05-06 08:58:33 +00008468 // Go ahead and analyze implicit conversions in the operands. Note
8469 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00008470 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8471 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00008472
John McCallcc7e5bf2010-05-06 08:58:33 +00008473 // If the signed range is non-negative, -Wsign-compare won't fire,
8474 // but we should still check for comparisons which are always true
8475 // or false.
8476 if (signedRange.NonNegative)
8477 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008478
8479 // For (in)equality comparisons, if the unsigned operand is a
8480 // constant which cannot collide with a overflowed signed operand,
8481 // then reinterpreting the signed operand as unsigned will not
8482 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00008483 if (E->isEqualityOp()) {
8484 unsigned comparisonWidth = S.Context.getIntWidth(T);
8485 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00008486
John McCallcc7e5bf2010-05-06 08:58:33 +00008487 // We should never be unable to prove that the unsigned operand is
8488 // non-negative.
8489 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8490
8491 if (unsignedRange.Width < comparisonWidth)
8492 return;
8493 }
8494
Douglas Gregorbfb4a212012-05-01 01:53:49 +00008495 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8496 S.PDiag(diag::warn_mixed_sign_comparison)
8497 << LHS->getType() << RHS->getType()
8498 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00008499}
8500
John McCall1f425642010-11-11 03:21:53 +00008501/// Analyzes an attempt to assign the given value to a bitfield.
8502///
8503/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008504bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8505 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00008506 assert(Bitfield->isBitField());
8507 if (Bitfield->isInvalidDecl())
8508 return false;
8509
John McCalldeebbcf2010-11-11 05:33:51 +00008510 // White-list bool bitfields.
8511 if (Bitfield->getType()->isBooleanType())
8512 return false;
8513
Douglas Gregor789adec2011-02-04 13:09:01 +00008514 // Ignore value- or type-dependent expressions.
8515 if (Bitfield->getBitWidth()->isValueDependent() ||
8516 Bitfield->getBitWidth()->isTypeDependent() ||
8517 Init->isValueDependent() ||
8518 Init->isTypeDependent())
8519 return false;
8520
John McCall1f425642010-11-11 03:21:53 +00008521 Expr *OriginalInit = Init->IgnoreParenImpCasts();
8522
Richard Smith5fab0c92011-12-28 19:48:30 +00008523 llvm::APSInt Value;
8524 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00008525 return false;
8526
John McCall1f425642010-11-11 03:21:53 +00008527 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00008528 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00008529
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008530 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00008531 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008532 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8533 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00008534
John McCall1f425642010-11-11 03:21:53 +00008535 if (OriginalWidth <= FieldWidth)
8536 return false;
8537
Eli Friedmanc267a322012-01-26 23:11:39 +00008538 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00008539 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00008540 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00008541
Eli Friedmanc267a322012-01-26 23:11:39 +00008542 // Check whether the stored value is equal to the original value.
8543 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00008544 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00008545 return false;
8546
Eli Friedmanc267a322012-01-26 23:11:39 +00008547 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00008548 // therefore don't strictly fit into a signed bitfield of width 1.
8549 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00008550 return false;
8551
John McCall1f425642010-11-11 03:21:53 +00008552 std::string PrettyValue = Value.toString(10);
8553 std::string PrettyTrunc = TruncatedValue.toString(10);
8554
8555 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8556 << PrettyValue << PrettyTrunc << OriginalInit->getType()
8557 << Init->getSourceRange();
8558
8559 return true;
8560}
8561
John McCalld2a53122010-11-09 23:24:47 +00008562/// Analyze the given simple or compound assignment for warning-worthy
8563/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008564void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00008565 // Just recurse on the LHS.
8566 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8567
8568 // We want to recurse on the RHS as normal unless we're assigning to
8569 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00008570 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008571 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00008572 E->getOperatorLoc())) {
8573 // Recurse, ignoring any implicit conversions on the RHS.
8574 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8575 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00008576 }
8577 }
8578
8579 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8580}
8581
John McCall263a48b2010-01-04 23:31:57 +00008582/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008583void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8584 SourceLocation CContext, unsigned diag,
8585 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008586 if (pruneControlFlow) {
8587 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8588 S.PDiag(diag)
8589 << SourceType << T << E->getSourceRange()
8590 << SourceRange(CContext));
8591 return;
8592 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00008593 S.Diag(E->getExprLoc(), diag)
8594 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8595}
8596
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008597/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008598void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8599 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008600 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008601}
8602
Richard Trieube234c32016-04-21 21:04:55 +00008603
8604/// Diagnose an implicit cast from a floating point value to an integer value.
8605void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8606
8607 SourceLocation CContext) {
8608 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
8609 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
8610
8611 Expr *InnerE = E->IgnoreParenImpCasts();
8612 // We also want to warn on, e.g., "int i = -1.234"
8613 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8614 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8615 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8616
8617 const bool IsLiteral =
8618 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8619
8620 llvm::APFloat Value(0.0);
8621 bool IsConstant =
8622 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8623 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00008624 return DiagnoseImpCast(S, E, T, CContext,
8625 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00008626 }
8627
Chandler Carruth016ef402011-04-10 08:36:24 +00008628 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00008629
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00008630 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8631 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00008632 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8633 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00008634 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00008635 if (IsLiteral) return;
8636 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8637 PruneWarnings);
8638 }
8639
8640 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00008641 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00008642 // Warn on floating point literal to integer.
8643 DiagID = diag::warn_impcast_literal_float_to_integer;
8644 } else if (IntegerValue == 0) {
8645 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
8646 return DiagnoseImpCast(S, E, T, CContext,
8647 diag::warn_impcast_float_integer, PruneWarnings);
8648 }
8649 // Warn on non-zero to zero conversion.
8650 DiagID = diag::warn_impcast_float_to_integer_zero;
8651 } else {
8652 if (IntegerValue.isUnsigned()) {
8653 if (!IntegerValue.isMaxValue()) {
8654 return DiagnoseImpCast(S, E, T, CContext,
8655 diag::warn_impcast_float_integer, PruneWarnings);
8656 }
8657 } else { // IntegerValue.isSigned()
8658 if (!IntegerValue.isMaxSignedValue() &&
8659 !IntegerValue.isMinSignedValue()) {
8660 return DiagnoseImpCast(S, E, T, CContext,
8661 diag::warn_impcast_float_integer, PruneWarnings);
8662 }
8663 }
8664 // Warn on evaluatable floating point expression to integer conversion.
8665 DiagID = diag::warn_impcast_float_to_integer;
8666 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008667
Eli Friedman07185912013-08-29 23:44:43 +00008668 // FIXME: Force the precision of the source value down so we don't print
8669 // digits which are usually useless (we don't really care here if we
8670 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
8671 // would automatically print the shortest representation, but it's a bit
8672 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00008673 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00008674 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
8675 precision = (precision * 59 + 195) / 196;
8676 Value.toString(PrettySourceValue, precision);
8677
David Blaikie9b88cc02012-05-15 17:18:27 +00008678 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00008679 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00008680 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00008681 else
David Blaikie9b88cc02012-05-15 17:18:27 +00008682 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00008683
Richard Trieube234c32016-04-21 21:04:55 +00008684 if (PruneWarnings) {
8685 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8686 S.PDiag(DiagID)
8687 << E->getType() << T.getUnqualifiedType()
8688 << PrettySourceValue << PrettyTargetValue
8689 << E->getSourceRange() << SourceRange(CContext));
8690 } else {
8691 S.Diag(E->getExprLoc(), DiagID)
8692 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8693 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8694 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008695}
8696
John McCall18a2c2c2010-11-09 22:22:12 +00008697std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8698 if (!Range.Width) return "0";
8699
8700 llvm::APSInt ValueInRange = Value;
8701 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00008702 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00008703 return ValueInRange.toString(10);
8704}
8705
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008706bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008707 if (!isa<ImplicitCastExpr>(Ex))
8708 return false;
8709
8710 Expr *InnerE = Ex->IgnoreParenImpCasts();
8711 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8712 const Type *Source =
8713 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8714 if (Target->isDependentType())
8715 return false;
8716
8717 const BuiltinType *FloatCandidateBT =
8718 dyn_cast<BuiltinType>(ToBool ? Source : Target);
8719 const Type *BoolCandidateType = ToBool ? Target : Source;
8720
8721 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8722 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8723}
8724
8725void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8726 SourceLocation CC) {
8727 unsigned NumArgs = TheCall->getNumArgs();
8728 for (unsigned i = 0; i < NumArgs; ++i) {
8729 Expr *CurrA = TheCall->getArg(i);
8730 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8731 continue;
8732
8733 bool IsSwapped = ((i > 0) &&
8734 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8735 IsSwapped |= ((i < (NumArgs - 1)) &&
8736 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8737 if (IsSwapped) {
8738 // Warn on this floating-point to bool conversion.
8739 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8740 CurrA->getType(), CC,
8741 diag::warn_impcast_floating_point_to_bool);
8742 }
8743 }
8744}
8745
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008746void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00008747 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
8748 E->getExprLoc()))
8749 return;
8750
Richard Trieu09d6b802016-01-08 23:35:06 +00008751 // Don't warn on functions which have return type nullptr_t.
8752 if (isa<CallExpr>(E))
8753 return;
8754
Richard Trieu5b993502014-10-15 03:42:06 +00008755 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
8756 const Expr::NullPointerConstantKind NullKind =
8757 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
8758 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
8759 return;
8760
8761 // Return if target type is a safe conversion.
8762 if (T->isAnyPointerType() || T->isBlockPointerType() ||
8763 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8764 return;
8765
8766 SourceLocation Loc = E->getSourceRange().getBegin();
8767
Richard Trieu0a5e1662016-02-13 00:58:53 +00008768 // Venture through the macro stacks to get to the source of macro arguments.
8769 // The new location is a better location than the complete location that was
8770 // passed in.
8771 while (S.SourceMgr.isMacroArgExpansion(Loc))
8772 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8773
8774 while (S.SourceMgr.isMacroArgExpansion(CC))
8775 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8776
Richard Trieu5b993502014-10-15 03:42:06 +00008777 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00008778 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8779 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8780 Loc, S.SourceMgr, S.getLangOpts());
8781 if (MacroName == "NULL")
8782 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00008783 }
8784
8785 // Only warn if the null and context location are in the same macro expansion.
8786 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8787 return;
8788
8789 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8790 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8791 << FixItHint::CreateReplacement(Loc,
8792 S.getFixItZeroLiteralForType(T, Loc));
8793}
8794
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008795void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8796 ObjCArrayLiteral *ArrayLiteral);
8797void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8798 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00008799
8800/// Check a single element within a collection literal against the
8801/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008802void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8803 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008804 // Skip a bitcast to 'id' or qualified 'id'.
8805 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8806 if (ICE->getCastKind() == CK_BitCast &&
8807 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8808 Element = ICE->getSubExpr();
8809 }
8810
8811 QualType ElementType = Element->getType();
8812 ExprResult ElementResult(Element);
8813 if (ElementType->getAs<ObjCObjectPointerType>() &&
8814 S.CheckSingleAssignmentConstraints(TargetElementType,
8815 ElementResult,
8816 false, false)
8817 != Sema::Compatible) {
8818 S.Diag(Element->getLocStart(),
8819 diag::warn_objc_collection_literal_element)
8820 << ElementType << ElementKind << TargetElementType
8821 << Element->getSourceRange();
8822 }
8823
8824 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8825 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8826 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8827 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8828}
8829
8830/// Check an Objective-C array literal being converted to the given
8831/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008832void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8833 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008834 if (!S.NSArrayDecl)
8835 return;
8836
8837 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8838 if (!TargetObjCPtr)
8839 return;
8840
8841 if (TargetObjCPtr->isUnspecialized() ||
8842 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8843 != S.NSArrayDecl->getCanonicalDecl())
8844 return;
8845
8846 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8847 if (TypeArgs.size() != 1)
8848 return;
8849
8850 QualType TargetElementType = TypeArgs[0];
8851 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8852 checkObjCCollectionLiteralElement(S, TargetElementType,
8853 ArrayLiteral->getElement(I),
8854 0);
8855 }
8856}
8857
8858/// Check an Objective-C dictionary literal being converted to the given
8859/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008860void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8861 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008862 if (!S.NSDictionaryDecl)
8863 return;
8864
8865 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8866 if (!TargetObjCPtr)
8867 return;
8868
8869 if (TargetObjCPtr->isUnspecialized() ||
8870 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8871 != S.NSDictionaryDecl->getCanonicalDecl())
8872 return;
8873
8874 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8875 if (TypeArgs.size() != 2)
8876 return;
8877
8878 QualType TargetKeyType = TypeArgs[0];
8879 QualType TargetObjectType = TypeArgs[1];
8880 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8881 auto Element = DictionaryLiteral->getKeyValueElement(I);
8882 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8883 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8884 }
8885}
8886
Richard Trieufc404c72016-02-05 23:02:38 +00008887// Helper function to filter out cases for constant width constant conversion.
8888// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008889bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8890 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00008891 // If initializing from a constant, and the constant starts with '0',
8892 // then it is a binary, octal, or hexadecimal. Allow these constants
8893 // to fill all the bits, even if there is a sign change.
8894 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8895 const char FirstLiteralCharacter =
8896 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8897 if (FirstLiteralCharacter == '0')
8898 return false;
8899 }
8900
8901 // If the CC location points to a '{', and the type is char, then assume
8902 // assume it is an array initialization.
8903 if (CC.isValid() && T->isCharType()) {
8904 const char FirstContextCharacter =
8905 S.getSourceManager().getCharacterData(CC)[0];
8906 if (FirstContextCharacter == '{')
8907 return false;
8908 }
8909
8910 return true;
8911}
8912
John McCallcc7e5bf2010-05-06 08:58:33 +00008913void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00008914 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008915 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00008916
John McCallcc7e5bf2010-05-06 08:58:33 +00008917 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
8918 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
8919 if (Source == Target) return;
8920 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00008921
Chandler Carruthc22845a2011-07-26 05:40:03 +00008922 // If the conversion context location is invalid don't complain. We also
8923 // don't want to emit a warning if the issue occurs from the expansion of
8924 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
8925 // delay this check as long as possible. Once we detect we are in that
8926 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008927 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00008928 return;
8929
Richard Trieu021baa32011-09-23 20:10:00 +00008930 // Diagnose implicit casts to bool.
8931 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
8932 if (isa<StringLiteral>(E))
8933 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00008934 // and expressions, for instance, assert(0 && "error here"), are
8935 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00008936 return DiagnoseImpCast(S, E, T, CC,
8937 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00008938 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
8939 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
8940 // This covers the literal expressions that evaluate to Objective-C
8941 // objects.
8942 return DiagnoseImpCast(S, E, T, CC,
8943 diag::warn_impcast_objective_c_literal_to_bool);
8944 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008945 if (Source->isPointerType() || Source->canDecayToPointerType()) {
8946 // Warn on pointer to bool conversion that is always true.
8947 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
8948 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00008949 }
Richard Trieu021baa32011-09-23 20:10:00 +00008950 }
John McCall263a48b2010-01-04 23:31:57 +00008951
Douglas Gregor5054cb02015-07-07 03:58:22 +00008952 // Check implicit casts from Objective-C collection literals to specialized
8953 // collection types, e.g., NSArray<NSString *> *.
8954 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
8955 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
8956 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
8957 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
8958
John McCall263a48b2010-01-04 23:31:57 +00008959 // Strip vector types.
8960 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008961 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008962 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008963 return;
John McCallacf0ee52010-10-08 02:01:28 +00008964 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008965 }
Chris Lattneree7286f2011-06-14 04:51:15 +00008966
8967 // If the vector cast is cast between two vectors of the same size, it is
8968 // a bitcast, not a conversion.
8969 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
8970 return;
John McCall263a48b2010-01-04 23:31:57 +00008971
8972 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
8973 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
8974 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00008975 if (auto VecTy = dyn_cast<VectorType>(Target))
8976 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00008977
8978 // Strip complex types.
8979 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008980 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008981 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008982 return;
8983
John McCallacf0ee52010-10-08 02:01:28 +00008984 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008985 }
John McCall263a48b2010-01-04 23:31:57 +00008986
8987 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
8988 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
8989 }
8990
8991 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
8992 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
8993
8994 // If the source is floating point...
8995 if (SourceBT && SourceBT->isFloatingPoint()) {
8996 // ...and the target is floating point...
8997 if (TargetBT && TargetBT->isFloatingPoint()) {
8998 // ...then warn if we're dropping FP rank.
8999
9000 // Builtin FP kinds are ordered by increasing FP rank.
9001 if (SourceBT->getKind() > TargetBT->getKind()) {
9002 // Don't warn about float constants that are precisely
9003 // representable in the target type.
9004 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009005 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00009006 // Value might be a float, a float vector, or a float complex.
9007 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00009008 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9009 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00009010 return;
9011 }
9012
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009013 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009014 return;
9015
John McCallacf0ee52010-10-08 02:01:28 +00009016 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00009017 }
9018 // ... or possibly if we're increasing rank, too
9019 else if (TargetBT->getKind() > SourceBT->getKind()) {
9020 if (S.SourceMgr.isInSystemMacro(CC))
9021 return;
9022
9023 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00009024 }
9025 return;
9026 }
9027
Richard Trieube234c32016-04-21 21:04:55 +00009028 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00009029 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009030 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009031 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00009032
Richard Trieube234c32016-04-21 21:04:55 +00009033 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00009034 }
John McCall263a48b2010-01-04 23:31:57 +00009035
Richard Smith54894fd2015-12-30 01:06:52 +00009036 // Detect the case where a call result is converted from floating-point to
9037 // to bool, and the final argument to the call is converted from bool, to
9038 // discover this typo:
9039 //
9040 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9041 //
9042 // FIXME: This is an incredibly special case; is there some more general
9043 // way to detect this class of misplaced-parentheses bug?
9044 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009045 // Check last argument of function call to see if it is an
9046 // implicit cast from a type matching the type the result
9047 // is being cast to.
9048 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00009049 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009050 Expr *LastA = CEx->getArg(NumArgs - 1);
9051 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00009052 if (isa<ImplicitCastExpr>(LastA) &&
9053 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009054 // Warn on this floating-point to bool conversion
9055 DiagnoseImpCast(S, E, T, CC,
9056 diag::warn_impcast_floating_point_to_bool);
9057 }
9058 }
9059 }
John McCall263a48b2010-01-04 23:31:57 +00009060 return;
9061 }
9062
Richard Trieu5b993502014-10-15 03:42:06 +00009063 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00009064
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009065 S.DiscardMisalignedMemberAddress(Target, E);
9066
David Blaikie9366d2b2012-06-19 21:19:06 +00009067 if (!Source->isIntegerType() || !Target->isIntegerType())
9068 return;
9069
David Blaikie7555b6a2012-05-15 16:56:36 +00009070 // TODO: remove this early return once the false positives for constant->bool
9071 // in templates, macros, etc, are reduced or removed.
9072 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9073 return;
9074
John McCallcc7e5bf2010-05-06 08:58:33 +00009075 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00009076 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00009077
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009078 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00009079 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009080 // TODO: this should happen for bitfield stores, too.
9081 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00009082 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009083 if (S.SourceMgr.isInSystemMacro(CC))
9084 return;
9085
John McCall18a2c2c2010-11-09 22:22:12 +00009086 std::string PrettySourceValue = Value.toString(10);
9087 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009088
Ted Kremenek33ba9952011-10-22 02:37:33 +00009089 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9090 S.PDiag(diag::warn_impcast_integer_precision_constant)
9091 << PrettySourceValue << PrettyTargetValue
9092 << E->getType() << T << E->getSourceRange()
9093 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00009094 return;
9095 }
9096
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009097 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9098 if (S.SourceMgr.isInSystemMacro(CC))
9099 return;
9100
David Blaikie9455da02012-04-12 22:40:54 +00009101 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00009102 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9103 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00009104 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00009105 }
9106
Richard Trieudcb55572016-01-29 23:51:16 +00009107 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9108 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9109 // Warn when doing a signed to signed conversion, warn if the positive
9110 // source value is exactly the width of the target type, which will
9111 // cause a negative value to be stored.
9112
9113 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00009114 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9115 !S.SourceMgr.isInSystemMacro(CC)) {
9116 if (isSameWidthConstantConversion(S, E, T, CC)) {
9117 std::string PrettySourceValue = Value.toString(10);
9118 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00009119
Richard Trieufc404c72016-02-05 23:02:38 +00009120 S.DiagRuntimeBehavior(
9121 E->getExprLoc(), E,
9122 S.PDiag(diag::warn_impcast_integer_precision_constant)
9123 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9124 << E->getSourceRange() << clang::SourceRange(CC));
9125 return;
Richard Trieudcb55572016-01-29 23:51:16 +00009126 }
9127 }
Richard Trieufc404c72016-02-05 23:02:38 +00009128
Richard Trieudcb55572016-01-29 23:51:16 +00009129 // Fall through for non-constants to give a sign conversion warning.
9130 }
9131
John McCallcc7e5bf2010-05-06 08:58:33 +00009132 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9133 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9134 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009135 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009136 return;
9137
John McCallcc7e5bf2010-05-06 08:58:33 +00009138 unsigned DiagID = diag::warn_impcast_integer_sign;
9139
9140 // Traditionally, gcc has warned about this under -Wsign-compare.
9141 // We also want to warn about it in -Wconversion.
9142 // So if -Wconversion is off, use a completely identical diagnostic
9143 // in the sign-compare group.
9144 // The conditional-checking code will
9145 if (ICContext) {
9146 DiagID = diag::warn_impcast_integer_sign_conditional;
9147 *ICContext = true;
9148 }
9149
John McCallacf0ee52010-10-08 02:01:28 +00009150 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00009151 }
9152
Douglas Gregora78f1932011-02-22 02:45:07 +00009153 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00009154 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9155 // type, to give us better diagnostics.
9156 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009157 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00009158 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9159 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9160 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9161 SourceType = S.Context.getTypeDeclType(Enum);
9162 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9163 }
9164 }
9165
Douglas Gregora78f1932011-02-22 02:45:07 +00009166 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9167 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00009168 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9169 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009170 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009171 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009172 return;
9173
Douglas Gregor364f7db2011-03-12 00:14:31 +00009174 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00009175 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009176 }
John McCall263a48b2010-01-04 23:31:57 +00009177}
9178
David Blaikie18e9ac72012-05-15 21:57:38 +00009179void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9180 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009181
9182void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00009183 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009184 E = E->IgnoreParenImpCasts();
9185
9186 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00009187 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009188
John McCallacf0ee52010-10-08 02:01:28 +00009189 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009190 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009191 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00009192}
9193
David Blaikie18e9ac72012-05-15 21:57:38 +00009194void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9195 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00009196 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009197
9198 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00009199 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9200 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009201
9202 // If -Wconversion would have warned about either of the candidates
9203 // for a signedness conversion to the context type...
9204 if (!Suspicious) return;
9205
9206 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009207 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00009208 return;
9209
John McCallcc7e5bf2010-05-06 08:58:33 +00009210 // ...then check whether it would have warned about either of the
9211 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00009212 if (E->getType() == T) return;
9213
9214 Suspicious = false;
9215 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9216 E->getType(), CC, &Suspicious);
9217 if (!Suspicious)
9218 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00009219 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009220}
9221
Richard Trieu65724892014-11-15 06:37:39 +00009222/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9223/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009224void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00009225 if (S.getLangOpts().Bool)
9226 return;
9227 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9228}
9229
John McCallcc7e5bf2010-05-06 08:58:33 +00009230/// AnalyzeImplicitConversions - Find and report any interesting
9231/// implicit conversions in the given expression. There are a couple
9232/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009233void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00009234 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00009235 Expr *E = OrigE->IgnoreParenImpCasts();
9236
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00009237 if (E->isTypeDependent() || E->isValueDependent())
9238 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00009239
John McCallcc7e5bf2010-05-06 08:58:33 +00009240 // For conditional operators, we analyze the arguments as if they
9241 // were being fed directly into the output.
9242 if (isa<ConditionalOperator>(E)) {
9243 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00009244 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009245 return;
9246 }
9247
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009248 // Check implicit argument conversions for function calls.
9249 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9250 CheckImplicitArgumentConversions(S, Call, CC);
9251
John McCallcc7e5bf2010-05-06 08:58:33 +00009252 // Go ahead and check any implicit conversions we might have skipped.
9253 // The non-canonical typecheck is just an optimization;
9254 // CheckImplicitConversion will filter out dead implicit conversions.
9255 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009256 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009257
9258 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00009259
9260 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9261 // The bound subexpressions in a PseudoObjectExpr are not reachable
9262 // as transitive children.
9263 // FIXME: Use a more uniform representation for this.
9264 for (auto *SE : POE->semantics())
9265 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9266 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00009267 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00009268
John McCallcc7e5bf2010-05-06 08:58:33 +00009269 // Skip past explicit casts.
9270 if (isa<ExplicitCastExpr>(E)) {
9271 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00009272 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009273 }
9274
John McCalld2a53122010-11-09 23:24:47 +00009275 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9276 // Do a somewhat different check with comparison operators.
9277 if (BO->isComparisonOp())
9278 return AnalyzeComparison(S, BO);
9279
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009280 // And with simple assignments.
9281 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00009282 return AnalyzeAssignment(S, BO);
9283 }
John McCallcc7e5bf2010-05-06 08:58:33 +00009284
9285 // These break the otherwise-useful invariant below. Fortunately,
9286 // we don't really need to recurse into them, because any internal
9287 // expressions should have been analyzed already when they were
9288 // built into statements.
9289 if (isa<StmtExpr>(E)) return;
9290
9291 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00009292 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00009293
9294 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00009295 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00009296 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00009297 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00009298 for (Stmt *SubStmt : E->children()) {
9299 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00009300 if (!ChildExpr)
9301 continue;
9302
Richard Trieu955231d2014-01-25 01:10:35 +00009303 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00009304 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00009305 // Ignore checking string literals that are in logical and operators.
9306 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00009307 continue;
9308 AnalyzeImplicitConversions(S, ChildExpr, CC);
9309 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009310
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009311 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00009312 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9313 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009314 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00009315
9316 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9317 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009318 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009319 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009320
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009321 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9322 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00009323 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009324}
9325
9326} // end anonymous namespace
9327
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009328static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
9329 unsigned Start, unsigned End) {
9330 bool IllegalParams = false;
9331 for (unsigned I = Start; I <= End; ++I) {
9332 QualType Ty = TheCall->getArg(I)->getType();
9333 // Taking into account implicit conversions,
9334 // allow any integer within 32 bits range
9335 if (!Ty->isIntegerType() ||
9336 S.Context.getTypeSizeInChars(Ty).getQuantity() > 4) {
9337 S.Diag(TheCall->getArg(I)->getLocStart(),
9338 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9339 IllegalParams = true;
9340 }
9341 // Potentially emit standard warnings for implicit conversions if enabled
9342 // using -Wconversion.
9343 CheckImplicitConversion(S, TheCall->getArg(I), S.Context.UnsignedIntTy,
9344 TheCall->getArg(I)->getLocStart());
9345 }
9346 return IllegalParams;
9347}
9348
Richard Trieuc1888e02014-06-28 23:25:37 +00009349// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9350// Returns true when emitting a warning about taking the address of a reference.
9351static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00009352 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00009353 E = E->IgnoreParenImpCasts();
9354
9355 const FunctionDecl *FD = nullptr;
9356
9357 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9358 if (!DRE->getDecl()->getType()->isReferenceType())
9359 return false;
9360 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9361 if (!M->getMemberDecl()->getType()->isReferenceType())
9362 return false;
9363 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00009364 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00009365 return false;
9366 FD = Call->getDirectCallee();
9367 } else {
9368 return false;
9369 }
9370
9371 SemaRef.Diag(E->getExprLoc(), PD);
9372
9373 // If possible, point to location of function.
9374 if (FD) {
9375 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9376 }
9377
9378 return true;
9379}
9380
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009381// Returns true if the SourceLocation is expanded from any macro body.
9382// Returns false if the SourceLocation is invalid, is from not in a macro
9383// expansion, or is from expanded from a top-level macro argument.
9384static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9385 if (Loc.isInvalid())
9386 return false;
9387
9388 while (Loc.isMacroID()) {
9389 if (SM.isMacroBodyExpansion(Loc))
9390 return true;
9391 Loc = SM.getImmediateMacroCallerLoc(Loc);
9392 }
9393
9394 return false;
9395}
9396
Richard Trieu3bb8b562014-02-26 02:36:06 +00009397/// \brief Diagnose pointers that are always non-null.
9398/// \param E the expression containing the pointer
9399/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9400/// compared to a null pointer
9401/// \param IsEqual True when the comparison is equal to a null pointer
9402/// \param Range Extra SourceRange to highlight in the diagnostic
9403void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9404 Expr::NullPointerConstantKind NullKind,
9405 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00009406 if (!E)
9407 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009408
9409 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009410 if (E->getExprLoc().isMacroID()) {
9411 const SourceManager &SM = getSourceManager();
9412 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9413 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00009414 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009415 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009416 E = E->IgnoreImpCasts();
9417
9418 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9419
Richard Trieuf7432752014-06-06 21:39:26 +00009420 if (isa<CXXThisExpr>(E)) {
9421 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9422 : diag::warn_this_bool_conversion;
9423 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9424 return;
9425 }
9426
Richard Trieu3bb8b562014-02-26 02:36:06 +00009427 bool IsAddressOf = false;
9428
9429 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9430 if (UO->getOpcode() != UO_AddrOf)
9431 return;
9432 IsAddressOf = true;
9433 E = UO->getSubExpr();
9434 }
9435
Richard Trieuc1888e02014-06-28 23:25:37 +00009436 if (IsAddressOf) {
9437 unsigned DiagID = IsCompare
9438 ? diag::warn_address_of_reference_null_compare
9439 : diag::warn_address_of_reference_bool_conversion;
9440 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9441 << IsEqual;
9442 if (CheckForReference(*this, E, PD)) {
9443 return;
9444 }
9445 }
9446
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009447 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9448 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00009449 std::string Str;
9450 llvm::raw_string_ostream S(Str);
9451 E->printPretty(S, nullptr, getPrintingPolicy());
9452 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9453 : diag::warn_cast_nonnull_to_bool;
9454 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9455 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009456 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00009457 };
9458
9459 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9460 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9461 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009462 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9463 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009464 return;
9465 }
9466 }
9467 }
9468
Richard Trieu3bb8b562014-02-26 02:36:06 +00009469 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00009470 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009471 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9472 D = R->getDecl();
9473 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9474 D = M->getMemberDecl();
9475 }
9476
9477 // Weak Decls can be null.
9478 if (!D || D->isWeak())
9479 return;
George Burgess IV850269a2015-12-08 22:02:00 +00009480
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009481 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00009482 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9483 if (getCurFunction() &&
9484 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009485 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9486 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009487 return;
9488 }
9489
9490 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +00009491 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +00009492 assert(ParamIter != FD->param_end());
9493 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9494
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009495 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9496 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009497 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +00009498 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009499 }
George Burgess IV850269a2015-12-08 22:02:00 +00009500
9501 for (unsigned ArgNo : NonNull->args()) {
9502 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009503 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009504 return;
9505 }
George Burgess IV850269a2015-12-08 22:02:00 +00009506 }
9507 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009508 }
9509 }
George Burgess IV850269a2015-12-08 22:02:00 +00009510 }
9511
Richard Trieu3bb8b562014-02-26 02:36:06 +00009512 QualType T = D->getType();
9513 const bool IsArray = T->isArrayType();
9514 const bool IsFunction = T->isFunctionType();
9515
Richard Trieuc1888e02014-06-28 23:25:37 +00009516 // Address of function is used to silence the function warning.
9517 if (IsAddressOf && IsFunction) {
9518 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009519 }
9520
9521 // Found nothing.
9522 if (!IsAddressOf && !IsFunction && !IsArray)
9523 return;
9524
9525 // Pretty print the expression for the diagnostic.
9526 std::string Str;
9527 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00009528 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00009529
9530 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9531 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00009532 enum {
9533 AddressOf,
9534 FunctionPointer,
9535 ArrayPointer
9536 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009537 if (IsAddressOf)
9538 DiagType = AddressOf;
9539 else if (IsFunction)
9540 DiagType = FunctionPointer;
9541 else if (IsArray)
9542 DiagType = ArrayPointer;
9543 else
9544 llvm_unreachable("Could not determine diagnostic.");
9545 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9546 << Range << IsEqual;
9547
9548 if (!IsFunction)
9549 return;
9550
9551 // Suggest '&' to silence the function warning.
9552 Diag(E->getExprLoc(), diag::note_function_warning_silence)
9553 << FixItHint::CreateInsertion(E->getLocStart(), "&");
9554
9555 // Check to see if '()' fixit should be emitted.
9556 QualType ReturnType;
9557 UnresolvedSet<4> NonTemplateOverloads;
9558 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9559 if (ReturnType.isNull())
9560 return;
9561
9562 if (IsCompare) {
9563 // There are two cases here. If there is null constant, the only suggest
9564 // for a pointer return type. If the null is 0, then suggest if the return
9565 // type is a pointer or an integer type.
9566 if (!ReturnType->isPointerType()) {
9567 if (NullKind == Expr::NPCK_ZeroExpression ||
9568 NullKind == Expr::NPCK_ZeroLiteral) {
9569 if (!ReturnType->isIntegerType())
9570 return;
9571 } else {
9572 return;
9573 }
9574 }
9575 } else { // !IsCompare
9576 // For function to bool, only suggest if the function pointer has bool
9577 // return type.
9578 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9579 return;
9580 }
9581 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00009582 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00009583}
9584
John McCallcc7e5bf2010-05-06 08:58:33 +00009585/// Diagnoses "dangerous" implicit conversions within the given
9586/// expression (which is a full expression). Implements -Wconversion
9587/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009588///
9589/// \param CC the "context" location of the implicit conversion, i.e.
9590/// the most location of the syntactic entity requiring the implicit
9591/// conversion
9592void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009593 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00009594 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00009595 return;
9596
9597 // Don't diagnose for value- or type-dependent expressions.
9598 if (E->isTypeDependent() || E->isValueDependent())
9599 return;
9600
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009601 // Check for array bounds violations in cases where the check isn't triggered
9602 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9603 // ArraySubscriptExpr is on the RHS of a variable initialization.
9604 CheckArrayAccess(E);
9605
John McCallacf0ee52010-10-08 02:01:28 +00009606 // This is not the right CC for (e.g.) a variable initialization.
9607 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009608}
9609
Richard Trieu65724892014-11-15 06:37:39 +00009610/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9611/// Input argument E is a logical expression.
9612void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9613 ::CheckBoolLikeConversion(*this, E, CC);
9614}
9615
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009616/// Diagnose when expression is an integer constant expression and its evaluation
9617/// results in integer overflow
9618void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00009619 // Use a work list to deal with nested struct initializers.
9620 SmallVector<Expr *, 2> Exprs(1, E);
9621
9622 do {
9623 Expr *E = Exprs.pop_back_val();
9624
9625 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9626 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9627 continue;
9628 }
9629
9630 if (auto InitList = dyn_cast<InitListExpr>(E))
9631 Exprs.append(InitList->inits().begin(), InitList->inits().end());
9632 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009633}
9634
Richard Smithc406cb72013-01-17 01:17:56 +00009635namespace {
9636/// \brief Visitor for expressions which looks for unsequenced operations on the
9637/// same object.
9638class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009639 typedef EvaluatedExprVisitor<SequenceChecker> Base;
9640
Richard Smithc406cb72013-01-17 01:17:56 +00009641 /// \brief A tree of sequenced regions within an expression. Two regions are
9642 /// unsequenced if one is an ancestor or a descendent of the other. When we
9643 /// finish processing an expression with sequencing, such as a comma
9644 /// expression, we fold its tree nodes into its parent, since they are
9645 /// unsequenced with respect to nodes we will visit later.
9646 class SequenceTree {
9647 struct Value {
9648 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9649 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +00009650 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +00009651 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009652 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00009653
9654 public:
9655 /// \brief A region within an expression which may be sequenced with respect
9656 /// to some other region.
9657 class Seq {
9658 explicit Seq(unsigned N) : Index(N) {}
9659 unsigned Index;
9660 friend class SequenceTree;
9661 public:
9662 Seq() : Index(0) {}
9663 };
9664
9665 SequenceTree() { Values.push_back(Value(0)); }
9666 Seq root() const { return Seq(0); }
9667
9668 /// \brief Create a new sequence of operations, which is an unsequenced
9669 /// subset of \p Parent. This sequence of operations is sequenced with
9670 /// respect to other children of \p Parent.
9671 Seq allocate(Seq Parent) {
9672 Values.push_back(Value(Parent.Index));
9673 return Seq(Values.size() - 1);
9674 }
9675
9676 /// \brief Merge a sequence of operations into its parent.
9677 void merge(Seq S) {
9678 Values[S.Index].Merged = true;
9679 }
9680
9681 /// \brief Determine whether two operations are unsequenced. This operation
9682 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9683 /// should have been merged into its parent as appropriate.
9684 bool isUnsequenced(Seq Cur, Seq Old) {
9685 unsigned C = representative(Cur.Index);
9686 unsigned Target = representative(Old.Index);
9687 while (C >= Target) {
9688 if (C == Target)
9689 return true;
9690 C = Values[C].Parent;
9691 }
9692 return false;
9693 }
9694
9695 private:
9696 /// \brief Pick a representative for a sequence.
9697 unsigned representative(unsigned K) {
9698 if (Values[K].Merged)
9699 // Perform path compression as we go.
9700 return Values[K].Parent = representative(Values[K].Parent);
9701 return K;
9702 }
9703 };
9704
9705 /// An object for which we can track unsequenced uses.
9706 typedef NamedDecl *Object;
9707
9708 /// Different flavors of object usage which we track. We only track the
9709 /// least-sequenced usage of each kind.
9710 enum UsageKind {
9711 /// A read of an object. Multiple unsequenced reads are OK.
9712 UK_Use,
9713 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00009714 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00009715 UK_ModAsValue,
9716 /// A modification of an object which is not sequenced before the value
9717 /// computation of the expression, such as n++.
9718 UK_ModAsSideEffect,
9719
9720 UK_Count = UK_ModAsSideEffect + 1
9721 };
9722
9723 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00009724 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00009725 Expr *Use;
9726 SequenceTree::Seq Seq;
9727 };
9728
9729 struct UsageInfo {
9730 UsageInfo() : Diagnosed(false) {}
9731 Usage Uses[UK_Count];
9732 /// Have we issued a diagnostic for this variable already?
9733 bool Diagnosed;
9734 };
9735 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9736
9737 Sema &SemaRef;
9738 /// Sequenced regions within the expression.
9739 SequenceTree Tree;
9740 /// Declaration modifications and references which we have seen.
9741 UsageInfoMap UsageMap;
9742 /// The region we are currently within.
9743 SequenceTree::Seq Region;
9744 /// Filled in with declarations which were modified as a side-effect
9745 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009746 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00009747 /// Expressions to check later. We defer checking these to reduce
9748 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009749 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00009750
9751 /// RAII object wrapping the visitation of a sequenced subexpression of an
9752 /// expression. At the end of this process, the side-effects of the evaluation
9753 /// become sequenced with respect to the value computation of the result, so
9754 /// we downgrade any UK_ModAsSideEffect within the evaluation to
9755 /// UK_ModAsValue.
9756 struct SequencedSubexpression {
9757 SequencedSubexpression(SequenceChecker &Self)
9758 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9759 Self.ModAsSideEffect = &ModAsSideEffect;
9760 }
9761 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +00009762 for (auto &M : llvm::reverse(ModAsSideEffect)) {
9763 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +00009764 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +00009765 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9766 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +00009767 }
9768 Self.ModAsSideEffect = OldModAsSideEffect;
9769 }
9770
9771 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009772 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9773 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00009774 };
9775
Richard Smith40238f02013-06-20 22:21:56 +00009776 /// RAII object wrapping the visitation of a subexpression which we might
9777 /// choose to evaluate as a constant. If any subexpression is evaluated and
9778 /// found to be non-constant, this allows us to suppress the evaluation of
9779 /// the outer expression.
9780 class EvaluationTracker {
9781 public:
9782 EvaluationTracker(SequenceChecker &Self)
9783 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9784 Self.EvalTracker = this;
9785 }
9786 ~EvaluationTracker() {
9787 Self.EvalTracker = Prev;
9788 if (Prev)
9789 Prev->EvalOK &= EvalOK;
9790 }
9791
9792 bool evaluate(const Expr *E, bool &Result) {
9793 if (!EvalOK || E->isValueDependent())
9794 return false;
9795 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9796 return EvalOK;
9797 }
9798
9799 private:
9800 SequenceChecker &Self;
9801 EvaluationTracker *Prev;
9802 bool EvalOK;
9803 } *EvalTracker;
9804
Richard Smithc406cb72013-01-17 01:17:56 +00009805 /// \brief Find the object which is produced by the specified expression,
9806 /// if any.
9807 Object getObject(Expr *E, bool Mod) const {
9808 E = E->IgnoreParenCasts();
9809 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9810 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9811 return getObject(UO->getSubExpr(), Mod);
9812 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9813 if (BO->getOpcode() == BO_Comma)
9814 return getObject(BO->getRHS(), Mod);
9815 if (Mod && BO->isAssignmentOp())
9816 return getObject(BO->getLHS(), Mod);
9817 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9818 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9819 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9820 return ME->getMemberDecl();
9821 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9822 // FIXME: If this is a reference, map through to its value.
9823 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00009824 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00009825 }
9826
9827 /// \brief Note that an object was modified or used by an expression.
9828 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9829 Usage &U = UI.Uses[UK];
9830 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9831 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9832 ModAsSideEffect->push_back(std::make_pair(O, U));
9833 U.Use = Ref;
9834 U.Seq = Region;
9835 }
9836 }
9837 /// \brief Check whether a modification or use conflicts with a prior usage.
9838 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9839 bool IsModMod) {
9840 if (UI.Diagnosed)
9841 return;
9842
9843 const Usage &U = UI.Uses[OtherKind];
9844 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9845 return;
9846
9847 Expr *Mod = U.Use;
9848 Expr *ModOrUse = Ref;
9849 if (OtherKind == UK_Use)
9850 std::swap(Mod, ModOrUse);
9851
9852 SemaRef.Diag(Mod->getExprLoc(),
9853 IsModMod ? diag::warn_unsequenced_mod_mod
9854 : diag::warn_unsequenced_mod_use)
9855 << O << SourceRange(ModOrUse->getExprLoc());
9856 UI.Diagnosed = true;
9857 }
9858
9859 void notePreUse(Object O, Expr *Use) {
9860 UsageInfo &U = UsageMap[O];
9861 // Uses conflict with other modifications.
9862 checkUsage(O, U, Use, UK_ModAsValue, false);
9863 }
9864 void notePostUse(Object O, Expr *Use) {
9865 UsageInfo &U = UsageMap[O];
9866 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9867 addUsage(U, O, Use, UK_Use);
9868 }
9869
9870 void notePreMod(Object O, Expr *Mod) {
9871 UsageInfo &U = UsageMap[O];
9872 // Modifications conflict with other modifications and with uses.
9873 checkUsage(O, U, Mod, UK_ModAsValue, true);
9874 checkUsage(O, U, Mod, UK_Use, false);
9875 }
9876 void notePostMod(Object O, Expr *Use, UsageKind UK) {
9877 UsageInfo &U = UsageMap[O];
9878 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9879 addUsage(U, O, Use, UK);
9880 }
9881
9882public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009883 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00009884 : Base(S.Context), SemaRef(S), Region(Tree.root()),
9885 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009886 Visit(E);
9887 }
9888
9889 void VisitStmt(Stmt *S) {
9890 // Skip all statements which aren't expressions for now.
9891 }
9892
9893 void VisitExpr(Expr *E) {
9894 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00009895 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00009896 }
9897
9898 void VisitCastExpr(CastExpr *E) {
9899 Object O = Object();
9900 if (E->getCastKind() == CK_LValueToRValue)
9901 O = getObject(E->getSubExpr(), false);
9902
9903 if (O)
9904 notePreUse(O, E);
9905 VisitExpr(E);
9906 if (O)
9907 notePostUse(O, E);
9908 }
9909
9910 void VisitBinComma(BinaryOperator *BO) {
9911 // C++11 [expr.comma]p1:
9912 // Every value computation and side effect associated with the left
9913 // expression is sequenced before every value computation and side
9914 // effect associated with the right expression.
9915 SequenceTree::Seq LHS = Tree.allocate(Region);
9916 SequenceTree::Seq RHS = Tree.allocate(Region);
9917 SequenceTree::Seq OldRegion = Region;
9918
9919 {
9920 SequencedSubexpression SeqLHS(*this);
9921 Region = LHS;
9922 Visit(BO->getLHS());
9923 }
9924
9925 Region = RHS;
9926 Visit(BO->getRHS());
9927
9928 Region = OldRegion;
9929
9930 // Forget that LHS and RHS are sequenced. They are both unsequenced
9931 // with respect to other stuff.
9932 Tree.merge(LHS);
9933 Tree.merge(RHS);
9934 }
9935
9936 void VisitBinAssign(BinaryOperator *BO) {
9937 // The modification is sequenced after the value computation of the LHS
9938 // and RHS, so check it before inspecting the operands and update the
9939 // map afterwards.
9940 Object O = getObject(BO->getLHS(), true);
9941 if (!O)
9942 return VisitExpr(BO);
9943
9944 notePreMod(O, BO);
9945
9946 // C++11 [expr.ass]p7:
9947 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
9948 // only once.
9949 //
9950 // Therefore, for a compound assignment operator, O is considered used
9951 // everywhere except within the evaluation of E1 itself.
9952 if (isa<CompoundAssignOperator>(BO))
9953 notePreUse(O, BO);
9954
9955 Visit(BO->getLHS());
9956
9957 if (isa<CompoundAssignOperator>(BO))
9958 notePostUse(O, BO);
9959
9960 Visit(BO->getRHS());
9961
Richard Smith83e37bee2013-06-26 23:16:51 +00009962 // C++11 [expr.ass]p1:
9963 // the assignment is sequenced [...] before the value computation of the
9964 // assignment expression.
9965 // C11 6.5.16/3 has no such rule.
9966 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9967 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00009968 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009969
Richard Smithc406cb72013-01-17 01:17:56 +00009970 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
9971 VisitBinAssign(CAO);
9972 }
9973
9974 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9975 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9976 void VisitUnaryPreIncDec(UnaryOperator *UO) {
9977 Object O = getObject(UO->getSubExpr(), true);
9978 if (!O)
9979 return VisitExpr(UO);
9980
9981 notePreMod(O, UO);
9982 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00009983 // C++11 [expr.pre.incr]p1:
9984 // the expression ++x is equivalent to x+=1
9985 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9986 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00009987 }
9988
9989 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9990 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9991 void VisitUnaryPostIncDec(UnaryOperator *UO) {
9992 Object O = getObject(UO->getSubExpr(), true);
9993 if (!O)
9994 return VisitExpr(UO);
9995
9996 notePreMod(O, UO);
9997 Visit(UO->getSubExpr());
9998 notePostMod(O, UO, UK_ModAsSideEffect);
9999 }
10000
10001 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10002 void VisitBinLOr(BinaryOperator *BO) {
10003 // The side-effects of the LHS of an '&&' are sequenced before the
10004 // value computation of the RHS, and hence before the value computation
10005 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10006 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000010007 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010008 {
10009 SequencedSubexpression Sequenced(*this);
10010 Visit(BO->getLHS());
10011 }
10012
10013 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010014 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010015 if (!Result)
10016 Visit(BO->getRHS());
10017 } else {
10018 // Check for unsequenced operations in the RHS, treating it as an
10019 // entirely separate evaluation.
10020 //
10021 // FIXME: If there are operations in the RHS which are unsequenced
10022 // with respect to operations outside the RHS, and those operations
10023 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000010024 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010025 }
Richard Smithc406cb72013-01-17 01:17:56 +000010026 }
10027 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000010028 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010029 {
10030 SequencedSubexpression Sequenced(*this);
10031 Visit(BO->getLHS());
10032 }
10033
10034 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010035 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010036 if (Result)
10037 Visit(BO->getRHS());
10038 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000010039 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010040 }
Richard Smithc406cb72013-01-17 01:17:56 +000010041 }
10042
10043 // Only visit the condition, unless we can be sure which subexpression will
10044 // be chosen.
10045 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000010046 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000010047 {
10048 SequencedSubexpression Sequenced(*this);
10049 Visit(CO->getCond());
10050 }
Richard Smithc406cb72013-01-17 01:17:56 +000010051
10052 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010053 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000010054 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010055 else {
Richard Smithd33f5202013-01-17 23:18:09 +000010056 WorkList.push_back(CO->getTrueExpr());
10057 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010058 }
Richard Smithc406cb72013-01-17 01:17:56 +000010059 }
10060
Richard Smithe3dbfe02013-06-30 10:40:20 +000010061 void VisitCallExpr(CallExpr *CE) {
10062 // C++11 [intro.execution]p15:
10063 // When calling a function [...], every value computation and side effect
10064 // associated with any argument expression, or with the postfix expression
10065 // designating the called function, is sequenced before execution of every
10066 // expression or statement in the body of the function [and thus before
10067 // the value computation of its result].
10068 SequencedSubexpression Sequenced(*this);
10069 Base::VisitCallExpr(CE);
10070
10071 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10072 }
10073
Richard Smithc406cb72013-01-17 01:17:56 +000010074 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010075 // This is a call, so all subexpressions are sequenced before the result.
10076 SequencedSubexpression Sequenced(*this);
10077
Richard Smithc406cb72013-01-17 01:17:56 +000010078 if (!CCE->isListInitialization())
10079 return VisitExpr(CCE);
10080
10081 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010082 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010083 SequenceTree::Seq Parent = Region;
10084 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10085 E = CCE->arg_end();
10086 I != E; ++I) {
10087 Region = Tree.allocate(Parent);
10088 Elts.push_back(Region);
10089 Visit(*I);
10090 }
10091
10092 // Forget that the initializers are sequenced.
10093 Region = Parent;
10094 for (unsigned I = 0; I < Elts.size(); ++I)
10095 Tree.merge(Elts[I]);
10096 }
10097
10098 void VisitInitListExpr(InitListExpr *ILE) {
10099 if (!SemaRef.getLangOpts().CPlusPlus11)
10100 return VisitExpr(ILE);
10101
10102 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010103 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010104 SequenceTree::Seq Parent = Region;
10105 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10106 Expr *E = ILE->getInit(I);
10107 if (!E) continue;
10108 Region = Tree.allocate(Parent);
10109 Elts.push_back(Region);
10110 Visit(E);
10111 }
10112
10113 // Forget that the initializers are sequenced.
10114 Region = Parent;
10115 for (unsigned I = 0; I < Elts.size(); ++I)
10116 Tree.merge(Elts[I]);
10117 }
10118};
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010119} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +000010120
10121void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010122 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000010123 WorkList.push_back(E);
10124 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000010125 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000010126 SequenceChecker(*this, Item, WorkList);
10127 }
Richard Smithc406cb72013-01-17 01:17:56 +000010128}
10129
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010130void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10131 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010132 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000010133 if (!E->isInstantiationDependent())
10134 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010135 if (!IsConstexpr && !E->isValueDependent())
10136 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010137 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000010138}
10139
John McCall1f425642010-11-11 03:21:53 +000010140void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10141 FieldDecl *BitField,
10142 Expr *Init) {
10143 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10144}
10145
David Majnemer61a5bbf2015-04-07 22:08:51 +000010146static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10147 SourceLocation Loc) {
10148 if (!PType->isVariablyModifiedType())
10149 return;
10150 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10151 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10152 return;
10153 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000010154 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10155 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10156 return;
10157 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000010158 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10159 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10160 return;
10161 }
10162
10163 const ArrayType *AT = S.Context.getAsArrayType(PType);
10164 if (!AT)
10165 return;
10166
10167 if (AT->getSizeModifier() != ArrayType::Star) {
10168 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10169 return;
10170 }
10171
10172 S.Diag(Loc, diag::err_array_star_in_function_definition);
10173}
10174
Mike Stump0c2ec772010-01-21 03:59:47 +000010175/// CheckParmsForFunctionDef - Check that the parameters of the given
10176/// function are appropriate for the definition of a function. This
10177/// takes care of any checks that cannot be performed on the
10178/// declaration itself, e.g., that the types of each of the function
10179/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000010180bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000010181 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010182 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000010183 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010184 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10185 // function declarator that is part of a function definition of
10186 // that function shall not have incomplete type.
10187 //
10188 // This is also C++ [dcl.fct]p6.
10189 if (!Param->isInvalidDecl() &&
10190 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010191 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010192 Param->setInvalidDecl();
10193 HasInvalidParm = true;
10194 }
10195
10196 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10197 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000010198 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000010199 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000010200 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000010201 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000010202 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000010203
10204 // C99 6.7.5.3p12:
10205 // If the function declarator is not part of a definition of that
10206 // function, parameters may have incomplete type and may use the [*]
10207 // notation in their sequences of declarator specifiers to specify
10208 // variable length array types.
10209 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000010210 // FIXME: This diagnostic should point the '[*]' if source-location
10211 // information is added for it.
10212 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010213
10214 // MSVC destroys objects passed by value in the callee. Therefore a
10215 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010216 // object's destructor. However, we don't perform any direct access check
10217 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +000010218 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10219 .getCXXABI()
10220 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +000010221 if (!Param->isInvalidDecl()) {
10222 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10223 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10224 if (!ClassDecl->isInvalidDecl() &&
10225 !ClassDecl->hasIrrelevantDestructor() &&
10226 !ClassDecl->isDependentContext()) {
10227 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10228 MarkFunctionReferenced(Param->getLocation(), Destructor);
10229 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10230 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010231 }
10232 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010233 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010234
10235 // Parameters with the pass_object_size attribute only need to be marked
10236 // constant at function definitions. Because we lack information about
10237 // whether we're on a declaration or definition when we're instantiating the
10238 // attribute, we need to check for constness here.
10239 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10240 if (!Param->getType().isConstQualified())
10241 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10242 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000010243 }
10244
10245 return HasInvalidParm;
10246}
John McCall2b5c1b22010-08-12 21:44:57 +000010247
10248/// CheckCastAlign - Implements -Wcast-align, which warns when a
10249/// pointer cast increases the alignment requirements.
10250void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10251 // This is actually a lot of work to potentially be doing on every
10252 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010253 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000010254 return;
10255
10256 // Ignore dependent types.
10257 if (T->isDependentType() || Op->getType()->isDependentType())
10258 return;
10259
10260 // Require that the destination be a pointer type.
10261 const PointerType *DestPtr = T->getAs<PointerType>();
10262 if (!DestPtr) return;
10263
10264 // If the destination has alignment 1, we're done.
10265 QualType DestPointee = DestPtr->getPointeeType();
10266 if (DestPointee->isIncompleteType()) return;
10267 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10268 if (DestAlign.isOne()) return;
10269
10270 // Require that the source be a pointer type.
10271 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10272 if (!SrcPtr) return;
10273 QualType SrcPointee = SrcPtr->getPointeeType();
10274
10275 // Whitelist casts from cv void*. We already implicitly
10276 // whitelisted casts to cv void*, since they have alignment 1.
10277 // Also whitelist casts involving incomplete types, which implicitly
10278 // includes 'void'.
10279 if (SrcPointee->isIncompleteType()) return;
10280
10281 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
10282 if (SrcAlign >= DestAlign) return;
10283
10284 Diag(TRange.getBegin(), diag::warn_cast_align)
10285 << Op->getType() << T
10286 << static_cast<unsigned>(SrcAlign.getQuantity())
10287 << static_cast<unsigned>(DestAlign.getQuantity())
10288 << TRange << Op->getSourceRange();
10289}
10290
Chandler Carruth28389f02011-08-05 09:10:50 +000010291/// \brief Check whether this array fits the idiom of a size-one tail padded
10292/// array member of a struct.
10293///
10294/// We avoid emitting out-of-bounds access warnings for such arrays as they are
10295/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000010296static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000010297 const NamedDecl *ND) {
10298 if (Size != 1 || !ND) return false;
10299
10300 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10301 if (!FD) return false;
10302
10303 // Don't consider sizes resulting from macro expansions or template argument
10304 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000010305
10306 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010307 while (TInfo) {
10308 TypeLoc TL = TInfo->getTypeLoc();
10309 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000010310 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10311 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010312 TInfo = TDL->getTypeSourceInfo();
10313 continue;
10314 }
David Blaikie6adc78e2013-02-18 22:06:02 +000010315 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10316 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000010317 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10318 return false;
10319 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010320 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000010321 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010322
10323 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000010324 if (!RD) return false;
10325 if (RD->isUnion()) return false;
10326 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10327 if (!CRD->isStandardLayout()) return false;
10328 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010329
Benjamin Kramer8c543672011-08-06 03:04:42 +000010330 // See if this is the last field decl in the record.
10331 const Decl *D = FD;
10332 while ((D = D->getNextDeclInContext()))
10333 if (isa<FieldDecl>(D))
10334 return false;
10335 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000010336}
10337
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010338void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010339 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000010340 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010341 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010342 if (IndexExpr->isValueDependent())
10343 return;
10344
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010345 const Type *EffectiveType =
10346 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010347 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010348 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010349 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010350 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000010351 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000010352
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010353 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000010354 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000010355 return;
Richard Smith13f67182011-12-16 19:31:14 +000010356 if (IndexNegated)
10357 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000010358
Craig Topperc3ec1492014-05-26 06:22:03 +000010359 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000010360 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10361 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +000010362 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +000010363 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +000010364
Ted Kremeneke4b316c2011-02-23 23:06:04 +000010365 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010366 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000010367 if (!size.isStrictlyPositive())
10368 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010369
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010370 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000010371 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010372 // Make sure we're comparing apples to apples when comparing index to size
10373 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10374 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000010375 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000010376 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010377 if (ptrarith_typesize != array_typesize) {
10378 // There's a cast to a different size type involved
10379 uint64_t ratio = array_typesize / ptrarith_typesize;
10380 // TODO: Be smarter about handling cases where array_typesize is not a
10381 // multiple of ptrarith_typesize
10382 if (ptrarith_typesize * ratio == array_typesize)
10383 size *= llvm::APInt(size.getBitWidth(), ratio);
10384 }
10385 }
10386
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010387 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010388 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010389 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010390 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010391
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010392 // For array subscripting the index must be less than size, but for pointer
10393 // arithmetic also allow the index (offset) to be equal to size since
10394 // computing the next address after the end of the array is legal and
10395 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010396 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000010397 return;
10398
10399 // Also don't warn for arrays of size 1 which are members of some
10400 // structure. These are often used to approximate flexible arrays in C89
10401 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010402 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000010403 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010404
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010405 // Suppress the warning if the subscript expression (as identified by the
10406 // ']' location) and the index expression are both from macro expansions
10407 // within a system header.
10408 if (ASE) {
10409 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10410 ASE->getRBracketLoc());
10411 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10412 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10413 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000010414 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010415 return;
10416 }
10417 }
10418
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010419 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010420 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010421 DiagID = diag::warn_array_index_exceeds_bounds;
10422
10423 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10424 PDiag(DiagID) << index.toString(10, true)
10425 << size.toString(10, true)
10426 << (unsigned)size.getLimitedValue(~0U)
10427 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010428 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010429 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010430 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010431 DiagID = diag::warn_ptr_arith_precedes_bounds;
10432 if (index.isNegative()) index = -index;
10433 }
10434
10435 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10436 PDiag(DiagID) << index.toString(10, true)
10437 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000010438 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000010439
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000010440 if (!ND) {
10441 // Try harder to find a NamedDecl to point at in the note.
10442 while (const ArraySubscriptExpr *ASE =
10443 dyn_cast<ArraySubscriptExpr>(BaseExpr))
10444 BaseExpr = ASE->getBase()->IgnoreParenCasts();
10445 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10446 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10447 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10448 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10449 }
10450
Chandler Carruth1af88f12011-02-17 21:10:52 +000010451 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010452 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10453 PDiag(diag::note_array_index_out_of_bounds)
10454 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000010455}
10456
Ted Kremenekdf26df72011-03-01 18:41:00 +000010457void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010458 int AllowOnePastEnd = 0;
10459 while (expr) {
10460 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000010461 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010462 case Stmt::ArraySubscriptExprClass: {
10463 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010464 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010465 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +000010466 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010467 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010468 case Stmt::OMPArraySectionExprClass: {
10469 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10470 if (ASE->getLowerBound())
10471 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10472 /*ASE=*/nullptr, AllowOnePastEnd > 0);
10473 return;
10474 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010475 case Stmt::UnaryOperatorClass: {
10476 // Only unwrap the * and & unary operators
10477 const UnaryOperator *UO = cast<UnaryOperator>(expr);
10478 expr = UO->getSubExpr();
10479 switch (UO->getOpcode()) {
10480 case UO_AddrOf:
10481 AllowOnePastEnd++;
10482 break;
10483 case UO_Deref:
10484 AllowOnePastEnd--;
10485 break;
10486 default:
10487 return;
10488 }
10489 break;
10490 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010491 case Stmt::ConditionalOperatorClass: {
10492 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10493 if (const Expr *lhs = cond->getLHS())
10494 CheckArrayAccess(lhs);
10495 if (const Expr *rhs = cond->getRHS())
10496 CheckArrayAccess(rhs);
10497 return;
10498 }
10499 default:
10500 return;
10501 }
Peter Collingbourne91147592011-04-15 00:35:48 +000010502 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010503}
John McCall31168b02011-06-15 23:02:42 +000010504
10505//===--- CHECK: Objective-C retain cycles ----------------------------------//
10506
10507namespace {
10508 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +000010509 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +000010510 VarDecl *Variable;
10511 SourceRange Range;
10512 SourceLocation Loc;
10513 bool Indirect;
10514
10515 void setLocsFrom(Expr *e) {
10516 Loc = e->getExprLoc();
10517 Range = e->getSourceRange();
10518 }
10519 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010520} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010521
10522/// Consider whether capturing the given variable can possibly lead to
10523/// a retain cycle.
10524static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010525 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000010526 // lifetime. In MRR, it's captured strongly if the variable is
10527 // __block and has an appropriate type.
10528 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10529 return false;
10530
10531 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010532 if (ref)
10533 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000010534 return true;
10535}
10536
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010537static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000010538 while (true) {
10539 e = e->IgnoreParens();
10540 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10541 switch (cast->getCastKind()) {
10542 case CK_BitCast:
10543 case CK_LValueBitCast:
10544 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000010545 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000010546 e = cast->getSubExpr();
10547 continue;
10548
John McCall31168b02011-06-15 23:02:42 +000010549 default:
10550 return false;
10551 }
10552 }
10553
10554 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10555 ObjCIvarDecl *ivar = ref->getDecl();
10556 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10557 return false;
10558
10559 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010560 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000010561 return false;
10562
10563 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10564 owner.Indirect = true;
10565 return true;
10566 }
10567
10568 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10569 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10570 if (!var) return false;
10571 return considerVariable(var, ref, owner);
10572 }
10573
John McCall31168b02011-06-15 23:02:42 +000010574 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10575 if (member->isArrow()) return false;
10576
10577 // Don't count this as an indirect ownership.
10578 e = member->getBase();
10579 continue;
10580 }
10581
John McCallfe96e0b2011-11-06 09:01:30 +000010582 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10583 // Only pay attention to pseudo-objects on property references.
10584 ObjCPropertyRefExpr *pre
10585 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10586 ->IgnoreParens());
10587 if (!pre) return false;
10588 if (pre->isImplicitProperty()) return false;
10589 ObjCPropertyDecl *property = pre->getExplicitProperty();
10590 if (!property->isRetaining() &&
10591 !(property->getPropertyIvarDecl() &&
10592 property->getPropertyIvarDecl()->getType()
10593 .getObjCLifetime() == Qualifiers::OCL_Strong))
10594 return false;
10595
10596 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010597 if (pre->isSuperReceiver()) {
10598 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10599 if (!owner.Variable)
10600 return false;
10601 owner.Loc = pre->getLocation();
10602 owner.Range = pre->getSourceRange();
10603 return true;
10604 }
John McCallfe96e0b2011-11-06 09:01:30 +000010605 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10606 ->getSourceExpr());
10607 continue;
10608 }
10609
John McCall31168b02011-06-15 23:02:42 +000010610 // Array ivars?
10611
10612 return false;
10613 }
10614}
10615
10616namespace {
10617 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10618 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10619 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010620 Context(Context), Variable(variable), Capturer(nullptr),
10621 VarWillBeReased(false) {}
10622 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000010623 VarDecl *Variable;
10624 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010625 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +000010626
10627 void VisitDeclRefExpr(DeclRefExpr *ref) {
10628 if (ref->getDecl() == Variable && !Capturer)
10629 Capturer = ref;
10630 }
10631
John McCall31168b02011-06-15 23:02:42 +000010632 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10633 if (Capturer) return;
10634 Visit(ref->getBase());
10635 if (Capturer && ref->isFreeIvar())
10636 Capturer = ref;
10637 }
10638
10639 void VisitBlockExpr(BlockExpr *block) {
10640 // Look inside nested blocks
10641 if (block->getBlockDecl()->capturesVariable(Variable))
10642 Visit(block->getBlockDecl()->getBody());
10643 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000010644
10645 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
10646 if (Capturer) return;
10647 if (OVE->getSourceExpr())
10648 Visit(OVE->getSourceExpr());
10649 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010650 void VisitBinaryOperator(BinaryOperator *BinOp) {
10651 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
10652 return;
10653 Expr *LHS = BinOp->getLHS();
10654 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
10655 if (DRE->getDecl() != Variable)
10656 return;
10657 if (Expr *RHS = BinOp->getRHS()) {
10658 RHS = RHS->IgnoreParenCasts();
10659 llvm::APSInt Value;
10660 VarWillBeReased =
10661 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
10662 }
10663 }
10664 }
John McCall31168b02011-06-15 23:02:42 +000010665 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010666} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010667
10668/// Check whether the given argument is a block which captures a
10669/// variable.
10670static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
10671 assert(owner.Variable && owner.Loc.isValid());
10672
10673 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000010674
10675 // Look through [^{...} copy] and Block_copy(^{...}).
10676 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
10677 Selector Cmd = ME->getSelector();
10678 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
10679 e = ME->getInstanceReceiver();
10680 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000010681 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000010682 e = e->IgnoreParenCasts();
10683 }
10684 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
10685 if (CE->getNumArgs() == 1) {
10686 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000010687 if (Fn) {
10688 const IdentifierInfo *FnI = Fn->getIdentifier();
10689 if (FnI && FnI->isStr("_Block_copy")) {
10690 e = CE->getArg(0)->IgnoreParenCasts();
10691 }
10692 }
Jordan Rose67e887c2012-09-17 17:54:30 +000010693 }
10694 }
10695
John McCall31168b02011-06-15 23:02:42 +000010696 BlockExpr *block = dyn_cast<BlockExpr>(e);
10697 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000010698 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000010699
10700 FindCaptureVisitor visitor(S.Context, owner.Variable);
10701 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010702 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000010703}
10704
10705static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10706 RetainCycleOwner &owner) {
10707 assert(capturer);
10708 assert(owner.Variable && owner.Loc.isValid());
10709
10710 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10711 << owner.Variable << capturer->getSourceRange();
10712 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10713 << owner.Indirect << owner.Range;
10714}
10715
10716/// Check for a keyword selector that starts with the word 'add' or
10717/// 'set'.
10718static bool isSetterLikeSelector(Selector sel) {
10719 if (sel.isUnarySelector()) return false;
10720
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010721 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000010722 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010723 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000010724 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010725 else if (str.startswith("add")) {
10726 // Specially whitelist 'addOperationWithBlock:'.
10727 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
10728 return false;
10729 str = str.substr(3);
10730 }
John McCall31168b02011-06-15 23:02:42 +000010731 else
10732 return false;
10733
10734 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000010735 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000010736}
10737
Benjamin Kramer3a743452015-03-09 15:03:32 +000010738static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
10739 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010740 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
10741 Message->getReceiverInterface(),
10742 NSAPI::ClassId_NSMutableArray);
10743 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010744 return None;
10745 }
10746
10747 Selector Sel = Message->getSelector();
10748
10749 Optional<NSAPI::NSArrayMethodKind> MKOpt =
10750 S.NSAPIObj->getNSArrayMethodKind(Sel);
10751 if (!MKOpt) {
10752 return None;
10753 }
10754
10755 NSAPI::NSArrayMethodKind MK = *MKOpt;
10756
10757 switch (MK) {
10758 case NSAPI::NSMutableArr_addObject:
10759 case NSAPI::NSMutableArr_insertObjectAtIndex:
10760 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
10761 return 0;
10762 case NSAPI::NSMutableArr_replaceObjectAtIndex:
10763 return 1;
10764
10765 default:
10766 return None;
10767 }
10768
10769 return None;
10770}
10771
10772static
10773Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10774 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010775 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10776 Message->getReceiverInterface(),
10777 NSAPI::ClassId_NSMutableDictionary);
10778 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010779 return None;
10780 }
10781
10782 Selector Sel = Message->getSelector();
10783
10784 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10785 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10786 if (!MKOpt) {
10787 return None;
10788 }
10789
10790 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10791
10792 switch (MK) {
10793 case NSAPI::NSMutableDict_setObjectForKey:
10794 case NSAPI::NSMutableDict_setValueForKey:
10795 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10796 return 0;
10797
10798 default:
10799 return None;
10800 }
10801
10802 return None;
10803}
10804
10805static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010806 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10807 Message->getReceiverInterface(),
10808 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000010809
Alex Denisov5dfac812015-08-06 04:51:14 +000010810 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10811 Message->getReceiverInterface(),
10812 NSAPI::ClassId_NSMutableOrderedSet);
10813 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010814 return None;
10815 }
10816
10817 Selector Sel = Message->getSelector();
10818
10819 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10820 if (!MKOpt) {
10821 return None;
10822 }
10823
10824 NSAPI::NSSetMethodKind MK = *MKOpt;
10825
10826 switch (MK) {
10827 case NSAPI::NSMutableSet_addObject:
10828 case NSAPI::NSOrderedSet_setObjectAtIndex:
10829 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10830 case NSAPI::NSOrderedSet_insertObjectAtIndex:
10831 return 0;
10832 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10833 return 1;
10834 }
10835
10836 return None;
10837}
10838
10839void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10840 if (!Message->isInstanceMessage()) {
10841 return;
10842 }
10843
10844 Optional<int> ArgOpt;
10845
10846 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10847 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10848 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10849 return;
10850 }
10851
10852 int ArgIndex = *ArgOpt;
10853
Alex Denisove1d882c2015-03-04 17:55:52 +000010854 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10855 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10856 Arg = OE->getSourceExpr()->IgnoreImpCasts();
10857 }
10858
Alex Denisov5dfac812015-08-06 04:51:14 +000010859 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010860 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010861 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010862 Diag(Message->getSourceRange().getBegin(),
10863 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000010864 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000010865 }
10866 }
Alex Denisov5dfac812015-08-06 04:51:14 +000010867 } else {
10868 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10869
10870 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10871 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10872 }
10873
10874 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10875 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10876 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10877 ValueDecl *Decl = ReceiverRE->getDecl();
10878 Diag(Message->getSourceRange().getBegin(),
10879 diag::warn_objc_circular_container)
10880 << Decl->getName() << Decl->getName();
10881 if (!ArgRE->isObjCSelfExpr()) {
10882 Diag(Decl->getLocation(),
10883 diag::note_objc_circular_container_declared_here)
10884 << Decl->getName();
10885 }
10886 }
10887 }
10888 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
10889 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
10890 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
10891 ObjCIvarDecl *Decl = IvarRE->getDecl();
10892 Diag(Message->getSourceRange().getBegin(),
10893 diag::warn_objc_circular_container)
10894 << Decl->getName() << Decl->getName();
10895 Diag(Decl->getLocation(),
10896 diag::note_objc_circular_container_declared_here)
10897 << Decl->getName();
10898 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010899 }
10900 }
10901 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010902}
10903
John McCall31168b02011-06-15 23:02:42 +000010904/// Check a message send to see if it's likely to cause a retain cycle.
10905void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
10906 // Only check instance methods whose selector looks like a setter.
10907 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
10908 return;
10909
10910 // Try to find a variable that the receiver is strongly owned by.
10911 RetainCycleOwner owner;
10912 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010913 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000010914 return;
10915 } else {
10916 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
10917 owner.Variable = getCurMethodDecl()->getSelfDecl();
10918 owner.Loc = msg->getSuperLoc();
10919 owner.Range = msg->getSuperLoc();
10920 }
10921
10922 // Check whether the receiver is captured by any of the arguments.
10923 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
10924 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
10925 return diagnoseRetainCycle(*this, capturer, owner);
10926}
10927
10928/// Check a property assign to see if it's likely to cause a retain cycle.
10929void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
10930 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010931 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000010932 return;
10933
10934 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
10935 diagnoseRetainCycle(*this, capturer, owner);
10936}
10937
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010938void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
10939 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000010940 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010941 return;
10942
10943 // Because we don't have an expression for the variable, we have to set the
10944 // location explicitly here.
10945 Owner.Loc = Var->getLocation();
10946 Owner.Range = Var->getSourceRange();
10947
10948 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
10949 diagnoseRetainCycle(*this, Capturer, Owner);
10950}
10951
Ted Kremenek9304da92012-12-21 08:04:28 +000010952static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
10953 Expr *RHS, bool isProperty) {
10954 // Check if RHS is an Objective-C object literal, which also can get
10955 // immediately zapped in a weak reference. Note that we explicitly
10956 // allow ObjCStringLiterals, since those are designed to never really die.
10957 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010958
Ted Kremenek64873352012-12-21 22:46:35 +000010959 // This enum needs to match with the 'select' in
10960 // warn_objc_arc_literal_assign (off-by-1).
10961 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
10962 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
10963 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010964
10965 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000010966 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000010967 << (isProperty ? 0 : 1)
10968 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010969
10970 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000010971}
10972
Ted Kremenekc1f014a2012-12-21 19:45:30 +000010973static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
10974 Qualifiers::ObjCLifetime LT,
10975 Expr *RHS, bool isProperty) {
10976 // Strip off any implicit cast added to get to the one ARC-specific.
10977 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
10978 if (cast->getCastKind() == CK_ARCConsumeObject) {
10979 S.Diag(Loc, diag::warn_arc_retained_assign)
10980 << (LT == Qualifiers::OCL_ExplicitNone)
10981 << (isProperty ? 0 : 1)
10982 << RHS->getSourceRange();
10983 return true;
10984 }
10985 RHS = cast->getSubExpr();
10986 }
10987
10988 if (LT == Qualifiers::OCL_Weak &&
10989 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
10990 return true;
10991
10992 return false;
10993}
10994
Ted Kremenekb36234d2012-12-21 08:04:20 +000010995bool Sema::checkUnsafeAssigns(SourceLocation Loc,
10996 QualType LHS, Expr *RHS) {
10997 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
10998
10999 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11000 return false;
11001
11002 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11003 return true;
11004
11005 return false;
11006}
11007
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011008void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11009 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011010 QualType LHSType;
11011 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011012 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011013 ObjCPropertyRefExpr *PRE
11014 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11015 if (PRE && !PRE->isImplicitProperty()) {
11016 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11017 if (PD)
11018 LHSType = PD->getType();
11019 }
11020
11021 if (LHSType.isNull())
11022 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000011023
11024 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11025
11026 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011027 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000011028 getCurFunction()->markSafeWeakUse(LHS);
11029 }
11030
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011031 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11032 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000011033
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011034 // FIXME. Check for other life times.
11035 if (LT != Qualifiers::OCL_None)
11036 return;
11037
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011038 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011039 if (PRE->isImplicitProperty())
11040 return;
11041 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11042 if (!PD)
11043 return;
11044
Bill Wendling44426052012-12-20 19:22:21 +000011045 unsigned Attributes = PD->getPropertyAttributes();
11046 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011047 // when 'assign' attribute was not explicitly specified
11048 // by user, ignore it and rely on property type itself
11049 // for lifetime info.
11050 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11051 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11052 LHSType->isObjCRetainableType())
11053 return;
11054
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011055 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000011056 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011057 Diag(Loc, diag::warn_arc_retained_property_assign)
11058 << RHS->getSourceRange();
11059 return;
11060 }
11061 RHS = cast->getSubExpr();
11062 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011063 }
Bill Wendling44426052012-12-20 19:22:21 +000011064 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000011065 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11066 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000011067 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011068 }
11069}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011070
11071//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11072
11073namespace {
11074bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11075 SourceLocation StmtLoc,
11076 const NullStmt *Body) {
11077 // Do not warn if the body is a macro that expands to nothing, e.g:
11078 //
11079 // #define CALL(x)
11080 // if (condition)
11081 // CALL(0);
11082 //
11083 if (Body->hasLeadingEmptyMacro())
11084 return false;
11085
11086 // Get line numbers of statement and body.
11087 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000011088 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011089 &StmtLineInvalid);
11090 if (StmtLineInvalid)
11091 return false;
11092
11093 bool BodyLineInvalid;
11094 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11095 &BodyLineInvalid);
11096 if (BodyLineInvalid)
11097 return false;
11098
11099 // Warn if null statement and body are on the same line.
11100 if (StmtLine != BodyLine)
11101 return false;
11102
11103 return true;
11104}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011105} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011106
11107void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11108 const Stmt *Body,
11109 unsigned DiagID) {
11110 // Since this is a syntactic check, don't emit diagnostic for template
11111 // instantiations, this just adds noise.
11112 if (CurrentInstantiationScope)
11113 return;
11114
11115 // The body should be a null statement.
11116 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11117 if (!NBody)
11118 return;
11119
11120 // Do the usual checks.
11121 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11122 return;
11123
11124 Diag(NBody->getSemiLoc(), DiagID);
11125 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11126}
11127
11128void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11129 const Stmt *PossibleBody) {
11130 assert(!CurrentInstantiationScope); // Ensured by caller
11131
11132 SourceLocation StmtLoc;
11133 const Stmt *Body;
11134 unsigned DiagID;
11135 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11136 StmtLoc = FS->getRParenLoc();
11137 Body = FS->getBody();
11138 DiagID = diag::warn_empty_for_body;
11139 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11140 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11141 Body = WS->getBody();
11142 DiagID = diag::warn_empty_while_body;
11143 } else
11144 return; // Neither `for' nor `while'.
11145
11146 // The body should be a null statement.
11147 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11148 if (!NBody)
11149 return;
11150
11151 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011152 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011153 return;
11154
11155 // Do the usual checks.
11156 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11157 return;
11158
11159 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11160 // noise level low, emit diagnostics only if for/while is followed by a
11161 // CompoundStmt, e.g.:
11162 // for (int i = 0; i < n; i++);
11163 // {
11164 // a(i);
11165 // }
11166 // or if for/while is followed by a statement with more indentation
11167 // than for/while itself:
11168 // for (int i = 0; i < n; i++);
11169 // a(i);
11170 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11171 if (!ProbableTypo) {
11172 bool BodyColInvalid;
11173 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11174 PossibleBody->getLocStart(),
11175 &BodyColInvalid);
11176 if (BodyColInvalid)
11177 return;
11178
11179 bool StmtColInvalid;
11180 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11181 S->getLocStart(),
11182 &StmtColInvalid);
11183 if (StmtColInvalid)
11184 return;
11185
11186 if (BodyCol > StmtCol)
11187 ProbableTypo = true;
11188 }
11189
11190 if (ProbableTypo) {
11191 Diag(NBody->getSemiLoc(), DiagID);
11192 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11193 }
11194}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011195
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011196//===--- CHECK: Warn on self move with std::move. -------------------------===//
11197
11198/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11199void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11200 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011201 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11202 return;
11203
11204 if (!ActiveTemplateInstantiations.empty())
11205 return;
11206
11207 // Strip parens and casts away.
11208 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11209 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11210
11211 // Check for a call expression
11212 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11213 if (!CE || CE->getNumArgs() != 1)
11214 return;
11215
11216 // Check for a call to std::move
11217 const FunctionDecl *FD = CE->getDirectCallee();
11218 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11219 !FD->getIdentifier()->isStr("move"))
11220 return;
11221
11222 // Get argument from std::move
11223 RHSExpr = CE->getArg(0);
11224
11225 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11226 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11227
11228 // Two DeclRefExpr's, check that the decls are the same.
11229 if (LHSDeclRef && RHSDeclRef) {
11230 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11231 return;
11232 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11233 RHSDeclRef->getDecl()->getCanonicalDecl())
11234 return;
11235
11236 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11237 << LHSExpr->getSourceRange()
11238 << RHSExpr->getSourceRange();
11239 return;
11240 }
11241
11242 // Member variables require a different approach to check for self moves.
11243 // MemberExpr's are the same if every nested MemberExpr refers to the same
11244 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11245 // the base Expr's are CXXThisExpr's.
11246 const Expr *LHSBase = LHSExpr;
11247 const Expr *RHSBase = RHSExpr;
11248 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11249 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11250 if (!LHSME || !RHSME)
11251 return;
11252
11253 while (LHSME && RHSME) {
11254 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11255 RHSME->getMemberDecl()->getCanonicalDecl())
11256 return;
11257
11258 LHSBase = LHSME->getBase();
11259 RHSBase = RHSME->getBase();
11260 LHSME = dyn_cast<MemberExpr>(LHSBase);
11261 RHSME = dyn_cast<MemberExpr>(RHSBase);
11262 }
11263
11264 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11265 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11266 if (LHSDeclRef && RHSDeclRef) {
11267 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11268 return;
11269 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11270 RHSDeclRef->getDecl()->getCanonicalDecl())
11271 return;
11272
11273 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11274 << LHSExpr->getSourceRange()
11275 << RHSExpr->getSourceRange();
11276 return;
11277 }
11278
11279 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11280 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11281 << LHSExpr->getSourceRange()
11282 << RHSExpr->getSourceRange();
11283}
11284
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011285//===--- Layout compatibility ----------------------------------------------//
11286
11287namespace {
11288
11289bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11290
11291/// \brief Check if two enumeration types are layout-compatible.
11292bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11293 // C++11 [dcl.enum] p8:
11294 // Two enumeration types are layout-compatible if they have the same
11295 // underlying type.
11296 return ED1->isComplete() && ED2->isComplete() &&
11297 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11298}
11299
11300/// \brief Check if two fields are layout-compatible.
11301bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11302 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11303 return false;
11304
11305 if (Field1->isBitField() != Field2->isBitField())
11306 return false;
11307
11308 if (Field1->isBitField()) {
11309 // Make sure that the bit-fields are the same length.
11310 unsigned Bits1 = Field1->getBitWidthValue(C);
11311 unsigned Bits2 = Field2->getBitWidthValue(C);
11312
11313 if (Bits1 != Bits2)
11314 return false;
11315 }
11316
11317 return true;
11318}
11319
11320/// \brief Check if two standard-layout structs are layout-compatible.
11321/// (C++11 [class.mem] p17)
11322bool isLayoutCompatibleStruct(ASTContext &C,
11323 RecordDecl *RD1,
11324 RecordDecl *RD2) {
11325 // If both records are C++ classes, check that base classes match.
11326 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11327 // If one of records is a CXXRecordDecl we are in C++ mode,
11328 // thus the other one is a CXXRecordDecl, too.
11329 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11330 // Check number of base classes.
11331 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11332 return false;
11333
11334 // Check the base classes.
11335 for (CXXRecordDecl::base_class_const_iterator
11336 Base1 = D1CXX->bases_begin(),
11337 BaseEnd1 = D1CXX->bases_end(),
11338 Base2 = D2CXX->bases_begin();
11339 Base1 != BaseEnd1;
11340 ++Base1, ++Base2) {
11341 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11342 return false;
11343 }
11344 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11345 // If only RD2 is a C++ class, it should have zero base classes.
11346 if (D2CXX->getNumBases() > 0)
11347 return false;
11348 }
11349
11350 // Check the fields.
11351 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11352 Field2End = RD2->field_end(),
11353 Field1 = RD1->field_begin(),
11354 Field1End = RD1->field_end();
11355 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11356 if (!isLayoutCompatible(C, *Field1, *Field2))
11357 return false;
11358 }
11359 if (Field1 != Field1End || Field2 != Field2End)
11360 return false;
11361
11362 return true;
11363}
11364
11365/// \brief Check if two standard-layout unions are layout-compatible.
11366/// (C++11 [class.mem] p18)
11367bool isLayoutCompatibleUnion(ASTContext &C,
11368 RecordDecl *RD1,
11369 RecordDecl *RD2) {
11370 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011371 for (auto *Field2 : RD2->fields())
11372 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011373
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011374 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011375 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11376 I = UnmatchedFields.begin(),
11377 E = UnmatchedFields.end();
11378
11379 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011380 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011381 bool Result = UnmatchedFields.erase(*I);
11382 (void) Result;
11383 assert(Result);
11384 break;
11385 }
11386 }
11387 if (I == E)
11388 return false;
11389 }
11390
11391 return UnmatchedFields.empty();
11392}
11393
11394bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11395 if (RD1->isUnion() != RD2->isUnion())
11396 return false;
11397
11398 if (RD1->isUnion())
11399 return isLayoutCompatibleUnion(C, RD1, RD2);
11400 else
11401 return isLayoutCompatibleStruct(C, RD1, RD2);
11402}
11403
11404/// \brief Check if two types are layout-compatible in C++11 sense.
11405bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11406 if (T1.isNull() || T2.isNull())
11407 return false;
11408
11409 // C++11 [basic.types] p11:
11410 // If two types T1 and T2 are the same type, then T1 and T2 are
11411 // layout-compatible types.
11412 if (C.hasSameType(T1, T2))
11413 return true;
11414
11415 T1 = T1.getCanonicalType().getUnqualifiedType();
11416 T2 = T2.getCanonicalType().getUnqualifiedType();
11417
11418 const Type::TypeClass TC1 = T1->getTypeClass();
11419 const Type::TypeClass TC2 = T2->getTypeClass();
11420
11421 if (TC1 != TC2)
11422 return false;
11423
11424 if (TC1 == Type::Enum) {
11425 return isLayoutCompatible(C,
11426 cast<EnumType>(T1)->getDecl(),
11427 cast<EnumType>(T2)->getDecl());
11428 } else if (TC1 == Type::Record) {
11429 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11430 return false;
11431
11432 return isLayoutCompatible(C,
11433 cast<RecordType>(T1)->getDecl(),
11434 cast<RecordType>(T2)->getDecl());
11435 }
11436
11437 return false;
11438}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011439} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011440
11441//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11442
11443namespace {
11444/// \brief Given a type tag expression find the type tag itself.
11445///
11446/// \param TypeExpr Type tag expression, as it appears in user's code.
11447///
11448/// \param VD Declaration of an identifier that appears in a type tag.
11449///
11450/// \param MagicValue Type tag magic value.
11451bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11452 const ValueDecl **VD, uint64_t *MagicValue) {
11453 while(true) {
11454 if (!TypeExpr)
11455 return false;
11456
11457 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11458
11459 switch (TypeExpr->getStmtClass()) {
11460 case Stmt::UnaryOperatorClass: {
11461 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11462 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11463 TypeExpr = UO->getSubExpr();
11464 continue;
11465 }
11466 return false;
11467 }
11468
11469 case Stmt::DeclRefExprClass: {
11470 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11471 *VD = DRE->getDecl();
11472 return true;
11473 }
11474
11475 case Stmt::IntegerLiteralClass: {
11476 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11477 llvm::APInt MagicValueAPInt = IL->getValue();
11478 if (MagicValueAPInt.getActiveBits() <= 64) {
11479 *MagicValue = MagicValueAPInt.getZExtValue();
11480 return true;
11481 } else
11482 return false;
11483 }
11484
11485 case Stmt::BinaryConditionalOperatorClass:
11486 case Stmt::ConditionalOperatorClass: {
11487 const AbstractConditionalOperator *ACO =
11488 cast<AbstractConditionalOperator>(TypeExpr);
11489 bool Result;
11490 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11491 if (Result)
11492 TypeExpr = ACO->getTrueExpr();
11493 else
11494 TypeExpr = ACO->getFalseExpr();
11495 continue;
11496 }
11497 return false;
11498 }
11499
11500 case Stmt::BinaryOperatorClass: {
11501 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11502 if (BO->getOpcode() == BO_Comma) {
11503 TypeExpr = BO->getRHS();
11504 continue;
11505 }
11506 return false;
11507 }
11508
11509 default:
11510 return false;
11511 }
11512 }
11513}
11514
11515/// \brief Retrieve the C type corresponding to type tag TypeExpr.
11516///
11517/// \param TypeExpr Expression that specifies a type tag.
11518///
11519/// \param MagicValues Registered magic values.
11520///
11521/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11522/// kind.
11523///
11524/// \param TypeInfo Information about the corresponding C type.
11525///
11526/// \returns true if the corresponding C type was found.
11527bool GetMatchingCType(
11528 const IdentifierInfo *ArgumentKind,
11529 const Expr *TypeExpr, const ASTContext &Ctx,
11530 const llvm::DenseMap<Sema::TypeTagMagicValue,
11531 Sema::TypeTagData> *MagicValues,
11532 bool &FoundWrongKind,
11533 Sema::TypeTagData &TypeInfo) {
11534 FoundWrongKind = false;
11535
11536 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000011537 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011538
11539 uint64_t MagicValue;
11540
11541 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11542 return false;
11543
11544 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000011545 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011546 if (I->getArgumentKind() != ArgumentKind) {
11547 FoundWrongKind = true;
11548 return false;
11549 }
11550 TypeInfo.Type = I->getMatchingCType();
11551 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11552 TypeInfo.MustBeNull = I->getMustBeNull();
11553 return true;
11554 }
11555 return false;
11556 }
11557
11558 if (!MagicValues)
11559 return false;
11560
11561 llvm::DenseMap<Sema::TypeTagMagicValue,
11562 Sema::TypeTagData>::const_iterator I =
11563 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11564 if (I == MagicValues->end())
11565 return false;
11566
11567 TypeInfo = I->second;
11568 return true;
11569}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011570} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011571
11572void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11573 uint64_t MagicValue, QualType Type,
11574 bool LayoutCompatible,
11575 bool MustBeNull) {
11576 if (!TypeTagForDatatypeMagicValues)
11577 TypeTagForDatatypeMagicValues.reset(
11578 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11579
11580 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11581 (*TypeTagForDatatypeMagicValues)[Magic] =
11582 TypeTagData(Type, LayoutCompatible, MustBeNull);
11583}
11584
11585namespace {
11586bool IsSameCharType(QualType T1, QualType T2) {
11587 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11588 if (!BT1)
11589 return false;
11590
11591 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11592 if (!BT2)
11593 return false;
11594
11595 BuiltinType::Kind T1Kind = BT1->getKind();
11596 BuiltinType::Kind T2Kind = BT2->getKind();
11597
11598 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
11599 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
11600 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11601 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11602}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011603} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011604
11605void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11606 const Expr * const *ExprArgs) {
11607 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11608 bool IsPointerAttr = Attr->getIsPointer();
11609
11610 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11611 bool FoundWrongKind;
11612 TypeTagData TypeInfo;
11613 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11614 TypeTagForDatatypeMagicValues.get(),
11615 FoundWrongKind, TypeInfo)) {
11616 if (FoundWrongKind)
11617 Diag(TypeTagExpr->getExprLoc(),
11618 diag::warn_type_tag_for_datatype_wrong_kind)
11619 << TypeTagExpr->getSourceRange();
11620 return;
11621 }
11622
11623 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11624 if (IsPointerAttr) {
11625 // Skip implicit cast of pointer to `void *' (as a function argument).
11626 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000011627 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000011628 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011629 ArgumentExpr = ICE->getSubExpr();
11630 }
11631 QualType ArgumentType = ArgumentExpr->getType();
11632
11633 // Passing a `void*' pointer shouldn't trigger a warning.
11634 if (IsPointerAttr && ArgumentType->isVoidPointerType())
11635 return;
11636
11637 if (TypeInfo.MustBeNull) {
11638 // Type tag with matching void type requires a null pointer.
11639 if (!ArgumentExpr->isNullPointerConstant(Context,
11640 Expr::NPC_ValueDependentIsNotNull)) {
11641 Diag(ArgumentExpr->getExprLoc(),
11642 diag::warn_type_safety_null_pointer_required)
11643 << ArgumentKind->getName()
11644 << ArgumentExpr->getSourceRange()
11645 << TypeTagExpr->getSourceRange();
11646 }
11647 return;
11648 }
11649
11650 QualType RequiredType = TypeInfo.Type;
11651 if (IsPointerAttr)
11652 RequiredType = Context.getPointerType(RequiredType);
11653
11654 bool mismatch = false;
11655 if (!TypeInfo.LayoutCompatible) {
11656 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
11657
11658 // C++11 [basic.fundamental] p1:
11659 // Plain char, signed char, and unsigned char are three distinct types.
11660 //
11661 // But we treat plain `char' as equivalent to `signed char' or `unsigned
11662 // char' depending on the current char signedness mode.
11663 if (mismatch)
11664 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
11665 RequiredType->getPointeeType())) ||
11666 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
11667 mismatch = false;
11668 } else
11669 if (IsPointerAttr)
11670 mismatch = !isLayoutCompatible(Context,
11671 ArgumentType->getPointeeType(),
11672 RequiredType->getPointeeType());
11673 else
11674 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
11675
11676 if (mismatch)
11677 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000011678 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011679 << TypeInfo.LayoutCompatible << RequiredType
11680 << ArgumentExpr->getSourceRange()
11681 << TypeTagExpr->getSourceRange();
11682}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011683
11684void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11685 CharUnits Alignment) {
11686 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
11687}
11688
11689void Sema::DiagnoseMisalignedMembers() {
11690 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000011691 const NamedDecl *ND = m.RD;
11692 if (ND->getName().empty()) {
11693 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
11694 ND = TD;
11695 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011696 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000011697 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011698 }
11699 MisalignedMembers.clear();
11700}
11701
11702void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011703 E = E->IgnoreParens();
11704 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011705 return;
11706 if (isa<UnaryOperator>(E) &&
11707 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
11708 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11709 if (isa<MemberExpr>(Op)) {
11710 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
11711 MisalignedMember(Op));
11712 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011713 (T->isIntegerType() ||
11714 (T->isPointerType() &&
11715 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011716 MisalignedMembers.erase(MA);
11717 }
11718 }
11719}
11720
11721void Sema::RefersToMemberWithReducedAlignment(
11722 Expr *E,
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011723 std::function<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011724 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011725 if (!ME)
11726 return;
11727
11728 // For a chain of MemberExpr like "a.b.c.d" this list
11729 // will keep FieldDecl's like [d, c, b].
11730 SmallVector<FieldDecl *, 4> ReverseMemberChain;
11731 const MemberExpr *TopME = nullptr;
11732 bool AnyIsPacked = false;
11733 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011734 QualType BaseType = ME->getBase()->getType();
11735 if (ME->isArrow())
11736 BaseType = BaseType->getPointeeType();
11737 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
11738
11739 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011740 auto *FD = dyn_cast<FieldDecl>(MD);
11741 // We do not care about non-data members.
11742 if (!FD || FD->isInvalidDecl())
11743 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011744
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011745 AnyIsPacked =
11746 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
11747 ReverseMemberChain.push_back(FD);
11748
11749 TopME = ME;
11750 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
11751 } while (ME);
11752 assert(TopME && "We did not compute a topmost MemberExpr!");
11753
11754 // Not the scope of this diagnostic.
11755 if (!AnyIsPacked)
11756 return;
11757
11758 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
11759 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
11760 // TODO: The innermost base of the member expression may be too complicated.
11761 // For now, just disregard these cases. This is left for future
11762 // improvement.
11763 if (!DRE && !isa<CXXThisExpr>(TopBase))
11764 return;
11765
11766 // Alignment expected by the whole expression.
11767 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
11768
11769 // No need to do anything else with this case.
11770 if (ExpectedAlignment.isOne())
11771 return;
11772
11773 // Synthesize offset of the whole access.
11774 CharUnits Offset;
11775 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
11776 I++) {
11777 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
11778 }
11779
11780 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
11781 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
11782 ReverseMemberChain.back()->getParent()->getTypeForDecl());
11783
11784 // The base expression of the innermost MemberExpr may give
11785 // stronger guarantees than the class containing the member.
11786 if (DRE && !TopME->isArrow()) {
11787 const ValueDecl *VD = DRE->getDecl();
11788 if (!VD->getType()->isReferenceType())
11789 CompleteObjectAlignment =
11790 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
11791 }
11792
11793 // Check if the synthesized offset fulfills the alignment.
11794 if (Offset % ExpectedAlignment != 0 ||
11795 // It may fulfill the offset it but the effective alignment may still be
11796 // lower than the expected expression alignment.
11797 CompleteObjectAlignment < ExpectedAlignment) {
11798 // If this happens, we want to determine a sensible culprit of this.
11799 // Intuitively, watching the chain of member expressions from right to
11800 // left, we start with the required alignment (as required by the field
11801 // type) but some packed attribute in that chain has reduced the alignment.
11802 // It may happen that another packed structure increases it again. But if
11803 // we are here such increase has not been enough. So pointing the first
11804 // FieldDecl that either is packed or else its RecordDecl is,
11805 // seems reasonable.
11806 FieldDecl *FD = nullptr;
11807 CharUnits Alignment;
11808 for (FieldDecl *FDI : ReverseMemberChain) {
11809 if (FDI->hasAttr<PackedAttr>() ||
11810 FDI->getParent()->hasAttr<PackedAttr>()) {
11811 FD = FDI;
11812 Alignment = std::min(
11813 Context.getTypeAlignInChars(FD->getType()),
11814 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
11815 break;
11816 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011817 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011818 assert(FD && "We did not find a packed FieldDecl!");
11819 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011820 }
11821}
11822
11823void Sema::CheckAddressOfPackedMember(Expr *rhs) {
11824 using namespace std::placeholders;
11825 RefersToMemberWithReducedAlignment(
11826 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
11827 _2, _3, _4));
11828}
11829