blob: 501f93ed6292fa41abb67c68a240ca8b73747905 [file] [log] [blame]
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattnerb87b1b32007-08-10 20:18:51 +000015#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000017#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000020#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000021#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000022#include "clang/AST/ExprObjC.h"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000023#include "clang/AST/ExprOpenMP.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000030#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000035#include "clang/Sema/SemaInternal.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000036#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000037#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "llvm/ADT/SmallString.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000039#include "llvm/Support/ConvertUTF.h"
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +000040#include "llvm/Support/Format.h"
41#include "llvm/Support/Locale.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000042#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000043
Chris Lattnerb87b1b32007-08-10 20:18:51 +000044using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000045using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000046
Chris Lattnera26fb342009-02-18 17:49:48 +000047SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
48 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000049 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
50 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000051}
52
John McCallbebede42011-02-26 05:39:39 +000053/// Checks that a call expression's argument count is the desired number.
54/// This is useful when doing custom type-checking. Returns true on error.
55static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
56 unsigned argCount = call->getNumArgs();
57 if (argCount == desiredArgCount) return false;
58
59 if (argCount < desiredArgCount)
60 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
61 << 0 /*function call*/ << desiredArgCount << argCount
62 << call->getSourceRange();
63
64 // Highlight all the excess arguments.
65 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
66 call->getArg(argCount - 1)->getLocEnd());
67
68 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
69 << 0 /*function call*/ << desiredArgCount << argCount
70 << call->getArg(1)->getSourceRange();
71}
72
Julien Lerouge4a5b4442012-04-28 17:39:16 +000073/// Check that the first argument to __builtin_annotation is an integer
74/// and the second argument is a non-wide string literal.
75static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
76 if (checkArgCount(S, TheCall, 2))
77 return true;
78
79 // First argument should be an integer.
80 Expr *ValArg = TheCall->getArg(0);
81 QualType Ty = ValArg->getType();
82 if (!Ty->isIntegerType()) {
83 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
84 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000085 return true;
86 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000087
88 // Second argument should be a constant string.
89 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
90 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
91 if (!Literal || !Literal->isAscii()) {
92 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
93 << StrArg->getSourceRange();
94 return true;
95 }
96
97 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000098 return false;
99}
100
Richard Smith6cbd65d2013-07-11 02:27:57 +0000101/// Check that the argument to __builtin_addressof is a glvalue, and set the
102/// result type to the corresponding pointer type.
103static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
104 if (checkArgCount(S, TheCall, 1))
105 return true;
106
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000107 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000108 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
109 if (ResultType.isNull())
110 return true;
111
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000112 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000113 TheCall->setType(ResultType);
114 return false;
115}
116
John McCall03107a42015-10-29 20:48:01 +0000117static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
118 if (checkArgCount(S, TheCall, 3))
119 return true;
120
121 // First two arguments should be integers.
122 for (unsigned I = 0; I < 2; ++I) {
123 Expr *Arg = TheCall->getArg(I);
124 QualType Ty = Arg->getType();
125 if (!Ty->isIntegerType()) {
126 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
127 << Ty << Arg->getSourceRange();
128 return true;
129 }
130 }
131
132 // Third argument should be a pointer to a non-const integer.
133 // IRGen correctly handles volatile, restrict, and address spaces, and
134 // the other qualifiers aren't possible.
135 {
136 Expr *Arg = TheCall->getArg(2);
137 QualType Ty = Arg->getType();
138 const auto *PtrTy = Ty->getAs<PointerType>();
139 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
140 !PtrTy->getPointeeType().isConstQualified())) {
141 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
142 << Ty << Arg->getSourceRange();
143 return true;
144 }
145 }
146
147 return false;
148}
149
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000150static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
151 CallExpr *TheCall, unsigned SizeIdx,
152 unsigned DstSizeIdx) {
153 if (TheCall->getNumArgs() <= SizeIdx ||
154 TheCall->getNumArgs() <= DstSizeIdx)
155 return;
156
157 const Expr *SizeArg = TheCall->getArg(SizeIdx);
158 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
159
160 llvm::APSInt Size, DstSize;
161
162 // find out if both sizes are known at compile time
163 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
164 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
165 return;
166
167 if (Size.ule(DstSize))
168 return;
169
170 // confirmed overflow so generate the diagnostic.
171 IdentifierInfo *FnName = FDecl->getIdentifier();
172 SourceLocation SL = TheCall->getLocStart();
173 SourceRange SR = TheCall->getSourceRange();
174
175 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
176}
177
Peter Collingbournef7706832014-12-12 23:41:25 +0000178static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
179 if (checkArgCount(S, BuiltinCall, 2))
180 return true;
181
182 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
183 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
184 Expr *Call = BuiltinCall->getArg(0);
185 Expr *Chain = BuiltinCall->getArg(1);
186
187 if (Call->getStmtClass() != Stmt::CallExprClass) {
188 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
189 << Call->getSourceRange();
190 return true;
191 }
192
193 auto CE = cast<CallExpr>(Call);
194 if (CE->getCallee()->getType()->isBlockPointerType()) {
195 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
196 << Call->getSourceRange();
197 return true;
198 }
199
200 const Decl *TargetDecl = CE->getCalleeDecl();
201 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
202 if (FD->getBuiltinID()) {
203 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
204 << Call->getSourceRange();
205 return true;
206 }
207
208 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
209 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
210 << Call->getSourceRange();
211 return true;
212 }
213
214 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
215 if (ChainResult.isInvalid())
216 return true;
217 if (!ChainResult.get()->getType()->isPointerType()) {
218 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
219 << Chain->getSourceRange();
220 return true;
221 }
222
David Majnemerced8bdf2015-02-25 17:36:15 +0000223 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000224 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
225 QualType BuiltinTy = S.Context.getFunctionType(
226 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
227 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
228
229 Builtin =
230 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
231
232 BuiltinCall->setType(CE->getType());
233 BuiltinCall->setValueKind(CE->getValueKind());
234 BuiltinCall->setObjectKind(CE->getObjectKind());
235 BuiltinCall->setCallee(Builtin);
236 BuiltinCall->setArg(1, ChainResult.get());
237
238 return false;
239}
240
Reid Kleckner1d59f992015-01-22 01:36:17 +0000241static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
242 Scope::ScopeFlags NeededScopeFlags,
243 unsigned DiagID) {
244 // Scopes aren't available during instantiation. Fortunately, builtin
245 // functions cannot be template args so they cannot be formed through template
246 // instantiation. Therefore checking once during the parse is sufficient.
247 if (!SemaRef.ActiveTemplateInstantiations.empty())
248 return false;
249
250 Scope *S = SemaRef.getCurScope();
251 while (S && !S->isSEHExceptScope())
252 S = S->getParent();
253 if (!S || !(S->getFlags() & NeededScopeFlags)) {
254 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
255 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
256 << DRE->getDecl()->getIdentifier();
257 return true;
258 }
259
260 return false;
261}
262
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000263static inline bool isBlockPointer(Expr *Arg) {
264 return Arg->getType()->isBlockPointerType();
265}
266
267/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
268/// void*, which is a requirement of device side enqueue.
269static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
270 const BlockPointerType *BPT =
271 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
272 ArrayRef<QualType> Params =
273 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
274 unsigned ArgCounter = 0;
275 bool IllegalParams = false;
276 // Iterate through the block parameters until either one is found that is not
277 // a local void*, or the block is valid.
278 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
279 I != E; ++I, ++ArgCounter) {
280 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
281 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
282 LangAS::opencl_local) {
283 // Get the location of the error. If a block literal has been passed
284 // (BlockExpr) then we can point straight to the offending argument,
285 // else we just point to the variable reference.
286 SourceLocation ErrorLoc;
287 if (isa<BlockExpr>(BlockArg)) {
288 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
289 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
290 } else if (isa<DeclRefExpr>(BlockArg)) {
291 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
292 }
293 S.Diag(ErrorLoc,
294 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
295 IllegalParams = true;
296 }
297 }
298
299 return IllegalParams;
300}
301
302/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
303/// get_kernel_work_group_size
304/// and get_kernel_preferred_work_group_size_multiple builtin functions.
305static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
306 if (checkArgCount(S, TheCall, 1))
307 return true;
308
309 Expr *BlockArg = TheCall->getArg(0);
310 if (!isBlockPointer(BlockArg)) {
311 S.Diag(BlockArg->getLocStart(),
312 diag::err_opencl_enqueue_kernel_expected_type) << "block";
313 return true;
314 }
315 return checkOpenCLBlockArgs(S, BlockArg);
316}
317
318static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
319 unsigned Start, unsigned End);
320
321/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
322/// 'local void*' parameter of passed block.
323static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
324 Expr *BlockArg,
325 unsigned NumNonVarArgs) {
326 const BlockPointerType *BPT =
327 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
328 unsigned NumBlockParams =
329 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
330 unsigned TotalNumArgs = TheCall->getNumArgs();
331
332 // For each argument passed to the block, a corresponding uint needs to
333 // be passed to describe the size of the local memory.
334 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
335 S.Diag(TheCall->getLocStart(),
336 diag::err_opencl_enqueue_kernel_local_size_args);
337 return true;
338 }
339
340 // Check that the sizes of the local memory are specified by integers.
341 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
342 TotalNumArgs - 1);
343}
344
345/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
346/// overload formats specified in Table 6.13.17.1.
347/// int enqueue_kernel(queue_t queue,
348/// kernel_enqueue_flags_t flags,
349/// const ndrange_t ndrange,
350/// void (^block)(void))
351/// int enqueue_kernel(queue_t queue,
352/// kernel_enqueue_flags_t flags,
353/// const ndrange_t ndrange,
354/// uint num_events_in_wait_list,
355/// clk_event_t *event_wait_list,
356/// clk_event_t *event_ret,
357/// void (^block)(void))
358/// int enqueue_kernel(queue_t queue,
359/// kernel_enqueue_flags_t flags,
360/// const ndrange_t ndrange,
361/// void (^block)(local void*, ...),
362/// uint size0, ...)
363/// int enqueue_kernel(queue_t queue,
364/// kernel_enqueue_flags_t flags,
365/// const ndrange_t ndrange,
366/// uint num_events_in_wait_list,
367/// clk_event_t *event_wait_list,
368/// clk_event_t *event_ret,
369/// void (^block)(local void*, ...),
370/// uint size0, ...)
371static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
372 unsigned NumArgs = TheCall->getNumArgs();
373
374 if (NumArgs < 4) {
375 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
376 return true;
377 }
378
379 Expr *Arg0 = TheCall->getArg(0);
380 Expr *Arg1 = TheCall->getArg(1);
381 Expr *Arg2 = TheCall->getArg(2);
382 Expr *Arg3 = TheCall->getArg(3);
383
384 // First argument always needs to be a queue_t type.
385 if (!Arg0->getType()->isQueueT()) {
386 S.Diag(TheCall->getArg(0)->getLocStart(),
387 diag::err_opencl_enqueue_kernel_expected_type)
388 << S.Context.OCLQueueTy;
389 return true;
390 }
391
392 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
393 if (!Arg1->getType()->isIntegerType()) {
394 S.Diag(TheCall->getArg(1)->getLocStart(),
395 diag::err_opencl_enqueue_kernel_expected_type)
396 << "'kernel_enqueue_flags_t' (i.e. uint)";
397 return true;
398 }
399
400 // Third argument is always an ndrange_t type.
401 if (!Arg2->getType()->isNDRangeT()) {
402 S.Diag(TheCall->getArg(2)->getLocStart(),
403 diag::err_opencl_enqueue_kernel_expected_type)
404 << S.Context.OCLNDRangeTy;
405 return true;
406 }
407
408 // With four arguments, there is only one form that the function could be
409 // called in: no events and no variable arguments.
410 if (NumArgs == 4) {
411 // check that the last argument is the right block type.
412 if (!isBlockPointer(Arg3)) {
413 S.Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
414 << "block";
415 return true;
416 }
417 // we have a block type, check the prototype
418 const BlockPointerType *BPT =
419 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
420 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
421 S.Diag(Arg3->getLocStart(),
422 diag::err_opencl_enqueue_kernel_blocks_no_args);
423 return true;
424 }
425 return false;
426 }
427 // we can have block + varargs.
428 if (isBlockPointer(Arg3))
429 return (checkOpenCLBlockArgs(S, Arg3) ||
430 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
431 // last two cases with either exactly 7 args or 7 args and varargs.
432 if (NumArgs >= 7) {
433 // check common block argument.
434 Expr *Arg6 = TheCall->getArg(6);
435 if (!isBlockPointer(Arg6)) {
436 S.Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
437 << "block";
438 return true;
439 }
440 if (checkOpenCLBlockArgs(S, Arg6))
441 return true;
442
443 // Forth argument has to be any integer type.
444 if (!Arg3->getType()->isIntegerType()) {
445 S.Diag(TheCall->getArg(3)->getLocStart(),
446 diag::err_opencl_enqueue_kernel_expected_type)
447 << "integer";
448 return true;
449 }
450 // check remaining common arguments.
451 Expr *Arg4 = TheCall->getArg(4);
452 Expr *Arg5 = TheCall->getArg(5);
453
454 // Fith argument is always passed as pointers to clk_event_t.
455 if (!Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
456 S.Diag(TheCall->getArg(4)->getLocStart(),
457 diag::err_opencl_enqueue_kernel_expected_type)
458 << S.Context.getPointerType(S.Context.OCLClkEventTy);
459 return true;
460 }
461
462 // Sixth argument is always passed as pointers to clk_event_t.
463 if (!(Arg5->getType()->isPointerType() &&
464 Arg5->getType()->getPointeeType()->isClkEventT())) {
465 S.Diag(TheCall->getArg(5)->getLocStart(),
466 diag::err_opencl_enqueue_kernel_expected_type)
467 << S.Context.getPointerType(S.Context.OCLClkEventTy);
468 return true;
469 }
470
471 if (NumArgs == 7)
472 return false;
473
474 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
475 }
476
477 // None of the specific case has been detected, give generic error
478 S.Diag(TheCall->getLocStart(),
479 diag::err_opencl_enqueue_kernel_incorrect_args);
480 return true;
481}
482
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000483/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000484static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000485 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000486}
487
488/// Returns true if pipe element type is different from the pointer.
489static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
490 const Expr *Arg0 = Call->getArg(0);
491 // First argument type should always be pipe.
492 if (!Arg0->getType()->isPipeType()) {
493 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000494 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000495 return true;
496 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000497 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000498 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
499 // Validates the access qualifier is compatible with the call.
500 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
501 // read_only and write_only, and assumed to be read_only if no qualifier is
502 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000503 switch (Call->getDirectCallee()->getBuiltinID()) {
504 case Builtin::BIread_pipe:
505 case Builtin::BIreserve_read_pipe:
506 case Builtin::BIcommit_read_pipe:
507 case Builtin::BIwork_group_reserve_read_pipe:
508 case Builtin::BIsub_group_reserve_read_pipe:
509 case Builtin::BIwork_group_commit_read_pipe:
510 case Builtin::BIsub_group_commit_read_pipe:
511 if (!(!AccessQual || AccessQual->isReadOnly())) {
512 S.Diag(Arg0->getLocStart(),
513 diag::err_opencl_builtin_pipe_invalid_access_modifier)
514 << "read_only" << Arg0->getSourceRange();
515 return true;
516 }
517 break;
518 case Builtin::BIwrite_pipe:
519 case Builtin::BIreserve_write_pipe:
520 case Builtin::BIcommit_write_pipe:
521 case Builtin::BIwork_group_reserve_write_pipe:
522 case Builtin::BIsub_group_reserve_write_pipe:
523 case Builtin::BIwork_group_commit_write_pipe:
524 case Builtin::BIsub_group_commit_write_pipe:
525 if (!(AccessQual && AccessQual->isWriteOnly())) {
526 S.Diag(Arg0->getLocStart(),
527 diag::err_opencl_builtin_pipe_invalid_access_modifier)
528 << "write_only" << Arg0->getSourceRange();
529 return true;
530 }
531 break;
532 default:
533 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000534 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000535 return false;
536}
537
538/// Returns true if pipe element type is different from the pointer.
539static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
540 const Expr *Arg0 = Call->getArg(0);
541 const Expr *ArgIdx = Call->getArg(Idx);
542 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000543 const QualType EltTy = PipeTy->getElementType();
544 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000545 // The Idx argument should be a pointer and the type of the pointer and
546 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000547 if (!ArgTy ||
548 !S.Context.hasSameType(
549 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000550 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000551 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000552 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000553 return true;
554 }
555 return false;
556}
557
558// \brief Performs semantic analysis for the read/write_pipe call.
559// \param S Reference to the semantic analyzer.
560// \param Call A pointer to the builtin call.
561// \return True if a semantic error has been found, false otherwise.
562static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000563 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
564 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000565 switch (Call->getNumArgs()) {
566 case 2: {
567 if (checkOpenCLPipeArg(S, Call))
568 return true;
569 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000570 // read/write_pipe(pipe T, T*).
571 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000572 if (checkOpenCLPipePacketType(S, Call, 1))
573 return true;
574 } break;
575
576 case 4: {
577 if (checkOpenCLPipeArg(S, Call))
578 return true;
579 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000580 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
581 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000582 if (!Call->getArg(1)->getType()->isReserveIDT()) {
583 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000584 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000585 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000586 return true;
587 }
588
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000589 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000590 const Expr *Arg2 = Call->getArg(2);
591 if (!Arg2->getType()->isIntegerType() &&
592 !Arg2->getType()->isUnsignedIntegerType()) {
593 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000594 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000595 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000596 return true;
597 }
598
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000599 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000600 if (checkOpenCLPipePacketType(S, Call, 3))
601 return true;
602 } break;
603 default:
604 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000605 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000606 return true;
607 }
608
609 return false;
610}
611
612// \brief Performs a semantic analysis on the {work_group_/sub_group_
613// /_}reserve_{read/write}_pipe
614// \param S Reference to the semantic analyzer.
615// \param Call The call to the builtin function to be analyzed.
616// \return True if a semantic error was found, false otherwise.
617static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
618 if (checkArgCount(S, Call, 2))
619 return true;
620
621 if (checkOpenCLPipeArg(S, Call))
622 return true;
623
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000624 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000625 if (!Call->getArg(1)->getType()->isIntegerType() &&
626 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
627 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000628 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000629 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000630 return true;
631 }
632
633 return false;
634}
635
636// \brief Performs a semantic analysis on {work_group_/sub_group_
637// /_}commit_{read/write}_pipe
638// \param S Reference to the semantic analyzer.
639// \param Call The call to the builtin function to be analyzed.
640// \return True if a semantic error was found, false otherwise.
641static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
642 if (checkArgCount(S, Call, 2))
643 return true;
644
645 if (checkOpenCLPipeArg(S, Call))
646 return true;
647
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000648 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000649 if (!Call->getArg(1)->getType()->isReserveIDT()) {
650 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000651 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000652 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000653 return true;
654 }
655
656 return false;
657}
658
659// \brief Performs a semantic analysis on the call to built-in Pipe
660// Query Functions.
661// \param S Reference to the semantic analyzer.
662// \param Call The call to the builtin function to be analyzed.
663// \return True if a semantic error was found, false otherwise.
664static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
665 if (checkArgCount(S, Call, 1))
666 return true;
667
668 if (!Call->getArg(0)->getType()->isPipeType()) {
669 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000670 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000671 return true;
672 }
673
674 return false;
675}
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +0000676// \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
Yaxun Liuf7449a12016-05-20 19:54:38 +0000677// \brief Performs semantic analysis for the to_global/local/private call.
678// \param S Reference to the semantic analyzer.
679// \param BuiltinID ID of the builtin function.
680// \param Call A pointer to the builtin call.
681// \return True if a semantic error has been found, false otherwise.
682static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
683 CallExpr *Call) {
Yaxun Liuf7449a12016-05-20 19:54:38 +0000684 if (Call->getNumArgs() != 1) {
685 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
686 << Call->getDirectCallee() << Call->getSourceRange();
687 return true;
688 }
689
690 auto RT = Call->getArg(0)->getType();
691 if (!RT->isPointerType() || RT->getPointeeType()
692 .getAddressSpace() == LangAS::opencl_constant) {
693 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
694 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
695 return true;
696 }
697
698 RT = RT->getPointeeType();
699 auto Qual = RT.getQualifiers();
700 switch (BuiltinID) {
701 case Builtin::BIto_global:
702 Qual.setAddressSpace(LangAS::opencl_global);
703 break;
704 case Builtin::BIto_local:
705 Qual.setAddressSpace(LangAS::opencl_local);
706 break;
707 default:
708 Qual.removeAddressSpace();
709 }
710 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
711 RT.getUnqualifiedType(), Qual)));
712
713 return false;
714}
715
John McCalldadc5752010-08-24 06:29:42 +0000716ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000717Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
718 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000719 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000720
Chris Lattner3be167f2010-10-01 23:23:24 +0000721 // Find out if any arguments are required to be integer constant expressions.
722 unsigned ICEArguments = 0;
723 ASTContext::GetBuiltinTypeError Error;
724 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
725 if (Error != ASTContext::GE_None)
726 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
727
728 // If any arguments are required to be ICE's, check and diagnose.
729 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
730 // Skip arguments not required to be ICE's.
731 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
732
733 llvm::APSInt Result;
734 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
735 return true;
736 ICEArguments &= ~(1 << ArgNo);
737 }
738
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000739 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000740 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000741 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000742 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000743 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000744 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000745 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000746 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000747 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000748 if (SemaBuiltinVAStart(TheCall))
749 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000750 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000751 case Builtin::BI__va_start: {
752 switch (Context.getTargetInfo().getTriple().getArch()) {
753 case llvm::Triple::arm:
754 case llvm::Triple::thumb:
755 if (SemaBuiltinVAStartARM(TheCall))
756 return ExprError();
757 break;
758 default:
759 if (SemaBuiltinVAStart(TheCall))
760 return ExprError();
761 break;
762 }
763 break;
764 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000765 case Builtin::BI__builtin_isgreater:
766 case Builtin::BI__builtin_isgreaterequal:
767 case Builtin::BI__builtin_isless:
768 case Builtin::BI__builtin_islessequal:
769 case Builtin::BI__builtin_islessgreater:
770 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000771 if (SemaBuiltinUnorderedCompare(TheCall))
772 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000773 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000774 case Builtin::BI__builtin_fpclassify:
775 if (SemaBuiltinFPClassification(TheCall, 6))
776 return ExprError();
777 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000778 case Builtin::BI__builtin_isfinite:
779 case Builtin::BI__builtin_isinf:
780 case Builtin::BI__builtin_isinf_sign:
781 case Builtin::BI__builtin_isnan:
782 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000783 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000784 return ExprError();
785 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000786 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000787 return SemaBuiltinShuffleVector(TheCall);
788 // TheCall will be freed by the smart pointer here, but that's fine, since
789 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000790 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000791 if (SemaBuiltinPrefetch(TheCall))
792 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000793 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000794 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000795 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000796 if (SemaBuiltinAssume(TheCall))
797 return ExprError();
798 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000799 case Builtin::BI__builtin_assume_aligned:
800 if (SemaBuiltinAssumeAligned(TheCall))
801 return ExprError();
802 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000803 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000804 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000805 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000806 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000807 case Builtin::BI__builtin_longjmp:
808 if (SemaBuiltinLongjmp(TheCall))
809 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000810 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000811 case Builtin::BI__builtin_setjmp:
812 if (SemaBuiltinSetjmp(TheCall))
813 return ExprError();
814 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000815 case Builtin::BI_setjmp:
816 case Builtin::BI_setjmpex:
817 if (checkArgCount(*this, TheCall, 1))
818 return true;
819 break;
John McCallbebede42011-02-26 05:39:39 +0000820
821 case Builtin::BI__builtin_classify_type:
822 if (checkArgCount(*this, TheCall, 1)) return true;
823 TheCall->setType(Context.IntTy);
824 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000825 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000826 if (checkArgCount(*this, TheCall, 1)) return true;
827 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000828 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000829 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000830 case Builtin::BI__sync_fetch_and_add_1:
831 case Builtin::BI__sync_fetch_and_add_2:
832 case Builtin::BI__sync_fetch_and_add_4:
833 case Builtin::BI__sync_fetch_and_add_8:
834 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000835 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000836 case Builtin::BI__sync_fetch_and_sub_1:
837 case Builtin::BI__sync_fetch_and_sub_2:
838 case Builtin::BI__sync_fetch_and_sub_4:
839 case Builtin::BI__sync_fetch_and_sub_8:
840 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000841 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000842 case Builtin::BI__sync_fetch_and_or_1:
843 case Builtin::BI__sync_fetch_and_or_2:
844 case Builtin::BI__sync_fetch_and_or_4:
845 case Builtin::BI__sync_fetch_and_or_8:
846 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000847 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000848 case Builtin::BI__sync_fetch_and_and_1:
849 case Builtin::BI__sync_fetch_and_and_2:
850 case Builtin::BI__sync_fetch_and_and_4:
851 case Builtin::BI__sync_fetch_and_and_8:
852 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000853 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000854 case Builtin::BI__sync_fetch_and_xor_1:
855 case Builtin::BI__sync_fetch_and_xor_2:
856 case Builtin::BI__sync_fetch_and_xor_4:
857 case Builtin::BI__sync_fetch_and_xor_8:
858 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000859 case Builtin::BI__sync_fetch_and_nand:
860 case Builtin::BI__sync_fetch_and_nand_1:
861 case Builtin::BI__sync_fetch_and_nand_2:
862 case Builtin::BI__sync_fetch_and_nand_4:
863 case Builtin::BI__sync_fetch_and_nand_8:
864 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000865 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000866 case Builtin::BI__sync_add_and_fetch_1:
867 case Builtin::BI__sync_add_and_fetch_2:
868 case Builtin::BI__sync_add_and_fetch_4:
869 case Builtin::BI__sync_add_and_fetch_8:
870 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000871 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000872 case Builtin::BI__sync_sub_and_fetch_1:
873 case Builtin::BI__sync_sub_and_fetch_2:
874 case Builtin::BI__sync_sub_and_fetch_4:
875 case Builtin::BI__sync_sub_and_fetch_8:
876 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000877 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000878 case Builtin::BI__sync_and_and_fetch_1:
879 case Builtin::BI__sync_and_and_fetch_2:
880 case Builtin::BI__sync_and_and_fetch_4:
881 case Builtin::BI__sync_and_and_fetch_8:
882 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000883 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000884 case Builtin::BI__sync_or_and_fetch_1:
885 case Builtin::BI__sync_or_and_fetch_2:
886 case Builtin::BI__sync_or_and_fetch_4:
887 case Builtin::BI__sync_or_and_fetch_8:
888 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000889 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000890 case Builtin::BI__sync_xor_and_fetch_1:
891 case Builtin::BI__sync_xor_and_fetch_2:
892 case Builtin::BI__sync_xor_and_fetch_4:
893 case Builtin::BI__sync_xor_and_fetch_8:
894 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000895 case Builtin::BI__sync_nand_and_fetch:
896 case Builtin::BI__sync_nand_and_fetch_1:
897 case Builtin::BI__sync_nand_and_fetch_2:
898 case Builtin::BI__sync_nand_and_fetch_4:
899 case Builtin::BI__sync_nand_and_fetch_8:
900 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000901 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000902 case Builtin::BI__sync_val_compare_and_swap_1:
903 case Builtin::BI__sync_val_compare_and_swap_2:
904 case Builtin::BI__sync_val_compare_and_swap_4:
905 case Builtin::BI__sync_val_compare_and_swap_8:
906 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000907 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000908 case Builtin::BI__sync_bool_compare_and_swap_1:
909 case Builtin::BI__sync_bool_compare_and_swap_2:
910 case Builtin::BI__sync_bool_compare_and_swap_4:
911 case Builtin::BI__sync_bool_compare_and_swap_8:
912 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000913 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000914 case Builtin::BI__sync_lock_test_and_set_1:
915 case Builtin::BI__sync_lock_test_and_set_2:
916 case Builtin::BI__sync_lock_test_and_set_4:
917 case Builtin::BI__sync_lock_test_and_set_8:
918 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000919 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000920 case Builtin::BI__sync_lock_release_1:
921 case Builtin::BI__sync_lock_release_2:
922 case Builtin::BI__sync_lock_release_4:
923 case Builtin::BI__sync_lock_release_8:
924 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000925 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000926 case Builtin::BI__sync_swap_1:
927 case Builtin::BI__sync_swap_2:
928 case Builtin::BI__sync_swap_4:
929 case Builtin::BI__sync_swap_8:
930 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000931 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000932 case Builtin::BI__builtin_nontemporal_load:
933 case Builtin::BI__builtin_nontemporal_store:
934 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000935#define BUILTIN(ID, TYPE, ATTRS)
936#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
937 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000938 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000939#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000940 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000941 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000942 return ExprError();
943 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000944 case Builtin::BI__builtin_addressof:
945 if (SemaBuiltinAddressof(*this, TheCall))
946 return ExprError();
947 break;
John McCall03107a42015-10-29 20:48:01 +0000948 case Builtin::BI__builtin_add_overflow:
949 case Builtin::BI__builtin_sub_overflow:
950 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +0000951 if (SemaBuiltinOverflow(*this, TheCall))
952 return ExprError();
953 break;
Richard Smith760520b2014-06-03 23:27:44 +0000954 case Builtin::BI__builtin_operator_new:
955 case Builtin::BI__builtin_operator_delete:
956 if (!getLangOpts().CPlusPlus) {
957 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
958 << (BuiltinID == Builtin::BI__builtin_operator_new
959 ? "__builtin_operator_new"
960 : "__builtin_operator_delete")
961 << "C++";
962 return ExprError();
963 }
964 // CodeGen assumes it can find the global new and delete to call,
965 // so ensure that they are declared.
966 DeclareGlobalNewDelete();
967 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000968
969 // check secure string manipulation functions where overflows
970 // are detectable at compile time
971 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000972 case Builtin::BI__builtin___memmove_chk:
973 case Builtin::BI__builtin___memset_chk:
974 case Builtin::BI__builtin___strlcat_chk:
975 case Builtin::BI__builtin___strlcpy_chk:
976 case Builtin::BI__builtin___strncat_chk:
977 case Builtin::BI__builtin___strncpy_chk:
978 case Builtin::BI__builtin___stpncpy_chk:
979 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
980 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000981 case Builtin::BI__builtin___memccpy_chk:
982 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
983 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000984 case Builtin::BI__builtin___snprintf_chk:
985 case Builtin::BI__builtin___vsnprintf_chk:
986 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
987 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000988 case Builtin::BI__builtin_call_with_static_chain:
989 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
990 return ExprError();
991 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000992 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000993 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +0000994 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
995 diag::err_seh___except_block))
996 return ExprError();
997 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000998 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000999 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001000 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1001 diag::err_seh___except_filter))
1002 return ExprError();
1003 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001004 case Builtin::BI__GetExceptionInfo:
1005 if (checkArgCount(*this, TheCall, 1))
1006 return ExprError();
1007
1008 if (CheckCXXThrowOperand(
1009 TheCall->getLocStart(),
1010 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1011 TheCall))
1012 return ExprError();
1013
1014 TheCall->setType(Context.VoidPtrTy);
1015 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001016 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001017 case Builtin::BIread_pipe:
1018 case Builtin::BIwrite_pipe:
1019 // Since those two functions are declared with var args, we need a semantic
1020 // check for the argument.
1021 if (SemaBuiltinRWPipe(*this, TheCall))
1022 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001023 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001024 break;
1025 case Builtin::BIreserve_read_pipe:
1026 case Builtin::BIreserve_write_pipe:
1027 case Builtin::BIwork_group_reserve_read_pipe:
1028 case Builtin::BIwork_group_reserve_write_pipe:
1029 case Builtin::BIsub_group_reserve_read_pipe:
1030 case Builtin::BIsub_group_reserve_write_pipe:
1031 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1032 return ExprError();
1033 // Since return type of reserve_read/write_pipe built-in function is
1034 // reserve_id_t, which is not defined in the builtin def file , we used int
1035 // as return type and need to override the return type of these functions.
1036 TheCall->setType(Context.OCLReserveIDTy);
1037 break;
1038 case Builtin::BIcommit_read_pipe:
1039 case Builtin::BIcommit_write_pipe:
1040 case Builtin::BIwork_group_commit_read_pipe:
1041 case Builtin::BIwork_group_commit_write_pipe:
1042 case Builtin::BIsub_group_commit_read_pipe:
1043 case Builtin::BIsub_group_commit_write_pipe:
1044 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1045 return ExprError();
1046 break;
1047 case Builtin::BIget_pipe_num_packets:
1048 case Builtin::BIget_pipe_max_packets:
1049 if (SemaBuiltinPipePackets(*this, TheCall))
1050 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001051 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001052 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001053 case Builtin::BIto_global:
1054 case Builtin::BIto_local:
1055 case Builtin::BIto_private:
1056 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1057 return ExprError();
1058 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001059 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1060 case Builtin::BIenqueue_kernel:
1061 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1062 return ExprError();
1063 break;
1064 case Builtin::BIget_kernel_work_group_size:
1065 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1066 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1067 return ExprError();
Nate Begeman4904e322010-06-08 02:47:44 +00001068 }
Richard Smith760520b2014-06-03 23:27:44 +00001069
Nate Begeman4904e322010-06-08 02:47:44 +00001070 // Since the target specific builtins for each arch overlap, only check those
1071 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001072 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001073 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001074 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001075 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001076 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001077 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001078 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1079 return ExprError();
1080 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001081 case llvm::Triple::aarch64:
1082 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001083 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001084 return ExprError();
1085 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001086 case llvm::Triple::mips:
1087 case llvm::Triple::mipsel:
1088 case llvm::Triple::mips64:
1089 case llvm::Triple::mips64el:
1090 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1091 return ExprError();
1092 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001093 case llvm::Triple::systemz:
1094 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1095 return ExprError();
1096 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001097 case llvm::Triple::x86:
1098 case llvm::Triple::x86_64:
1099 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1100 return ExprError();
1101 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001102 case llvm::Triple::ppc:
1103 case llvm::Triple::ppc64:
1104 case llvm::Triple::ppc64le:
1105 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1106 return ExprError();
1107 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001108 default:
1109 break;
1110 }
1111 }
1112
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001113 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001114}
1115
Nate Begeman91e1fea2010-06-14 05:21:25 +00001116// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001117static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001118 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001119 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001120 switch (Type.getEltType()) {
1121 case NeonTypeFlags::Int8:
1122 case NeonTypeFlags::Poly8:
1123 return shift ? 7 : (8 << IsQuad) - 1;
1124 case NeonTypeFlags::Int16:
1125 case NeonTypeFlags::Poly16:
1126 return shift ? 15 : (4 << IsQuad) - 1;
1127 case NeonTypeFlags::Int32:
1128 return shift ? 31 : (2 << IsQuad) - 1;
1129 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001130 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001131 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001132 case NeonTypeFlags::Poly128:
1133 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001134 case NeonTypeFlags::Float16:
1135 assert(!shift && "cannot shift float types!");
1136 return (4 << IsQuad) - 1;
1137 case NeonTypeFlags::Float32:
1138 assert(!shift && "cannot shift float types!");
1139 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001140 case NeonTypeFlags::Float64:
1141 assert(!shift && "cannot shift float types!");
1142 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001143 }
David Blaikie8a40f702012-01-17 06:56:22 +00001144 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001145}
1146
Bob Wilsone4d77232011-11-08 05:04:11 +00001147/// getNeonEltType - Return the QualType corresponding to the elements of
1148/// the vector type specified by the NeonTypeFlags. This is used to check
1149/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001150static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001151 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001152 switch (Flags.getEltType()) {
1153 case NeonTypeFlags::Int8:
1154 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1155 case NeonTypeFlags::Int16:
1156 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1157 case NeonTypeFlags::Int32:
1158 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1159 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001160 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001161 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1162 else
1163 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1164 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001165 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001166 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001167 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001168 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001169 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001170 if (IsInt64Long)
1171 return Context.UnsignedLongTy;
1172 else
1173 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001174 case NeonTypeFlags::Poly128:
1175 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001176 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001177 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001178 case NeonTypeFlags::Float32:
1179 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001180 case NeonTypeFlags::Float64:
1181 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001182 }
David Blaikie8a40f702012-01-17 06:56:22 +00001183 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001184}
1185
Tim Northover12670412014-02-19 10:37:05 +00001186bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001187 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001188 uint64_t mask = 0;
1189 unsigned TV = 0;
1190 int PtrArgNum = -1;
1191 bool HasConstPtr = false;
1192 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001193#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001194#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001195#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001196 }
1197
1198 // For NEON intrinsics which are overloaded on vector element type, validate
1199 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001200 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001201 if (mask) {
1202 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1203 return true;
1204
1205 TV = Result.getLimitedValue(64);
1206 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1207 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001208 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001209 }
1210
1211 if (PtrArgNum >= 0) {
1212 // Check that pointer arguments have the specified type.
1213 Expr *Arg = TheCall->getArg(PtrArgNum);
1214 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1215 Arg = ICE->getSubExpr();
1216 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1217 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001218
Tim Northovera2ee4332014-03-29 15:09:45 +00001219 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +00001220 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +00001221 bool IsInt64Long =
1222 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1223 QualType EltTy =
1224 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001225 if (HasConstPtr)
1226 EltTy = EltTy.withConst();
1227 QualType LHSTy = Context.getPointerType(EltTy);
1228 AssignConvertType ConvTy;
1229 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1230 if (RHS.isInvalid())
1231 return true;
1232 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1233 RHS.get(), AA_Assigning))
1234 return true;
1235 }
1236
1237 // For NEON intrinsics which take an immediate value as part of the
1238 // instruction, range check them here.
1239 unsigned i = 0, l = 0, u = 0;
1240 switch (BuiltinID) {
1241 default:
1242 return false;
Tim Northover12670412014-02-19 10:37:05 +00001243#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001244#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001245#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001246 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001247
Richard Sandiford28940af2014-04-16 08:47:51 +00001248 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001249}
1250
Tim Northovera2ee4332014-03-29 15:09:45 +00001251bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1252 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001253 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001254 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001255 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001256 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001257 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001258 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1259 BuiltinID == AArch64::BI__builtin_arm_strex ||
1260 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001261 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001262 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001263 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1264 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1265 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001266
1267 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1268
1269 // Ensure that we have the proper number of arguments.
1270 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1271 return true;
1272
1273 // Inspect the pointer argument of the atomic builtin. This should always be
1274 // a pointer type, whose element is an integral scalar or pointer type.
1275 // Because it is a pointer type, we don't have to worry about any implicit
1276 // casts here.
1277 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1278 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1279 if (PointerArgRes.isInvalid())
1280 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001281 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001282
1283 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1284 if (!pointerType) {
1285 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1286 << PointerArg->getType() << PointerArg->getSourceRange();
1287 return true;
1288 }
1289
1290 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1291 // task is to insert the appropriate casts into the AST. First work out just
1292 // what the appropriate type is.
1293 QualType ValType = pointerType->getPointeeType();
1294 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1295 if (IsLdrex)
1296 AddrType.addConst();
1297
1298 // Issue a warning if the cast is dodgy.
1299 CastKind CastNeeded = CK_NoOp;
1300 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1301 CastNeeded = CK_BitCast;
1302 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1303 << PointerArg->getType()
1304 << Context.getPointerType(AddrType)
1305 << AA_Passing << PointerArg->getSourceRange();
1306 }
1307
1308 // Finally, do the cast and replace the argument with the corrected version.
1309 AddrType = Context.getPointerType(AddrType);
1310 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1311 if (PointerArgRes.isInvalid())
1312 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001313 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001314
1315 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1316
1317 // In general, we allow ints, floats and pointers to be loaded and stored.
1318 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1319 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1320 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1321 << PointerArg->getType() << PointerArg->getSourceRange();
1322 return true;
1323 }
1324
1325 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001326 if (Context.getTypeSize(ValType) > MaxWidth) {
1327 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001328 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1329 << PointerArg->getType() << PointerArg->getSourceRange();
1330 return true;
1331 }
1332
1333 switch (ValType.getObjCLifetime()) {
1334 case Qualifiers::OCL_None:
1335 case Qualifiers::OCL_ExplicitNone:
1336 // okay
1337 break;
1338
1339 case Qualifiers::OCL_Weak:
1340 case Qualifiers::OCL_Strong:
1341 case Qualifiers::OCL_Autoreleasing:
1342 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1343 << ValType << PointerArg->getSourceRange();
1344 return true;
1345 }
1346
Tim Northover6aacd492013-07-16 09:47:53 +00001347 if (IsLdrex) {
1348 TheCall->setType(ValType);
1349 return false;
1350 }
1351
1352 // Initialize the argument to be stored.
1353 ExprResult ValArg = TheCall->getArg(0);
1354 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1355 Context, ValType, /*consume*/ false);
1356 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1357 if (ValArg.isInvalid())
1358 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001359 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001360
1361 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1362 // but the custom checker bypasses all default analysis.
1363 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001364 return false;
1365}
1366
Nate Begeman4904e322010-06-08 02:47:44 +00001367bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +00001368 llvm::APSInt Result;
1369
Tim Northover6aacd492013-07-16 09:47:53 +00001370 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001371 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1372 BuiltinID == ARM::BI__builtin_arm_strex ||
1373 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001374 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001375 }
1376
Yi Kong26d104a2014-08-13 19:18:14 +00001377 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1378 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1379 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1380 }
1381
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001382 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1383 BuiltinID == ARM::BI__builtin_arm_wsr64)
1384 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1385
1386 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1387 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1388 BuiltinID == ARM::BI__builtin_arm_wsr ||
1389 BuiltinID == ARM::BI__builtin_arm_wsrp)
1390 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1391
Tim Northover12670412014-02-19 10:37:05 +00001392 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1393 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001394
Yi Kong4efadfb2014-07-03 16:01:25 +00001395 // For intrinsics which take an immediate value as part of the instruction,
1396 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001397 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001398 switch (BuiltinID) {
1399 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001400 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1401 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001402 case ARM::BI__builtin_arm_vcvtr_f:
1403 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001404 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001405 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001406 case ARM::BI__builtin_arm_isb:
1407 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001408 }
Nate Begemand773fe62010-06-13 04:47:52 +00001409
Nate Begemanf568b072010-08-03 21:32:34 +00001410 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001411 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001412}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001413
Tim Northover573cbee2014-05-24 12:52:07 +00001414bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001415 CallExpr *TheCall) {
1416 llvm::APSInt Result;
1417
Tim Northover573cbee2014-05-24 12:52:07 +00001418 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001419 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1420 BuiltinID == AArch64::BI__builtin_arm_strex ||
1421 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001422 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1423 }
1424
Yi Konga5548432014-08-13 19:18:20 +00001425 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1426 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1427 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1428 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1429 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1430 }
1431
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001432 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1433 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001434 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001435
1436 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1437 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1438 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1439 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1440 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1441
Tim Northovera2ee4332014-03-29 15:09:45 +00001442 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1443 return true;
1444
Yi Kong19a29ac2014-07-17 10:52:06 +00001445 // For intrinsics which take an immediate value as part of the instruction,
1446 // range check them here.
1447 unsigned i = 0, l = 0, u = 0;
1448 switch (BuiltinID) {
1449 default: return false;
1450 case AArch64::BI__builtin_arm_dmb:
1451 case AArch64::BI__builtin_arm_dsb:
1452 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1453 }
1454
Yi Kong19a29ac2014-07-17 10:52:06 +00001455 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001456}
1457
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001458// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1459// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1460// ordering for DSP is unspecified. MSA is ordered by the data format used
1461// by the underlying instruction i.e., df/m, df/n and then by size.
1462//
1463// FIXME: The size tests here should instead be tablegen'd along with the
1464// definitions from include/clang/Basic/BuiltinsMips.def.
1465// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1466// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001467bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001468 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001469 switch (BuiltinID) {
1470 default: return false;
1471 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1472 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001473 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1474 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1475 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1476 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1477 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001478 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1479 // df/m field.
1480 // These intrinsics take an unsigned 3 bit immediate.
1481 case Mips::BI__builtin_msa_bclri_b:
1482 case Mips::BI__builtin_msa_bnegi_b:
1483 case Mips::BI__builtin_msa_bseti_b:
1484 case Mips::BI__builtin_msa_sat_s_b:
1485 case Mips::BI__builtin_msa_sat_u_b:
1486 case Mips::BI__builtin_msa_slli_b:
1487 case Mips::BI__builtin_msa_srai_b:
1488 case Mips::BI__builtin_msa_srari_b:
1489 case Mips::BI__builtin_msa_srli_b:
1490 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1491 case Mips::BI__builtin_msa_binsli_b:
1492 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1493 // These intrinsics take an unsigned 4 bit immediate.
1494 case Mips::BI__builtin_msa_bclri_h:
1495 case Mips::BI__builtin_msa_bnegi_h:
1496 case Mips::BI__builtin_msa_bseti_h:
1497 case Mips::BI__builtin_msa_sat_s_h:
1498 case Mips::BI__builtin_msa_sat_u_h:
1499 case Mips::BI__builtin_msa_slli_h:
1500 case Mips::BI__builtin_msa_srai_h:
1501 case Mips::BI__builtin_msa_srari_h:
1502 case Mips::BI__builtin_msa_srli_h:
1503 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1504 case Mips::BI__builtin_msa_binsli_h:
1505 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1506 // These intrinsics take an unsigned 5 bit immedate.
1507 // The first block of intrinsics actually have an unsigned 5 bit field,
1508 // not a df/n field.
1509 case Mips::BI__builtin_msa_clei_u_b:
1510 case Mips::BI__builtin_msa_clei_u_h:
1511 case Mips::BI__builtin_msa_clei_u_w:
1512 case Mips::BI__builtin_msa_clei_u_d:
1513 case Mips::BI__builtin_msa_clti_u_b:
1514 case Mips::BI__builtin_msa_clti_u_h:
1515 case Mips::BI__builtin_msa_clti_u_w:
1516 case Mips::BI__builtin_msa_clti_u_d:
1517 case Mips::BI__builtin_msa_maxi_u_b:
1518 case Mips::BI__builtin_msa_maxi_u_h:
1519 case Mips::BI__builtin_msa_maxi_u_w:
1520 case Mips::BI__builtin_msa_maxi_u_d:
1521 case Mips::BI__builtin_msa_mini_u_b:
1522 case Mips::BI__builtin_msa_mini_u_h:
1523 case Mips::BI__builtin_msa_mini_u_w:
1524 case Mips::BI__builtin_msa_mini_u_d:
1525 case Mips::BI__builtin_msa_addvi_b:
1526 case Mips::BI__builtin_msa_addvi_h:
1527 case Mips::BI__builtin_msa_addvi_w:
1528 case Mips::BI__builtin_msa_addvi_d:
1529 case Mips::BI__builtin_msa_bclri_w:
1530 case Mips::BI__builtin_msa_bnegi_w:
1531 case Mips::BI__builtin_msa_bseti_w:
1532 case Mips::BI__builtin_msa_sat_s_w:
1533 case Mips::BI__builtin_msa_sat_u_w:
1534 case Mips::BI__builtin_msa_slli_w:
1535 case Mips::BI__builtin_msa_srai_w:
1536 case Mips::BI__builtin_msa_srari_w:
1537 case Mips::BI__builtin_msa_srli_w:
1538 case Mips::BI__builtin_msa_srlri_w:
1539 case Mips::BI__builtin_msa_subvi_b:
1540 case Mips::BI__builtin_msa_subvi_h:
1541 case Mips::BI__builtin_msa_subvi_w:
1542 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1543 case Mips::BI__builtin_msa_binsli_w:
1544 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1545 // These intrinsics take an unsigned 6 bit immediate.
1546 case Mips::BI__builtin_msa_bclri_d:
1547 case Mips::BI__builtin_msa_bnegi_d:
1548 case Mips::BI__builtin_msa_bseti_d:
1549 case Mips::BI__builtin_msa_sat_s_d:
1550 case Mips::BI__builtin_msa_sat_u_d:
1551 case Mips::BI__builtin_msa_slli_d:
1552 case Mips::BI__builtin_msa_srai_d:
1553 case Mips::BI__builtin_msa_srari_d:
1554 case Mips::BI__builtin_msa_srli_d:
1555 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1556 case Mips::BI__builtin_msa_binsli_d:
1557 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1558 // These intrinsics take a signed 5 bit immediate.
1559 case Mips::BI__builtin_msa_ceqi_b:
1560 case Mips::BI__builtin_msa_ceqi_h:
1561 case Mips::BI__builtin_msa_ceqi_w:
1562 case Mips::BI__builtin_msa_ceqi_d:
1563 case Mips::BI__builtin_msa_clti_s_b:
1564 case Mips::BI__builtin_msa_clti_s_h:
1565 case Mips::BI__builtin_msa_clti_s_w:
1566 case Mips::BI__builtin_msa_clti_s_d:
1567 case Mips::BI__builtin_msa_clei_s_b:
1568 case Mips::BI__builtin_msa_clei_s_h:
1569 case Mips::BI__builtin_msa_clei_s_w:
1570 case Mips::BI__builtin_msa_clei_s_d:
1571 case Mips::BI__builtin_msa_maxi_s_b:
1572 case Mips::BI__builtin_msa_maxi_s_h:
1573 case Mips::BI__builtin_msa_maxi_s_w:
1574 case Mips::BI__builtin_msa_maxi_s_d:
1575 case Mips::BI__builtin_msa_mini_s_b:
1576 case Mips::BI__builtin_msa_mini_s_h:
1577 case Mips::BI__builtin_msa_mini_s_w:
1578 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1579 // These intrinsics take an unsigned 8 bit immediate.
1580 case Mips::BI__builtin_msa_andi_b:
1581 case Mips::BI__builtin_msa_nori_b:
1582 case Mips::BI__builtin_msa_ori_b:
1583 case Mips::BI__builtin_msa_shf_b:
1584 case Mips::BI__builtin_msa_shf_h:
1585 case Mips::BI__builtin_msa_shf_w:
1586 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1587 case Mips::BI__builtin_msa_bseli_b:
1588 case Mips::BI__builtin_msa_bmnzi_b:
1589 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1590 // df/n format
1591 // These intrinsics take an unsigned 4 bit immediate.
1592 case Mips::BI__builtin_msa_copy_s_b:
1593 case Mips::BI__builtin_msa_copy_u_b:
1594 case Mips::BI__builtin_msa_insve_b:
1595 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1596 case Mips::BI__builtin_msa_sld_b:
1597 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1598 // These intrinsics take an unsigned 3 bit immediate.
1599 case Mips::BI__builtin_msa_copy_s_h:
1600 case Mips::BI__builtin_msa_copy_u_h:
1601 case Mips::BI__builtin_msa_insve_h:
1602 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1603 case Mips::BI__builtin_msa_sld_h:
1604 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1605 // These intrinsics take an unsigned 2 bit immediate.
1606 case Mips::BI__builtin_msa_copy_s_w:
1607 case Mips::BI__builtin_msa_copy_u_w:
1608 case Mips::BI__builtin_msa_insve_w:
1609 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1610 case Mips::BI__builtin_msa_sld_w:
1611 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1612 // These intrinsics take an unsigned 1 bit immediate.
1613 case Mips::BI__builtin_msa_copy_s_d:
1614 case Mips::BI__builtin_msa_copy_u_d:
1615 case Mips::BI__builtin_msa_insve_d:
1616 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1617 case Mips::BI__builtin_msa_sld_d:
1618 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1619 // Memory offsets and immediate loads.
1620 // These intrinsics take a signed 10 bit immediate.
1621 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 127; break;
1622 case Mips::BI__builtin_msa_ldi_h:
1623 case Mips::BI__builtin_msa_ldi_w:
1624 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1625 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1626 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1627 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1628 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1629 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1630 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1631 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1632 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001633 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001634
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001635 if (!m)
1636 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1637
1638 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1639 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001640}
1641
Kit Bartone50adcb2015-03-30 19:40:59 +00001642bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1643 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001644 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1645 BuiltinID == PPC::BI__builtin_divdeu ||
1646 BuiltinID == PPC::BI__builtin_bpermd;
1647 bool IsTarget64Bit = Context.getTargetInfo()
1648 .getTypeWidth(Context
1649 .getTargetInfo()
1650 .getIntPtrType()) == 64;
1651 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1652 BuiltinID == PPC::BI__builtin_divweu ||
1653 BuiltinID == PPC::BI__builtin_divde ||
1654 BuiltinID == PPC::BI__builtin_divdeu;
1655
1656 if (Is64BitBltin && !IsTarget64Bit)
1657 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1658 << TheCall->getSourceRange();
1659
1660 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1661 (BuiltinID == PPC::BI__builtin_bpermd &&
1662 !Context.getTargetInfo().hasFeature("bpermd")))
1663 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1664 << TheCall->getSourceRange();
1665
Kit Bartone50adcb2015-03-30 19:40:59 +00001666 switch (BuiltinID) {
1667 default: return false;
1668 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1669 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1670 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1671 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1672 case PPC::BI__builtin_tbegin:
1673 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1674 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1675 case PPC::BI__builtin_tabortwc:
1676 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1677 case PPC::BI__builtin_tabortwci:
1678 case PPC::BI__builtin_tabortdci:
1679 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1680 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1681 }
1682 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1683}
1684
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001685bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1686 CallExpr *TheCall) {
1687 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1688 Expr *Arg = TheCall->getArg(0);
1689 llvm::APSInt AbortCode(32);
1690 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1691 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1692 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1693 << Arg->getSourceRange();
1694 }
1695
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001696 // For intrinsics which take an immediate value as part of the instruction,
1697 // range check them here.
1698 unsigned i = 0, l = 0, u = 0;
1699 switch (BuiltinID) {
1700 default: return false;
1701 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1702 case SystemZ::BI__builtin_s390_verimb:
1703 case SystemZ::BI__builtin_s390_verimh:
1704 case SystemZ::BI__builtin_s390_verimf:
1705 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1706 case SystemZ::BI__builtin_s390_vfaeb:
1707 case SystemZ::BI__builtin_s390_vfaeh:
1708 case SystemZ::BI__builtin_s390_vfaef:
1709 case SystemZ::BI__builtin_s390_vfaebs:
1710 case SystemZ::BI__builtin_s390_vfaehs:
1711 case SystemZ::BI__builtin_s390_vfaefs:
1712 case SystemZ::BI__builtin_s390_vfaezb:
1713 case SystemZ::BI__builtin_s390_vfaezh:
1714 case SystemZ::BI__builtin_s390_vfaezf:
1715 case SystemZ::BI__builtin_s390_vfaezbs:
1716 case SystemZ::BI__builtin_s390_vfaezhs:
1717 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1718 case SystemZ::BI__builtin_s390_vfidb:
1719 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1720 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1721 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1722 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1723 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1724 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1725 case SystemZ::BI__builtin_s390_vstrcb:
1726 case SystemZ::BI__builtin_s390_vstrch:
1727 case SystemZ::BI__builtin_s390_vstrcf:
1728 case SystemZ::BI__builtin_s390_vstrczb:
1729 case SystemZ::BI__builtin_s390_vstrczh:
1730 case SystemZ::BI__builtin_s390_vstrczf:
1731 case SystemZ::BI__builtin_s390_vstrcbs:
1732 case SystemZ::BI__builtin_s390_vstrchs:
1733 case SystemZ::BI__builtin_s390_vstrcfs:
1734 case SystemZ::BI__builtin_s390_vstrczbs:
1735 case SystemZ::BI__builtin_s390_vstrczhs:
1736 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1737 }
1738 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001739}
1740
Craig Topper5ba2c502015-11-07 08:08:31 +00001741/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1742/// This checks that the target supports __builtin_cpu_supports and
1743/// that the string argument is constant and valid.
1744static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1745 Expr *Arg = TheCall->getArg(0);
1746
1747 // Check if the argument is a string literal.
1748 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1749 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1750 << Arg->getSourceRange();
1751
1752 // Check the contents of the string.
1753 StringRef Feature =
1754 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1755 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1756 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1757 << Arg->getSourceRange();
1758 return false;
1759}
1760
Craig Toppera7e253e2016-09-23 04:48:31 +00001761// Check if the rounding mode is legal.
1762bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1763 // Indicates if this instruction has rounding control or just SAE.
1764 bool HasRC = false;
1765
1766 unsigned ArgNum = 0;
1767 switch (BuiltinID) {
1768 default:
1769 return false;
1770 case X86::BI__builtin_ia32_vcvttsd2si32:
1771 case X86::BI__builtin_ia32_vcvttsd2si64:
1772 case X86::BI__builtin_ia32_vcvttsd2usi32:
1773 case X86::BI__builtin_ia32_vcvttsd2usi64:
1774 case X86::BI__builtin_ia32_vcvttss2si32:
1775 case X86::BI__builtin_ia32_vcvttss2si64:
1776 case X86::BI__builtin_ia32_vcvttss2usi32:
1777 case X86::BI__builtin_ia32_vcvttss2usi64:
1778 ArgNum = 1;
1779 break;
1780 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1781 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1782 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1783 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1784 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1785 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1786 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1787 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1788 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1789 case X86::BI__builtin_ia32_exp2pd_mask:
1790 case X86::BI__builtin_ia32_exp2ps_mask:
1791 case X86::BI__builtin_ia32_getexppd512_mask:
1792 case X86::BI__builtin_ia32_getexpps512_mask:
1793 case X86::BI__builtin_ia32_rcp28pd_mask:
1794 case X86::BI__builtin_ia32_rcp28ps_mask:
1795 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1796 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1797 case X86::BI__builtin_ia32_vcomisd:
1798 case X86::BI__builtin_ia32_vcomiss:
1799 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1800 ArgNum = 3;
1801 break;
1802 case X86::BI__builtin_ia32_cmppd512_mask:
1803 case X86::BI__builtin_ia32_cmpps512_mask:
1804 case X86::BI__builtin_ia32_cmpsd_mask:
1805 case X86::BI__builtin_ia32_cmpss_mask:
1806 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1807 case X86::BI__builtin_ia32_getexpss128_round_mask:
1808 case X86::BI__builtin_ia32_rcp28sd_round_mask:
1809 case X86::BI__builtin_ia32_rcp28ss_round_mask:
1810 case X86::BI__builtin_ia32_reducepd512_mask:
1811 case X86::BI__builtin_ia32_reduceps512_mask:
1812 case X86::BI__builtin_ia32_rndscalepd_mask:
1813 case X86::BI__builtin_ia32_rndscaleps_mask:
1814 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1815 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1816 ArgNum = 4;
1817 break;
1818 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001819 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001820 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001821 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001822 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001823 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001824 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001825 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001826 case X86::BI__builtin_ia32_rangepd512_mask:
1827 case X86::BI__builtin_ia32_rangeps512_mask:
1828 case X86::BI__builtin_ia32_rangesd128_round_mask:
1829 case X86::BI__builtin_ia32_rangess128_round_mask:
1830 case X86::BI__builtin_ia32_reducesd_mask:
1831 case X86::BI__builtin_ia32_reducess_mask:
1832 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1833 case X86::BI__builtin_ia32_rndscaless_round_mask:
1834 ArgNum = 5;
1835 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00001836 case X86::BI__builtin_ia32_vcvtsd2si64:
1837 case X86::BI__builtin_ia32_vcvtsd2si32:
1838 case X86::BI__builtin_ia32_vcvtsd2usi32:
1839 case X86::BI__builtin_ia32_vcvtsd2usi64:
1840 case X86::BI__builtin_ia32_vcvtss2si32:
1841 case X86::BI__builtin_ia32_vcvtss2si64:
1842 case X86::BI__builtin_ia32_vcvtss2usi32:
1843 case X86::BI__builtin_ia32_vcvtss2usi64:
1844 ArgNum = 1;
1845 HasRC = true;
1846 break;
1847 case X86::BI__builtin_ia32_cvtusi2sd64:
1848 case X86::BI__builtin_ia32_cvtusi2ss32:
1849 case X86::BI__builtin_ia32_cvtusi2ss64:
1850 ArgNum = 2;
1851 HasRC = true;
1852 break;
1853 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1854 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1855 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1856 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1857 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1858 case X86::BI__builtin_ia32_cvtps2qq512_mask:
1859 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1860 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1861 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1862 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1863 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
1864 ArgNum = 3;
1865 HasRC = true;
1866 break;
1867 case X86::BI__builtin_ia32_addpd512_mask:
1868 case X86::BI__builtin_ia32_addps512_mask:
1869 case X86::BI__builtin_ia32_divpd512_mask:
1870 case X86::BI__builtin_ia32_divps512_mask:
1871 case X86::BI__builtin_ia32_mulpd512_mask:
1872 case X86::BI__builtin_ia32_mulps512_mask:
1873 case X86::BI__builtin_ia32_subpd512_mask:
1874 case X86::BI__builtin_ia32_subps512_mask:
1875 case X86::BI__builtin_ia32_addss_round_mask:
1876 case X86::BI__builtin_ia32_addsd_round_mask:
1877 case X86::BI__builtin_ia32_divss_round_mask:
1878 case X86::BI__builtin_ia32_divsd_round_mask:
1879 case X86::BI__builtin_ia32_mulss_round_mask:
1880 case X86::BI__builtin_ia32_mulsd_round_mask:
1881 case X86::BI__builtin_ia32_subss_round_mask:
1882 case X86::BI__builtin_ia32_subsd_round_mask:
1883 case X86::BI__builtin_ia32_scalefpd512_mask:
1884 case X86::BI__builtin_ia32_scalefps512_mask:
1885 case X86::BI__builtin_ia32_scalefsd_round_mask:
1886 case X86::BI__builtin_ia32_scalefss_round_mask:
1887 case X86::BI__builtin_ia32_getmantpd512_mask:
1888 case X86::BI__builtin_ia32_getmantps512_mask:
1889 case X86::BI__builtin_ia32_vfmaddpd512_mask:
1890 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1891 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1892 case X86::BI__builtin_ia32_vfmaddps512_mask:
1893 case X86::BI__builtin_ia32_vfmaddps512_mask3:
1894 case X86::BI__builtin_ia32_vfmaddps512_maskz:
1895 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1896 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1897 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1898 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1899 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1900 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1901 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1902 case X86::BI__builtin_ia32_vfmsubps512_mask3:
1903 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1904 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1905 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1906 case X86::BI__builtin_ia32_vfnmaddps512_mask:
1907 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1908 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1909 case X86::BI__builtin_ia32_vfnmsubps512_mask:
1910 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1911 case X86::BI__builtin_ia32_vfmaddsd3_mask:
1912 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1913 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1914 case X86::BI__builtin_ia32_vfmaddss3_mask:
1915 case X86::BI__builtin_ia32_vfmaddss3_maskz:
1916 case X86::BI__builtin_ia32_vfmaddss3_mask3:
1917 ArgNum = 4;
1918 HasRC = true;
1919 break;
1920 case X86::BI__builtin_ia32_getmantsd_round_mask:
1921 case X86::BI__builtin_ia32_getmantss_round_mask:
1922 ArgNum = 5;
1923 HasRC = true;
1924 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00001925 }
1926
1927 llvm::APSInt Result;
1928
1929 // We can't check the value of a dependent argument.
1930 Expr *Arg = TheCall->getArg(ArgNum);
1931 if (Arg->isTypeDependent() || Arg->isValueDependent())
1932 return false;
1933
1934 // Check constant-ness first.
1935 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1936 return true;
1937
1938 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1939 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1940 // combined with ROUND_NO_EXC.
1941 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1942 Result == 8/*ROUND_NO_EXC*/ ||
1943 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1944 return false;
1945
1946 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1947 << Arg->getSourceRange();
1948}
1949
Craig Topperf0ddc892016-09-23 04:48:27 +00001950bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1951 if (BuiltinID == X86::BI__builtin_cpu_supports)
1952 return SemaBuiltinCpuSupports(*this, TheCall);
1953
1954 if (BuiltinID == X86::BI__builtin_ms_va_start)
1955 return SemaBuiltinMSVAStart(TheCall);
1956
Craig Toppera7e253e2016-09-23 04:48:31 +00001957 // If the intrinsic has rounding or SAE make sure its valid.
1958 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
1959 return true;
1960
Craig Topperf0ddc892016-09-23 04:48:27 +00001961 // For intrinsics which take an immediate value as part of the instruction,
1962 // range check them here.
1963 int i = 0, l = 0, u = 0;
1964 switch (BuiltinID) {
1965 default:
1966 return false;
Craig Topper39c87102016-05-18 03:18:12 +00001967 case X86::BI__builtin_ia32_extractf64x4_mask:
1968 case X86::BI__builtin_ia32_extracti64x4_mask:
1969 case X86::BI__builtin_ia32_extractf32x8_mask:
1970 case X86::BI__builtin_ia32_extracti32x8_mask:
1971 case X86::BI__builtin_ia32_extractf64x2_256_mask:
1972 case X86::BI__builtin_ia32_extracti64x2_256_mask:
1973 case X86::BI__builtin_ia32_extractf32x4_256_mask:
1974 case X86::BI__builtin_ia32_extracti32x4_256_mask:
1975 i = 1; l = 0; u = 1;
1976 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00001977 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00001978 case X86::BI__builtin_ia32_extractf32x4_mask:
1979 case X86::BI__builtin_ia32_extracti32x4_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001980 case X86::BI__builtin_ia32_extractf64x2_512_mask:
1981 case X86::BI__builtin_ia32_extracti64x2_512_mask:
1982 i = 1; l = 0; u = 3;
1983 break;
1984 case X86::BI__builtin_ia32_insertf32x8_mask:
1985 case X86::BI__builtin_ia32_inserti32x8_mask:
1986 case X86::BI__builtin_ia32_insertf64x4_mask:
1987 case X86::BI__builtin_ia32_inserti64x4_mask:
1988 case X86::BI__builtin_ia32_insertf64x2_256_mask:
1989 case X86::BI__builtin_ia32_inserti64x2_256_mask:
1990 case X86::BI__builtin_ia32_insertf32x4_256_mask:
1991 case X86::BI__builtin_ia32_inserti32x4_256_mask:
1992 i = 2; l = 0; u = 1;
Richard Trieucc3949d2016-02-18 22:34:54 +00001993 break;
1994 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00001995 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
1996 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
1997 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
1998 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001999 case X86::BI__builtin_ia32_insertf64x2_512_mask:
2000 case X86::BI__builtin_ia32_inserti64x2_512_mask:
2001 case X86::BI__builtin_ia32_insertf32x4_mask:
2002 case X86::BI__builtin_ia32_inserti32x4_mask:
2003 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002004 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002005 case X86::BI__builtin_ia32_vpermil2pd:
2006 case X86::BI__builtin_ia32_vpermil2pd256:
2007 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002008 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002009 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002010 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002011 case X86::BI__builtin_ia32_cmpb128_mask:
2012 case X86::BI__builtin_ia32_cmpw128_mask:
2013 case X86::BI__builtin_ia32_cmpd128_mask:
2014 case X86::BI__builtin_ia32_cmpq128_mask:
2015 case X86::BI__builtin_ia32_cmpb256_mask:
2016 case X86::BI__builtin_ia32_cmpw256_mask:
2017 case X86::BI__builtin_ia32_cmpd256_mask:
2018 case X86::BI__builtin_ia32_cmpq256_mask:
2019 case X86::BI__builtin_ia32_cmpb512_mask:
2020 case X86::BI__builtin_ia32_cmpw512_mask:
2021 case X86::BI__builtin_ia32_cmpd512_mask:
2022 case X86::BI__builtin_ia32_cmpq512_mask:
2023 case X86::BI__builtin_ia32_ucmpb128_mask:
2024 case X86::BI__builtin_ia32_ucmpw128_mask:
2025 case X86::BI__builtin_ia32_ucmpd128_mask:
2026 case X86::BI__builtin_ia32_ucmpq128_mask:
2027 case X86::BI__builtin_ia32_ucmpb256_mask:
2028 case X86::BI__builtin_ia32_ucmpw256_mask:
2029 case X86::BI__builtin_ia32_ucmpd256_mask:
2030 case X86::BI__builtin_ia32_ucmpq256_mask:
2031 case X86::BI__builtin_ia32_ucmpb512_mask:
2032 case X86::BI__builtin_ia32_ucmpw512_mask:
2033 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002034 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002035 case X86::BI__builtin_ia32_vpcomub:
2036 case X86::BI__builtin_ia32_vpcomuw:
2037 case X86::BI__builtin_ia32_vpcomud:
2038 case X86::BI__builtin_ia32_vpcomuq:
2039 case X86::BI__builtin_ia32_vpcomb:
2040 case X86::BI__builtin_ia32_vpcomw:
2041 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002042 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00002043 i = 2; l = 0; u = 7;
2044 break;
2045 case X86::BI__builtin_ia32_roundps:
2046 case X86::BI__builtin_ia32_roundpd:
2047 case X86::BI__builtin_ia32_roundps256:
2048 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002049 i = 1; l = 0; u = 15;
2050 break;
2051 case X86::BI__builtin_ia32_roundss:
2052 case X86::BI__builtin_ia32_roundsd:
2053 case X86::BI__builtin_ia32_rangepd128_mask:
2054 case X86::BI__builtin_ia32_rangepd256_mask:
2055 case X86::BI__builtin_ia32_rangepd512_mask:
2056 case X86::BI__builtin_ia32_rangeps128_mask:
2057 case X86::BI__builtin_ia32_rangeps256_mask:
2058 case X86::BI__builtin_ia32_rangeps512_mask:
2059 case X86::BI__builtin_ia32_getmantsd_round_mask:
2060 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002061 i = 2; l = 0; u = 15;
2062 break;
2063 case X86::BI__builtin_ia32_cmpps:
2064 case X86::BI__builtin_ia32_cmpss:
2065 case X86::BI__builtin_ia32_cmppd:
2066 case X86::BI__builtin_ia32_cmpsd:
2067 case X86::BI__builtin_ia32_cmpps256:
2068 case X86::BI__builtin_ia32_cmppd256:
2069 case X86::BI__builtin_ia32_cmpps128_mask:
2070 case X86::BI__builtin_ia32_cmppd128_mask:
2071 case X86::BI__builtin_ia32_cmpps256_mask:
2072 case X86::BI__builtin_ia32_cmppd256_mask:
2073 case X86::BI__builtin_ia32_cmpps512_mask:
2074 case X86::BI__builtin_ia32_cmppd512_mask:
2075 case X86::BI__builtin_ia32_cmpsd_mask:
2076 case X86::BI__builtin_ia32_cmpss_mask:
2077 i = 2; l = 0; u = 31;
2078 break;
2079 case X86::BI__builtin_ia32_xabort:
2080 i = 0; l = -128; u = 255;
2081 break;
2082 case X86::BI__builtin_ia32_pshufw:
2083 case X86::BI__builtin_ia32_aeskeygenassist128:
2084 i = 1; l = -128; u = 255;
2085 break;
2086 case X86::BI__builtin_ia32_vcvtps2ph:
2087 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper39c87102016-05-18 03:18:12 +00002088 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2089 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2090 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2091 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2092 case X86::BI__builtin_ia32_rndscaleps_mask:
2093 case X86::BI__builtin_ia32_rndscalepd_mask:
2094 case X86::BI__builtin_ia32_reducepd128_mask:
2095 case X86::BI__builtin_ia32_reducepd256_mask:
2096 case X86::BI__builtin_ia32_reducepd512_mask:
2097 case X86::BI__builtin_ia32_reduceps128_mask:
2098 case X86::BI__builtin_ia32_reduceps256_mask:
2099 case X86::BI__builtin_ia32_reduceps512_mask:
2100 case X86::BI__builtin_ia32_prold512_mask:
2101 case X86::BI__builtin_ia32_prolq512_mask:
2102 case X86::BI__builtin_ia32_prold128_mask:
2103 case X86::BI__builtin_ia32_prold256_mask:
2104 case X86::BI__builtin_ia32_prolq128_mask:
2105 case X86::BI__builtin_ia32_prolq256_mask:
2106 case X86::BI__builtin_ia32_prord128_mask:
2107 case X86::BI__builtin_ia32_prord256_mask:
2108 case X86::BI__builtin_ia32_prorq128_mask:
2109 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002110 case X86::BI__builtin_ia32_psllwi512_mask:
2111 case X86::BI__builtin_ia32_psllwi128_mask:
2112 case X86::BI__builtin_ia32_psllwi256_mask:
2113 case X86::BI__builtin_ia32_psrldi128_mask:
2114 case X86::BI__builtin_ia32_psrldi256_mask:
2115 case X86::BI__builtin_ia32_psrldi512_mask:
2116 case X86::BI__builtin_ia32_psrlqi128_mask:
2117 case X86::BI__builtin_ia32_psrlqi256_mask:
2118 case X86::BI__builtin_ia32_psrlqi512_mask:
2119 case X86::BI__builtin_ia32_psrawi512_mask:
2120 case X86::BI__builtin_ia32_psrawi128_mask:
2121 case X86::BI__builtin_ia32_psrawi256_mask:
2122 case X86::BI__builtin_ia32_psrlwi512_mask:
2123 case X86::BI__builtin_ia32_psrlwi128_mask:
2124 case X86::BI__builtin_ia32_psrlwi256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002125 case X86::BI__builtin_ia32_psradi128_mask:
2126 case X86::BI__builtin_ia32_psradi256_mask:
2127 case X86::BI__builtin_ia32_psradi512_mask:
2128 case X86::BI__builtin_ia32_psraqi128_mask:
2129 case X86::BI__builtin_ia32_psraqi256_mask:
2130 case X86::BI__builtin_ia32_psraqi512_mask:
2131 case X86::BI__builtin_ia32_pslldi128_mask:
2132 case X86::BI__builtin_ia32_pslldi256_mask:
2133 case X86::BI__builtin_ia32_pslldi512_mask:
2134 case X86::BI__builtin_ia32_psllqi128_mask:
2135 case X86::BI__builtin_ia32_psllqi256_mask:
2136 case X86::BI__builtin_ia32_psllqi512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002137 case X86::BI__builtin_ia32_fpclasspd128_mask:
2138 case X86::BI__builtin_ia32_fpclasspd256_mask:
2139 case X86::BI__builtin_ia32_fpclassps128_mask:
2140 case X86::BI__builtin_ia32_fpclassps256_mask:
2141 case X86::BI__builtin_ia32_fpclassps512_mask:
2142 case X86::BI__builtin_ia32_fpclasspd512_mask:
2143 case X86::BI__builtin_ia32_fpclasssd_mask:
2144 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002145 i = 1; l = 0; u = 255;
2146 break;
2147 case X86::BI__builtin_ia32_palignr:
2148 case X86::BI__builtin_ia32_insertps128:
2149 case X86::BI__builtin_ia32_dpps:
2150 case X86::BI__builtin_ia32_dppd:
2151 case X86::BI__builtin_ia32_dpps256:
2152 case X86::BI__builtin_ia32_mpsadbw128:
2153 case X86::BI__builtin_ia32_mpsadbw256:
2154 case X86::BI__builtin_ia32_pcmpistrm128:
2155 case X86::BI__builtin_ia32_pcmpistri128:
2156 case X86::BI__builtin_ia32_pcmpistria128:
2157 case X86::BI__builtin_ia32_pcmpistric128:
2158 case X86::BI__builtin_ia32_pcmpistrio128:
2159 case X86::BI__builtin_ia32_pcmpistris128:
2160 case X86::BI__builtin_ia32_pcmpistriz128:
2161 case X86::BI__builtin_ia32_pclmulqdq128:
2162 case X86::BI__builtin_ia32_vperm2f128_pd256:
2163 case X86::BI__builtin_ia32_vperm2f128_ps256:
2164 case X86::BI__builtin_ia32_vperm2f128_si256:
2165 case X86::BI__builtin_ia32_permti256:
2166 i = 2; l = -128; u = 255;
2167 break;
2168 case X86::BI__builtin_ia32_palignr128:
2169 case X86::BI__builtin_ia32_palignr256:
Craig Topper39c87102016-05-18 03:18:12 +00002170 case X86::BI__builtin_ia32_palignr512_mask:
2171 case X86::BI__builtin_ia32_alignq512_mask:
2172 case X86::BI__builtin_ia32_alignd512_mask:
2173 case X86::BI__builtin_ia32_alignd128_mask:
2174 case X86::BI__builtin_ia32_alignd256_mask:
2175 case X86::BI__builtin_ia32_alignq128_mask:
2176 case X86::BI__builtin_ia32_alignq256_mask:
2177 case X86::BI__builtin_ia32_vcomisd:
2178 case X86::BI__builtin_ia32_vcomiss:
2179 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2180 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2181 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2182 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002183 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2184 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2185 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2186 i = 2; l = 0; u = 255;
2187 break;
2188 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2189 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2190 case X86::BI__builtin_ia32_fixupimmps512_mask:
2191 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2192 case X86::BI__builtin_ia32_fixupimmsd_mask:
2193 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2194 case X86::BI__builtin_ia32_fixupimmss_mask:
2195 case X86::BI__builtin_ia32_fixupimmss_maskz:
2196 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2197 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2198 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2199 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2200 case X86::BI__builtin_ia32_fixupimmps128_mask:
2201 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2202 case X86::BI__builtin_ia32_fixupimmps256_mask:
2203 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2204 case X86::BI__builtin_ia32_pternlogd512_mask:
2205 case X86::BI__builtin_ia32_pternlogd512_maskz:
2206 case X86::BI__builtin_ia32_pternlogq512_mask:
2207 case X86::BI__builtin_ia32_pternlogq512_maskz:
2208 case X86::BI__builtin_ia32_pternlogd128_mask:
2209 case X86::BI__builtin_ia32_pternlogd128_maskz:
2210 case X86::BI__builtin_ia32_pternlogd256_mask:
2211 case X86::BI__builtin_ia32_pternlogd256_maskz:
2212 case X86::BI__builtin_ia32_pternlogq128_mask:
2213 case X86::BI__builtin_ia32_pternlogq128_maskz:
2214 case X86::BI__builtin_ia32_pternlogq256_mask:
2215 case X86::BI__builtin_ia32_pternlogq256_maskz:
2216 i = 3; l = 0; u = 255;
2217 break;
2218 case X86::BI__builtin_ia32_pcmpestrm128:
2219 case X86::BI__builtin_ia32_pcmpestri128:
2220 case X86::BI__builtin_ia32_pcmpestria128:
2221 case X86::BI__builtin_ia32_pcmpestric128:
2222 case X86::BI__builtin_ia32_pcmpestrio128:
2223 case X86::BI__builtin_ia32_pcmpestris128:
2224 case X86::BI__builtin_ia32_pcmpestriz128:
2225 i = 4; l = -128; u = 255;
2226 break;
2227 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2228 case X86::BI__builtin_ia32_rndscaless_round_mask:
2229 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002230 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002231 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002232 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002233}
2234
Richard Smith55ce3522012-06-25 20:30:08 +00002235/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2236/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2237/// Returns true when the format fits the function and the FormatStringInfo has
2238/// been populated.
2239bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2240 FormatStringInfo *FSI) {
2241 FSI->HasVAListArg = Format->getFirstArg() == 0;
2242 FSI->FormatIdx = Format->getFormatIdx() - 1;
2243 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002244
Richard Smith55ce3522012-06-25 20:30:08 +00002245 // The way the format attribute works in GCC, the implicit this argument
2246 // of member functions is counted. However, it doesn't appear in our own
2247 // lists, so decrement format_idx in that case.
2248 if (IsCXXMember) {
2249 if(FSI->FormatIdx == 0)
2250 return false;
2251 --FSI->FormatIdx;
2252 if (FSI->FirstDataArg != 0)
2253 --FSI->FirstDataArg;
2254 }
2255 return true;
2256}
Mike Stump11289f42009-09-09 15:08:12 +00002257
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002258/// Checks if a the given expression evaluates to null.
2259///
2260/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002261static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002262 // If the expression has non-null type, it doesn't evaluate to null.
2263 if (auto nullability
2264 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2265 if (*nullability == NullabilityKind::NonNull)
2266 return false;
2267 }
2268
Ted Kremeneka146db32014-01-17 06:24:47 +00002269 // As a special case, transparent unions initialized with zero are
2270 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002271 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002272 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2273 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002274 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002275 if (const InitListExpr *ILE =
2276 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002277 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002278 }
2279
2280 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002281 return (!Expr->isValueDependent() &&
2282 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2283 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002284}
2285
2286static void CheckNonNullArgument(Sema &S,
2287 const Expr *ArgExpr,
2288 SourceLocation CallSiteLoc) {
2289 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002290 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2291 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002292}
2293
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002294bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2295 FormatStringInfo FSI;
2296 if ((GetFormatStringType(Format) == FST_NSString) &&
2297 getFormatStringInfo(Format, false, &FSI)) {
2298 Idx = FSI.FormatIdx;
2299 return true;
2300 }
2301 return false;
2302}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002303/// \brief Diagnose use of %s directive in an NSString which is being passed
2304/// as formatting string to formatting method.
2305static void
2306DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2307 const NamedDecl *FDecl,
2308 Expr **Args,
2309 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002310 unsigned Idx = 0;
2311 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002312 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2313 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002314 Idx = 2;
2315 Format = true;
2316 }
2317 else
2318 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2319 if (S.GetFormatNSStringIdx(I, Idx)) {
2320 Format = true;
2321 break;
2322 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002323 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002324 if (!Format || NumArgs <= Idx)
2325 return;
2326 const Expr *FormatExpr = Args[Idx];
2327 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2328 FormatExpr = CSCE->getSubExpr();
2329 const StringLiteral *FormatString;
2330 if (const ObjCStringLiteral *OSL =
2331 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2332 FormatString = OSL->getString();
2333 else
2334 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2335 if (!FormatString)
2336 return;
2337 if (S.FormatStringHasSArg(FormatString)) {
2338 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2339 << "%s" << 1 << 1;
2340 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2341 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002342 }
2343}
2344
Douglas Gregorb4866e82015-06-19 18:13:19 +00002345/// Determine whether the given type has a non-null nullability annotation.
2346static bool isNonNullType(ASTContext &ctx, QualType type) {
2347 if (auto nullability = type->getNullability(ctx))
2348 return *nullability == NullabilityKind::NonNull;
2349
2350 return false;
2351}
2352
Ted Kremenek2bc73332014-01-17 06:24:43 +00002353static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002354 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002355 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002356 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002357 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002358 assert((FDecl || Proto) && "Need a function declaration or prototype");
2359
Ted Kremenek9aedc152014-01-17 06:24:56 +00002360 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002361 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002362 if (FDecl) {
2363 // Handle the nonnull attribute on the function/method declaration itself.
2364 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2365 if (!NonNull->args_size()) {
2366 // Easy case: all pointer arguments are nonnull.
2367 for (const auto *Arg : Args)
2368 if (S.isValidPointerAttrType(Arg->getType()))
2369 CheckNonNullArgument(S, Arg, CallSiteLoc);
2370 return;
2371 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002372
Douglas Gregorb4866e82015-06-19 18:13:19 +00002373 for (unsigned Val : NonNull->args()) {
2374 if (Val >= Args.size())
2375 continue;
2376 if (NonNullArgs.empty())
2377 NonNullArgs.resize(Args.size());
2378 NonNullArgs.set(Val);
2379 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002380 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002381 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002382
Douglas Gregorb4866e82015-06-19 18:13:19 +00002383 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2384 // Handle the nonnull attribute on the parameters of the
2385 // function/method.
2386 ArrayRef<ParmVarDecl*> parms;
2387 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2388 parms = FD->parameters();
2389 else
2390 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2391
2392 unsigned ParamIndex = 0;
2393 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2394 I != E; ++I, ++ParamIndex) {
2395 const ParmVarDecl *PVD = *I;
2396 if (PVD->hasAttr<NonNullAttr>() ||
2397 isNonNullType(S.Context, PVD->getType())) {
2398 if (NonNullArgs.empty())
2399 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002400
Douglas Gregorb4866e82015-06-19 18:13:19 +00002401 NonNullArgs.set(ParamIndex);
2402 }
2403 }
2404 } else {
2405 // If we have a non-function, non-method declaration but no
2406 // function prototype, try to dig out the function prototype.
2407 if (!Proto) {
2408 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2409 QualType type = VD->getType().getNonReferenceType();
2410 if (auto pointerType = type->getAs<PointerType>())
2411 type = pointerType->getPointeeType();
2412 else if (auto blockType = type->getAs<BlockPointerType>())
2413 type = blockType->getPointeeType();
2414 // FIXME: data member pointers?
2415
2416 // Dig out the function prototype, if there is one.
2417 Proto = type->getAs<FunctionProtoType>();
2418 }
2419 }
2420
2421 // Fill in non-null argument information from the nullability
2422 // information on the parameter types (if we have them).
2423 if (Proto) {
2424 unsigned Index = 0;
2425 for (auto paramType : Proto->getParamTypes()) {
2426 if (isNonNullType(S.Context, paramType)) {
2427 if (NonNullArgs.empty())
2428 NonNullArgs.resize(Args.size());
2429
2430 NonNullArgs.set(Index);
2431 }
2432
2433 ++Index;
2434 }
2435 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002436 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002437
Douglas Gregorb4866e82015-06-19 18:13:19 +00002438 // Check for non-null arguments.
2439 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2440 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002441 if (NonNullArgs[ArgIndex])
2442 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002443 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002444}
2445
Richard Smith55ce3522012-06-25 20:30:08 +00002446/// Handles the checks for format strings, non-POD arguments to vararg
2447/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002448void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2449 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00002450 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00002451 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002452 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002453 if (CurContext->isDependentContext())
2454 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002455
Ted Kremenekb8176da2010-09-09 04:33:05 +00002456 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002457 llvm::SmallBitVector CheckedVarArgs;
2458 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002459 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002460 // Only create vector if there are format attributes.
2461 CheckedVarArgs.resize(Args.size());
2462
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002463 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002464 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002465 }
Richard Smithd7293d72013-08-05 18:49:43 +00002466 }
Richard Smith55ce3522012-06-25 20:30:08 +00002467
2468 // Refuse POD arguments that weren't caught by the format string
2469 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00002470 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002471 unsigned NumParams = Proto ? Proto->getNumParams()
2472 : FDecl && isa<FunctionDecl>(FDecl)
2473 ? cast<FunctionDecl>(FDecl)->getNumParams()
2474 : FDecl && isa<ObjCMethodDecl>(FDecl)
2475 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2476 : 0;
2477
Alp Toker9cacbab2014-01-20 20:26:09 +00002478 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002479 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002480 if (const Expr *Arg = Args[ArgIdx]) {
2481 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2482 checkVariadicArgument(Arg, CallType);
2483 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002484 }
Richard Smithd7293d72013-08-05 18:49:43 +00002485 }
Mike Stump11289f42009-09-09 15:08:12 +00002486
Douglas Gregorb4866e82015-06-19 18:13:19 +00002487 if (FDecl || Proto) {
2488 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002489
Richard Trieu41bc0992013-06-22 00:20:41 +00002490 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002491 if (FDecl) {
2492 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2493 CheckArgumentWithTypeTag(I, Args.data());
2494 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002495 }
Richard Smith55ce3522012-06-25 20:30:08 +00002496}
2497
2498/// CheckConstructorCall - Check a constructor call for correctness and safety
2499/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002500void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2501 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002502 const FunctionProtoType *Proto,
2503 SourceLocation Loc) {
2504 VariadicCallType CallType =
2505 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002506 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
2507 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002508}
2509
2510/// CheckFunctionCall - Check a direct function call for various correctness
2511/// and safety properties not strictly enforced by the C type system.
2512bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2513 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002514 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2515 isa<CXXMethodDecl>(FDecl);
2516 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2517 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002518 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2519 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002520 Expr** Args = TheCall->getArgs();
2521 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00002522 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002523 // If this is a call to a member operator, hide the first argument
2524 // from checkCall.
2525 // FIXME: Our choice of AST representation here is less than ideal.
2526 ++Args;
2527 --NumArgs;
2528 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00002529 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002530 IsMemberFunction, TheCall->getRParenLoc(),
2531 TheCall->getCallee()->getSourceRange(), CallType);
2532
2533 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2534 // None of the checks below are needed for functions that don't have
2535 // simple names (e.g., C++ conversion functions).
2536 if (!FnInfo)
2537 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002538
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002539 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002540 if (getLangOpts().ObjC1)
2541 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002542
Anna Zaks22122702012-01-17 00:37:07 +00002543 unsigned CMId = FDecl->getMemoryFunctionKind();
2544 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002545 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002546
Anna Zaks201d4892012-01-13 21:52:01 +00002547 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002548 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002549 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002550 else if (CMId == Builtin::BIstrncat)
2551 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002552 else
Anna Zaks22122702012-01-17 00:37:07 +00002553 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002554
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002555 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002556}
2557
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002558bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002559 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002560 VariadicCallType CallType =
2561 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002562
Douglas Gregorb4866e82015-06-19 18:13:19 +00002563 checkCall(Method, nullptr, Args,
2564 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2565 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002566
2567 return false;
2568}
2569
Richard Trieu664c4c62013-06-20 21:03:13 +00002570bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2571 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002572 QualType Ty;
2573 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002574 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002575 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002576 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002577 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002578 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002579
Douglas Gregorb4866e82015-06-19 18:13:19 +00002580 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2581 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002582 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002583
Richard Trieu664c4c62013-06-20 21:03:13 +00002584 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002585 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002586 CallType = VariadicDoesNotApply;
2587 } else if (Ty->isBlockPointerType()) {
2588 CallType = VariadicBlock;
2589 } else { // Ty->isFunctionPointerType()
2590 CallType = VariadicFunction;
2591 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002592
Douglas Gregorb4866e82015-06-19 18:13:19 +00002593 checkCall(NDecl, Proto,
2594 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2595 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002596 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002597
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002598 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002599}
2600
Richard Trieu41bc0992013-06-22 00:20:41 +00002601/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2602/// such as function pointers returned from functions.
2603bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002604 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002605 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00002606 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002607 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002608 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002609 TheCall->getCallee()->getSourceRange(), CallType);
2610
2611 return false;
2612}
2613
Tim Northovere94a34c2014-03-11 10:49:14 +00002614static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002615 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002616 return false;
2617
JF Bastiendda2cb12016-04-18 18:01:49 +00002618 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002619 switch (Op) {
2620 case AtomicExpr::AO__c11_atomic_init:
2621 llvm_unreachable("There is no ordering argument for an init");
2622
2623 case AtomicExpr::AO__c11_atomic_load:
2624 case AtomicExpr::AO__atomic_load_n:
2625 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002626 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2627 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002628
2629 case AtomicExpr::AO__c11_atomic_store:
2630 case AtomicExpr::AO__atomic_store:
2631 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002632 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2633 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2634 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002635
2636 default:
2637 return true;
2638 }
2639}
2640
Richard Smithfeea8832012-04-12 05:08:17 +00002641ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2642 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002643 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2644 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002645
Richard Smithfeea8832012-04-12 05:08:17 +00002646 // All these operations take one of the following forms:
2647 enum {
2648 // C __c11_atomic_init(A *, C)
2649 Init,
2650 // C __c11_atomic_load(A *, int)
2651 Load,
2652 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002653 LoadCopy,
2654 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002655 Copy,
2656 // C __c11_atomic_add(A *, M, int)
2657 Arithmetic,
2658 // C __atomic_exchange_n(A *, CP, int)
2659 Xchg,
2660 // void __atomic_exchange(A *, C *, CP, int)
2661 GNUXchg,
2662 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2663 C11CmpXchg,
2664 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2665 GNUCmpXchg
2666 } Form = Init;
Eric Fiselier8d662442016-03-30 23:39:56 +00002667 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2668 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002669 // where:
2670 // C is an appropriate type,
2671 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2672 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2673 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2674 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002675
Gabor Horvath98bd0982015-03-16 09:59:54 +00002676 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2677 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2678 AtomicExpr::AO__atomic_load,
2679 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00002680 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2681 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2682 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2683 Op == AtomicExpr::AO__atomic_store_n ||
2684 Op == AtomicExpr::AO__atomic_exchange_n ||
2685 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2686 bool IsAddSub = false;
2687
2688 switch (Op) {
2689 case AtomicExpr::AO__c11_atomic_init:
2690 Form = Init;
2691 break;
2692
2693 case AtomicExpr::AO__c11_atomic_load:
2694 case AtomicExpr::AO__atomic_load_n:
2695 Form = Load;
2696 break;
2697
Richard Smithfeea8832012-04-12 05:08:17 +00002698 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002699 Form = LoadCopy;
2700 break;
2701
2702 case AtomicExpr::AO__c11_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002703 case AtomicExpr::AO__atomic_store:
2704 case AtomicExpr::AO__atomic_store_n:
2705 Form = Copy;
2706 break;
2707
2708 case AtomicExpr::AO__c11_atomic_fetch_add:
2709 case AtomicExpr::AO__c11_atomic_fetch_sub:
2710 case AtomicExpr::AO__atomic_fetch_add:
2711 case AtomicExpr::AO__atomic_fetch_sub:
2712 case AtomicExpr::AO__atomic_add_fetch:
2713 case AtomicExpr::AO__atomic_sub_fetch:
2714 IsAddSub = true;
2715 // Fall through.
2716 case AtomicExpr::AO__c11_atomic_fetch_and:
2717 case AtomicExpr::AO__c11_atomic_fetch_or:
2718 case AtomicExpr::AO__c11_atomic_fetch_xor:
2719 case AtomicExpr::AO__atomic_fetch_and:
2720 case AtomicExpr::AO__atomic_fetch_or:
2721 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00002722 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00002723 case AtomicExpr::AO__atomic_and_fetch:
2724 case AtomicExpr::AO__atomic_or_fetch:
2725 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00002726 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00002727 Form = Arithmetic;
2728 break;
2729
2730 case AtomicExpr::AO__c11_atomic_exchange:
2731 case AtomicExpr::AO__atomic_exchange_n:
2732 Form = Xchg;
2733 break;
2734
2735 case AtomicExpr::AO__atomic_exchange:
2736 Form = GNUXchg;
2737 break;
2738
2739 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2740 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2741 Form = C11CmpXchg;
2742 break;
2743
2744 case AtomicExpr::AO__atomic_compare_exchange:
2745 case AtomicExpr::AO__atomic_compare_exchange_n:
2746 Form = GNUCmpXchg;
2747 break;
2748 }
2749
2750 // Check we have the right number of arguments.
2751 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002752 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002753 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002754 << TheCall->getCallee()->getSourceRange();
2755 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00002756 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2757 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002758 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002759 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002760 << TheCall->getCallee()->getSourceRange();
2761 return ExprError();
2762 }
2763
Richard Smithfeea8832012-04-12 05:08:17 +00002764 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002765 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00002766 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2767 if (ConvertedPtr.isInvalid())
2768 return ExprError();
2769
2770 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002771 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2772 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00002773 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002774 << Ptr->getType() << Ptr->getSourceRange();
2775 return ExprError();
2776 }
2777
Richard Smithfeea8832012-04-12 05:08:17 +00002778 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2779 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2780 QualType ValType = AtomTy; // 'C'
2781 if (IsC11) {
2782 if (!AtomTy->isAtomicType()) {
2783 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2784 << Ptr->getType() << Ptr->getSourceRange();
2785 return ExprError();
2786 }
Richard Smithe00921a2012-09-15 06:09:58 +00002787 if (AtomTy.isConstQualified()) {
2788 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2789 << Ptr->getType() << Ptr->getSourceRange();
2790 return ExprError();
2791 }
Richard Smithfeea8832012-04-12 05:08:17 +00002792 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00002793 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002794 if (ValType.isConstQualified()) {
2795 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2796 << Ptr->getType() << Ptr->getSourceRange();
2797 return ExprError();
2798 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002799 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002800
Richard Smithfeea8832012-04-12 05:08:17 +00002801 // For an arithmetic operation, the implied arithmetic must be well-formed.
2802 if (Form == Arithmetic) {
2803 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2804 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2805 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2806 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2807 return ExprError();
2808 }
2809 if (!IsAddSub && !ValType->isIntegerType()) {
2810 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2811 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2812 return ExprError();
2813 }
David Majnemere85cff82015-01-28 05:48:06 +00002814 if (IsC11 && ValType->isPointerType() &&
2815 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2816 diag::err_incomplete_type)) {
2817 return ExprError();
2818 }
Richard Smithfeea8832012-04-12 05:08:17 +00002819 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2820 // For __atomic_*_n operations, the value type must be a scalar integral or
2821 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002822 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00002823 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2824 return ExprError();
2825 }
2826
Eli Friedmanaa769812013-09-11 03:49:34 +00002827 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2828 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00002829 // For GNU atomics, require a trivially-copyable type. This is not part of
2830 // the GNU atomics specification, but we enforce it for sanity.
2831 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002832 << Ptr->getType() << Ptr->getSourceRange();
2833 return ExprError();
2834 }
2835
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002836 switch (ValType.getObjCLifetime()) {
2837 case Qualifiers::OCL_None:
2838 case Qualifiers::OCL_ExplicitNone:
2839 // okay
2840 break;
2841
2842 case Qualifiers::OCL_Weak:
2843 case Qualifiers::OCL_Strong:
2844 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002845 // FIXME: Can this happen? By this point, ValType should be known
2846 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002847 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2848 << ValType << Ptr->getSourceRange();
2849 return ExprError();
2850 }
2851
David Majnemerc6eb6502015-06-03 00:26:35 +00002852 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2853 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00002854 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00002855 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00002856 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002857 QualType ResultType = ValType;
Eric Fiselier8d662442016-03-30 23:39:56 +00002858 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002859 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002860 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002861 ResultType = Context.BoolTy;
2862
Richard Smithfeea8832012-04-12 05:08:17 +00002863 // The type of a parameter passed 'by value'. In the GNU atomics, such
2864 // arguments are actually passed as pointers.
2865 QualType ByValType = ValType; // 'CP'
2866 if (!IsC11 && !IsN)
2867 ByValType = Ptr->getType();
2868
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002869 // The first argument --- the pointer --- has a fixed type; we
2870 // deduce the types of the rest of the arguments accordingly. Walk
2871 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002872 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002873 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002874 if (i < NumVals[Form] + 1) {
2875 switch (i) {
2876 case 1:
2877 // The second argument is the non-atomic operand. For arithmetic, this
2878 // is always passed by value, and for a compare_exchange it is always
2879 // passed by address. For the rest, GNU uses by-address and C11 uses
2880 // by-value.
2881 assert(Form != Load);
2882 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2883 Ty = ValType;
2884 else if (Form == Copy || Form == Xchg)
2885 Ty = ByValType;
2886 else if (Form == Arithmetic)
2887 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002888 else {
2889 Expr *ValArg = TheCall->getArg(i);
2890 unsigned AS = 0;
2891 // Keep address space of non-atomic pointer type.
2892 if (const PointerType *PtrTy =
2893 ValArg->getType()->getAs<PointerType>()) {
2894 AS = PtrTy->getPointeeType().getAddressSpace();
2895 }
2896 Ty = Context.getPointerType(
2897 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2898 }
Richard Smithfeea8832012-04-12 05:08:17 +00002899 break;
2900 case 2:
2901 // The third argument to compare_exchange / GNU exchange is a
2902 // (pointer to a) desired value.
2903 Ty = ByValType;
2904 break;
2905 case 3:
2906 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2907 Ty = Context.BoolTy;
2908 break;
2909 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002910 } else {
2911 // The order(s) are always converted to int.
2912 Ty = Context.IntTy;
2913 }
Richard Smithfeea8832012-04-12 05:08:17 +00002914
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002915 InitializedEntity Entity =
2916 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00002917 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002918 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2919 if (Arg.isInvalid())
2920 return true;
2921 TheCall->setArg(i, Arg.get());
2922 }
2923
Richard Smithfeea8832012-04-12 05:08:17 +00002924 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002925 SmallVector<Expr*, 5> SubExprs;
2926 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00002927 switch (Form) {
2928 case Init:
2929 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00002930 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002931 break;
2932 case Load:
2933 SubExprs.push_back(TheCall->getArg(1)); // Order
2934 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00002935 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00002936 case Copy:
2937 case Arithmetic:
2938 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002939 SubExprs.push_back(TheCall->getArg(2)); // Order
2940 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002941 break;
2942 case GNUXchg:
2943 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2944 SubExprs.push_back(TheCall->getArg(3)); // Order
2945 SubExprs.push_back(TheCall->getArg(1)); // Val1
2946 SubExprs.push_back(TheCall->getArg(2)); // Val2
2947 break;
2948 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002949 SubExprs.push_back(TheCall->getArg(3)); // Order
2950 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002951 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00002952 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00002953 break;
2954 case GNUCmpXchg:
2955 SubExprs.push_back(TheCall->getArg(4)); // Order
2956 SubExprs.push_back(TheCall->getArg(1)); // Val1
2957 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2958 SubExprs.push_back(TheCall->getArg(2)); // Val2
2959 SubExprs.push_back(TheCall->getArg(3)); // Weak
2960 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002961 }
Tim Northovere94a34c2014-03-11 10:49:14 +00002962
2963 if (SubExprs.size() >= 2 && Form != Init) {
2964 llvm::APSInt Result(32);
2965 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2966 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00002967 Diag(SubExprs[1]->getLocStart(),
2968 diag::warn_atomic_op_has_invalid_memory_order)
2969 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00002970 }
2971
Fariborz Jahanian615de762013-05-28 17:37:39 +00002972 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2973 SubExprs, ResultType, Op,
2974 TheCall->getRParenLoc());
2975
2976 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2977 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2978 Context.AtomicUsesUnsupportedLibcall(AE))
2979 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2980 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002981
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002982 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002983}
2984
John McCall29ad95b2011-08-27 01:09:30 +00002985/// checkBuiltinArgument - Given a call to a builtin function, perform
2986/// normal type-checking on the given argument, updating the call in
2987/// place. This is useful when a builtin function requires custom
2988/// type-checking for some of its arguments but not necessarily all of
2989/// them.
2990///
2991/// Returns true on error.
2992static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2993 FunctionDecl *Fn = E->getDirectCallee();
2994 assert(Fn && "builtin call without direct callee!");
2995
2996 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2997 InitializedEntity Entity =
2998 InitializedEntity::InitializeParameter(S.Context, Param);
2999
3000 ExprResult Arg = E->getArg(0);
3001 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3002 if (Arg.isInvalid())
3003 return true;
3004
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003005 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003006 return false;
3007}
3008
Chris Lattnerdc046542009-05-08 06:58:22 +00003009/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3010/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3011/// type of its first argument. The main ActOnCallExpr routines have already
3012/// promoted the types of arguments because all of these calls are prototyped as
3013/// void(...).
3014///
3015/// This function goes through and does final semantic checking for these
3016/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003017ExprResult
3018Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003019 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003020 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3021 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3022
3023 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003024 if (TheCall->getNumArgs() < 1) {
3025 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3026 << 0 << 1 << TheCall->getNumArgs()
3027 << TheCall->getCallee()->getSourceRange();
3028 return ExprError();
3029 }
Mike Stump11289f42009-09-09 15:08:12 +00003030
Chris Lattnerdc046542009-05-08 06:58:22 +00003031 // Inspect the first argument of the atomic builtin. This should always be
3032 // a pointer type, whose element is an integral scalar or pointer type.
3033 // Because it is a pointer type, we don't have to worry about any implicit
3034 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003035 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003036 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003037 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3038 if (FirstArgResult.isInvalid())
3039 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003040 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003041 TheCall->setArg(0, FirstArg);
3042
John McCall31168b02011-06-15 23:02:42 +00003043 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3044 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003045 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3046 << FirstArg->getType() << FirstArg->getSourceRange();
3047 return ExprError();
3048 }
Mike Stump11289f42009-09-09 15:08:12 +00003049
John McCall31168b02011-06-15 23:02:42 +00003050 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003051 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003052 !ValType->isBlockPointerType()) {
3053 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3054 << FirstArg->getType() << FirstArg->getSourceRange();
3055 return ExprError();
3056 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003057
John McCall31168b02011-06-15 23:02:42 +00003058 switch (ValType.getObjCLifetime()) {
3059 case Qualifiers::OCL_None:
3060 case Qualifiers::OCL_ExplicitNone:
3061 // okay
3062 break;
3063
3064 case Qualifiers::OCL_Weak:
3065 case Qualifiers::OCL_Strong:
3066 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003067 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003068 << ValType << FirstArg->getSourceRange();
3069 return ExprError();
3070 }
3071
John McCallb50451a2011-10-05 07:41:44 +00003072 // Strip any qualifiers off ValType.
3073 ValType = ValType.getUnqualifiedType();
3074
Chandler Carruth3973af72010-07-18 20:54:12 +00003075 // The majority of builtins return a value, but a few have special return
3076 // types, so allow them to override appropriately below.
3077 QualType ResultType = ValType;
3078
Chris Lattnerdc046542009-05-08 06:58:22 +00003079 // We need to figure out which concrete builtin this maps onto. For example,
3080 // __sync_fetch_and_add with a 2 byte object turns into
3081 // __sync_fetch_and_add_2.
3082#define BUILTIN_ROW(x) \
3083 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3084 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003085
Chris Lattnerdc046542009-05-08 06:58:22 +00003086 static const unsigned BuiltinIndices[][5] = {
3087 BUILTIN_ROW(__sync_fetch_and_add),
3088 BUILTIN_ROW(__sync_fetch_and_sub),
3089 BUILTIN_ROW(__sync_fetch_and_or),
3090 BUILTIN_ROW(__sync_fetch_and_and),
3091 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003092 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003093
Chris Lattnerdc046542009-05-08 06:58:22 +00003094 BUILTIN_ROW(__sync_add_and_fetch),
3095 BUILTIN_ROW(__sync_sub_and_fetch),
3096 BUILTIN_ROW(__sync_and_and_fetch),
3097 BUILTIN_ROW(__sync_or_and_fetch),
3098 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003099 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003100
Chris Lattnerdc046542009-05-08 06:58:22 +00003101 BUILTIN_ROW(__sync_val_compare_and_swap),
3102 BUILTIN_ROW(__sync_bool_compare_and_swap),
3103 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003104 BUILTIN_ROW(__sync_lock_release),
3105 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003106 };
Mike Stump11289f42009-09-09 15:08:12 +00003107#undef BUILTIN_ROW
3108
Chris Lattnerdc046542009-05-08 06:58:22 +00003109 // Determine the index of the size.
3110 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003111 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003112 case 1: SizeIndex = 0; break;
3113 case 2: SizeIndex = 1; break;
3114 case 4: SizeIndex = 2; break;
3115 case 8: SizeIndex = 3; break;
3116 case 16: SizeIndex = 4; break;
3117 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003118 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3119 << FirstArg->getType() << FirstArg->getSourceRange();
3120 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003121 }
Mike Stump11289f42009-09-09 15:08:12 +00003122
Chris Lattnerdc046542009-05-08 06:58:22 +00003123 // Each of these builtins has one pointer argument, followed by some number of
3124 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3125 // that we ignore. Find out which row of BuiltinIndices to read from as well
3126 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003127 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003128 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003129 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003130 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003131 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003132 case Builtin::BI__sync_fetch_and_add:
3133 case Builtin::BI__sync_fetch_and_add_1:
3134 case Builtin::BI__sync_fetch_and_add_2:
3135 case Builtin::BI__sync_fetch_and_add_4:
3136 case Builtin::BI__sync_fetch_and_add_8:
3137 case Builtin::BI__sync_fetch_and_add_16:
3138 BuiltinIndex = 0;
3139 break;
3140
3141 case Builtin::BI__sync_fetch_and_sub:
3142 case Builtin::BI__sync_fetch_and_sub_1:
3143 case Builtin::BI__sync_fetch_and_sub_2:
3144 case Builtin::BI__sync_fetch_and_sub_4:
3145 case Builtin::BI__sync_fetch_and_sub_8:
3146 case Builtin::BI__sync_fetch_and_sub_16:
3147 BuiltinIndex = 1;
3148 break;
3149
3150 case Builtin::BI__sync_fetch_and_or:
3151 case Builtin::BI__sync_fetch_and_or_1:
3152 case Builtin::BI__sync_fetch_and_or_2:
3153 case Builtin::BI__sync_fetch_and_or_4:
3154 case Builtin::BI__sync_fetch_and_or_8:
3155 case Builtin::BI__sync_fetch_and_or_16:
3156 BuiltinIndex = 2;
3157 break;
3158
3159 case Builtin::BI__sync_fetch_and_and:
3160 case Builtin::BI__sync_fetch_and_and_1:
3161 case Builtin::BI__sync_fetch_and_and_2:
3162 case Builtin::BI__sync_fetch_and_and_4:
3163 case Builtin::BI__sync_fetch_and_and_8:
3164 case Builtin::BI__sync_fetch_and_and_16:
3165 BuiltinIndex = 3;
3166 break;
Mike Stump11289f42009-09-09 15:08:12 +00003167
Douglas Gregor73722482011-11-28 16:30:08 +00003168 case Builtin::BI__sync_fetch_and_xor:
3169 case Builtin::BI__sync_fetch_and_xor_1:
3170 case Builtin::BI__sync_fetch_and_xor_2:
3171 case Builtin::BI__sync_fetch_and_xor_4:
3172 case Builtin::BI__sync_fetch_and_xor_8:
3173 case Builtin::BI__sync_fetch_and_xor_16:
3174 BuiltinIndex = 4;
3175 break;
3176
Hal Finkeld2208b52014-10-02 20:53:50 +00003177 case Builtin::BI__sync_fetch_and_nand:
3178 case Builtin::BI__sync_fetch_and_nand_1:
3179 case Builtin::BI__sync_fetch_and_nand_2:
3180 case Builtin::BI__sync_fetch_and_nand_4:
3181 case Builtin::BI__sync_fetch_and_nand_8:
3182 case Builtin::BI__sync_fetch_and_nand_16:
3183 BuiltinIndex = 5;
3184 WarnAboutSemanticsChange = true;
3185 break;
3186
Douglas Gregor73722482011-11-28 16:30:08 +00003187 case Builtin::BI__sync_add_and_fetch:
3188 case Builtin::BI__sync_add_and_fetch_1:
3189 case Builtin::BI__sync_add_and_fetch_2:
3190 case Builtin::BI__sync_add_and_fetch_4:
3191 case Builtin::BI__sync_add_and_fetch_8:
3192 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003193 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003194 break;
3195
3196 case Builtin::BI__sync_sub_and_fetch:
3197 case Builtin::BI__sync_sub_and_fetch_1:
3198 case Builtin::BI__sync_sub_and_fetch_2:
3199 case Builtin::BI__sync_sub_and_fetch_4:
3200 case Builtin::BI__sync_sub_and_fetch_8:
3201 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003202 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003203 break;
3204
3205 case Builtin::BI__sync_and_and_fetch:
3206 case Builtin::BI__sync_and_and_fetch_1:
3207 case Builtin::BI__sync_and_and_fetch_2:
3208 case Builtin::BI__sync_and_and_fetch_4:
3209 case Builtin::BI__sync_and_and_fetch_8:
3210 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003211 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003212 break;
3213
3214 case Builtin::BI__sync_or_and_fetch:
3215 case Builtin::BI__sync_or_and_fetch_1:
3216 case Builtin::BI__sync_or_and_fetch_2:
3217 case Builtin::BI__sync_or_and_fetch_4:
3218 case Builtin::BI__sync_or_and_fetch_8:
3219 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003220 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003221 break;
3222
3223 case Builtin::BI__sync_xor_and_fetch:
3224 case Builtin::BI__sync_xor_and_fetch_1:
3225 case Builtin::BI__sync_xor_and_fetch_2:
3226 case Builtin::BI__sync_xor_and_fetch_4:
3227 case Builtin::BI__sync_xor_and_fetch_8:
3228 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003229 BuiltinIndex = 10;
3230 break;
3231
3232 case Builtin::BI__sync_nand_and_fetch:
3233 case Builtin::BI__sync_nand_and_fetch_1:
3234 case Builtin::BI__sync_nand_and_fetch_2:
3235 case Builtin::BI__sync_nand_and_fetch_4:
3236 case Builtin::BI__sync_nand_and_fetch_8:
3237 case Builtin::BI__sync_nand_and_fetch_16:
3238 BuiltinIndex = 11;
3239 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003240 break;
Mike Stump11289f42009-09-09 15:08:12 +00003241
Chris Lattnerdc046542009-05-08 06:58:22 +00003242 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003243 case Builtin::BI__sync_val_compare_and_swap_1:
3244 case Builtin::BI__sync_val_compare_and_swap_2:
3245 case Builtin::BI__sync_val_compare_and_swap_4:
3246 case Builtin::BI__sync_val_compare_and_swap_8:
3247 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003248 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003249 NumFixed = 2;
3250 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003251
Chris Lattnerdc046542009-05-08 06:58:22 +00003252 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003253 case Builtin::BI__sync_bool_compare_and_swap_1:
3254 case Builtin::BI__sync_bool_compare_and_swap_2:
3255 case Builtin::BI__sync_bool_compare_and_swap_4:
3256 case Builtin::BI__sync_bool_compare_and_swap_8:
3257 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003258 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003259 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003260 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003261 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003262
3263 case Builtin::BI__sync_lock_test_and_set:
3264 case Builtin::BI__sync_lock_test_and_set_1:
3265 case Builtin::BI__sync_lock_test_and_set_2:
3266 case Builtin::BI__sync_lock_test_and_set_4:
3267 case Builtin::BI__sync_lock_test_and_set_8:
3268 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003269 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003270 break;
3271
Chris Lattnerdc046542009-05-08 06:58:22 +00003272 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003273 case Builtin::BI__sync_lock_release_1:
3274 case Builtin::BI__sync_lock_release_2:
3275 case Builtin::BI__sync_lock_release_4:
3276 case Builtin::BI__sync_lock_release_8:
3277 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003278 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003279 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003280 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003281 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003282
3283 case Builtin::BI__sync_swap:
3284 case Builtin::BI__sync_swap_1:
3285 case Builtin::BI__sync_swap_2:
3286 case Builtin::BI__sync_swap_4:
3287 case Builtin::BI__sync_swap_8:
3288 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003289 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003290 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003291 }
Mike Stump11289f42009-09-09 15:08:12 +00003292
Chris Lattnerdc046542009-05-08 06:58:22 +00003293 // Now that we know how many fixed arguments we expect, first check that we
3294 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003295 if (TheCall->getNumArgs() < 1+NumFixed) {
3296 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3297 << 0 << 1+NumFixed << TheCall->getNumArgs()
3298 << TheCall->getCallee()->getSourceRange();
3299 return ExprError();
3300 }
Mike Stump11289f42009-09-09 15:08:12 +00003301
Hal Finkeld2208b52014-10-02 20:53:50 +00003302 if (WarnAboutSemanticsChange) {
3303 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3304 << TheCall->getCallee()->getSourceRange();
3305 }
3306
Chris Lattner5b9241b2009-05-08 15:36:58 +00003307 // Get the decl for the concrete builtin from this, we can tell what the
3308 // concrete integer type we should convert to is.
3309 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003310 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003311 FunctionDecl *NewBuiltinDecl;
3312 if (NewBuiltinID == BuiltinID)
3313 NewBuiltinDecl = FDecl;
3314 else {
3315 // Perform builtin lookup to avoid redeclaring it.
3316 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3317 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3318 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3319 assert(Res.getFoundDecl());
3320 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003321 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003322 return ExprError();
3323 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003324
John McCallcf142162010-08-07 06:22:56 +00003325 // The first argument --- the pointer --- has a fixed type; we
3326 // deduce the types of the rest of the arguments accordingly. Walk
3327 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003328 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003329 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003330
Chris Lattnerdc046542009-05-08 06:58:22 +00003331 // GCC does an implicit conversion to the pointer or integer ValType. This
3332 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003333 // Initialize the argument.
3334 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3335 ValType, /*consume*/ false);
3336 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003337 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003338 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003339
Chris Lattnerdc046542009-05-08 06:58:22 +00003340 // Okay, we have something that *can* be converted to the right type. Check
3341 // to see if there is a potentially weird extension going on here. This can
3342 // happen when you do an atomic operation on something like an char* and
3343 // pass in 42. The 42 gets converted to char. This is even more strange
3344 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003345 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003346 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003347 }
Mike Stump11289f42009-09-09 15:08:12 +00003348
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003349 ASTContext& Context = this->getASTContext();
3350
3351 // Create a new DeclRefExpr to refer to the new decl.
3352 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3353 Context,
3354 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003355 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003356 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003357 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003358 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003359 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003360 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003361
Chris Lattnerdc046542009-05-08 06:58:22 +00003362 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003363 // FIXME: This loses syntactic information.
3364 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3365 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3366 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003367 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003368
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003369 // Change the result type of the call to match the original value type. This
3370 // is arbitrary, but the codegen for these builtins ins design to handle it
3371 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003372 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003373
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003374 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003375}
3376
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003377/// SemaBuiltinNontemporalOverloaded - We have a call to
3378/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3379/// overloaded function based on the pointer type of its last argument.
3380///
3381/// This function goes through and does final semantic checking for these
3382/// builtins.
3383ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3384 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3385 DeclRefExpr *DRE =
3386 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3387 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3388 unsigned BuiltinID = FDecl->getBuiltinID();
3389 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3390 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3391 "Unexpected nontemporal load/store builtin!");
3392 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3393 unsigned numArgs = isStore ? 2 : 1;
3394
3395 // Ensure that we have the proper number of arguments.
3396 if (checkArgCount(*this, TheCall, numArgs))
3397 return ExprError();
3398
3399 // Inspect the last argument of the nontemporal builtin. This should always
3400 // be a pointer type, from which we imply the type of the memory access.
3401 // Because it is a pointer type, we don't have to worry about any implicit
3402 // casts here.
3403 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3404 ExprResult PointerArgResult =
3405 DefaultFunctionArrayLvalueConversion(PointerArg);
3406
3407 if (PointerArgResult.isInvalid())
3408 return ExprError();
3409 PointerArg = PointerArgResult.get();
3410 TheCall->setArg(numArgs - 1, PointerArg);
3411
3412 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3413 if (!pointerType) {
3414 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3415 << PointerArg->getType() << PointerArg->getSourceRange();
3416 return ExprError();
3417 }
3418
3419 QualType ValType = pointerType->getPointeeType();
3420
3421 // Strip any qualifiers off ValType.
3422 ValType = ValType.getUnqualifiedType();
3423 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3424 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3425 !ValType->isVectorType()) {
3426 Diag(DRE->getLocStart(),
3427 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3428 << PointerArg->getType() << PointerArg->getSourceRange();
3429 return ExprError();
3430 }
3431
3432 if (!isStore) {
3433 TheCall->setType(ValType);
3434 return TheCallResult;
3435 }
3436
3437 ExprResult ValArg = TheCall->getArg(0);
3438 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3439 Context, ValType, /*consume*/ false);
3440 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3441 if (ValArg.isInvalid())
3442 return ExprError();
3443
3444 TheCall->setArg(0, ValArg.get());
3445 TheCall->setType(Context.VoidTy);
3446 return TheCallResult;
3447}
3448
Chris Lattner6436fb62009-02-18 06:01:06 +00003449/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003450/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003451/// Note: It might also make sense to do the UTF-16 conversion here (would
3452/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003453bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003454 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003455 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3456
Douglas Gregorfb65e592011-07-27 05:40:30 +00003457 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003458 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3459 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003460 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003461 }
Mike Stump11289f42009-09-09 15:08:12 +00003462
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003463 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003464 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003465 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00003466 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3467 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3468 llvm::UTF16 *ToPtr = &ToBuf[0];
3469
3470 llvm::ConversionResult Result =
3471 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3472 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003473 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00003474 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003475 Diag(Arg->getLocStart(),
3476 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3477 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003478 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003479}
3480
Charles Davisc7d5c942015-09-17 20:55:33 +00003481/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3482/// for validity. Emit an error and return true on failure; return false
3483/// on success.
3484bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003485 Expr *Fn = TheCall->getCallee();
3486 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003487 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003488 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003489 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3490 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003491 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003492 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003493 return true;
3494 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003495
3496 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003497 return Diag(TheCall->getLocEnd(),
3498 diag::err_typecheck_call_too_few_args_at_least)
3499 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003500 }
3501
John McCall29ad95b2011-08-27 01:09:30 +00003502 // Type-check the first argument normally.
3503 if (checkBuiltinArgument(*this, TheCall, 0))
3504 return true;
3505
Chris Lattnere202e6a2007-12-20 00:05:45 +00003506 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00003507 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00003508 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00003509 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00003510 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00003511 else if (FunctionDecl *FD = getCurFunctionDecl())
3512 isVariadic = FD->isVariadic();
3513 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00003514 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00003515
Chris Lattnere202e6a2007-12-20 00:05:45 +00003516 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003517 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3518 return true;
3519 }
Mike Stump11289f42009-09-09 15:08:12 +00003520
Chris Lattner43be2e62007-12-19 23:59:04 +00003521 // Verify that the second argument to the builtin is the last argument of the
3522 // current function or method.
3523 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003524 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003525
Nico Weber9eea7642013-05-24 23:31:57 +00003526 // These are valid if SecondArgIsLastNamedArgument is false after the next
3527 // block.
3528 QualType Type;
3529 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003530 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003531
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003532 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3533 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003534 // FIXME: This isn't correct for methods (results in bogus warning).
3535 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003536 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00003537 if (CurBlock)
David Majnemera3debed2016-06-24 05:33:44 +00003538 LastArg = CurBlock->TheDecl->parameters().back();
Steve Naroff439a3e42009-04-15 19:33:47 +00003539 else if (FunctionDecl *FD = getCurFunctionDecl())
David Majnemera3debed2016-06-24 05:33:44 +00003540 LastArg = FD->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003541 else
David Majnemera3debed2016-06-24 05:33:44 +00003542 LastArg = getCurMethodDecl()->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003543 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00003544
3545 Type = PV->getType();
3546 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003547 IsCRegister =
3548 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003549 }
3550 }
Mike Stump11289f42009-09-09 15:08:12 +00003551
Chris Lattner43be2e62007-12-19 23:59:04 +00003552 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003553 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003554 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003555 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00003556 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3557 // Promotable integers are UB, but enumerations need a bit of
3558 // extra checking to see what their promotable type actually is.
3559 if (!Type->isPromotableIntegerType())
3560 return false;
3561 if (!Type->isEnumeralType())
3562 return true;
3563 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3564 return !(ED &&
3565 Context.typesAreCompatible(ED->getPromotionType(), Type));
3566 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00003567 unsigned Reason = 0;
3568 if (Type->isReferenceType()) Reason = 1;
3569 else if (IsCRegister) Reason = 2;
3570 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003571 Diag(ParamLoc, diag::note_parameter_type) << Type;
3572 }
3573
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003574 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003575 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003576}
Chris Lattner43be2e62007-12-19 23:59:04 +00003577
Charles Davisc7d5c942015-09-17 20:55:33 +00003578/// Check the arguments to '__builtin_va_start' for validity, and that
3579/// it was called from a function of the native ABI.
3580/// Emit an error and return true on failure; return false on success.
3581bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3582 // On x86-64 Unix, don't allow this in Win64 ABI functions.
3583 // On x64 Windows, don't allow this in System V ABI functions.
3584 // (Yes, that means there's no corresponding way to support variadic
3585 // System V ABI functions on Windows.)
3586 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3587 unsigned OS = Context.getTargetInfo().getTriple().getOS();
3588 clang::CallingConv CC = CC_C;
3589 if (const FunctionDecl *FD = getCurFunctionDecl())
3590 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3591 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3592 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3593 return Diag(TheCall->getCallee()->getLocStart(),
3594 diag::err_va_start_used_in_wrong_abi_function)
3595 << (OS != llvm::Triple::Win32);
3596 }
3597 return SemaBuiltinVAStartImpl(TheCall);
3598}
3599
3600/// Check the arguments to '__builtin_ms_va_start' for validity, and that
3601/// it was called from a Win64 ABI function.
3602/// Emit an error and return true on failure; return false on success.
3603bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3604 // This only makes sense for x86-64.
3605 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3606 Expr *Callee = TheCall->getCallee();
3607 if (TT.getArch() != llvm::Triple::x86_64)
3608 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3609 // Don't allow this in System V ABI functions.
3610 clang::CallingConv CC = CC_C;
3611 if (const FunctionDecl *FD = getCurFunctionDecl())
3612 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3613 if (CC == CC_X86_64SysV ||
3614 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3615 return Diag(Callee->getLocStart(),
3616 diag::err_ms_va_start_used_in_sysv_function);
3617 return SemaBuiltinVAStartImpl(TheCall);
3618}
3619
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003620bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3621 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3622 // const char *named_addr);
3623
3624 Expr *Func = Call->getCallee();
3625
3626 if (Call->getNumArgs() < 3)
3627 return Diag(Call->getLocEnd(),
3628 diag::err_typecheck_call_too_few_args_at_least)
3629 << 0 /*function call*/ << 3 << Call->getNumArgs();
3630
3631 // Determine whether the current function is variadic or not.
3632 bool IsVariadic;
3633 if (BlockScopeInfo *CurBlock = getCurBlock())
3634 IsVariadic = CurBlock->TheDecl->isVariadic();
3635 else if (FunctionDecl *FD = getCurFunctionDecl())
3636 IsVariadic = FD->isVariadic();
3637 else if (ObjCMethodDecl *MD = getCurMethodDecl())
3638 IsVariadic = MD->isVariadic();
3639 else
3640 llvm_unreachable("unexpected statement type");
3641
3642 if (!IsVariadic) {
3643 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3644 return true;
3645 }
3646
3647 // Type-check the first argument normally.
3648 if (checkBuiltinArgument(*this, Call, 0))
3649 return true;
3650
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003651 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003652 unsigned ArgNo;
3653 QualType Type;
3654 } ArgumentTypes[] = {
3655 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3656 { 2, Context.getSizeType() },
3657 };
3658
3659 for (const auto &AT : ArgumentTypes) {
3660 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3661 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3662 continue;
3663 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3664 << Arg->getType() << AT.Type << 1 /* different class */
3665 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3666 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3667 }
3668
3669 return false;
3670}
3671
Chris Lattner2da14fb2007-12-20 00:26:33 +00003672/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3673/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003674bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3675 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003676 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003677 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003678 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003679 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003680 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003681 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003682 << SourceRange(TheCall->getArg(2)->getLocStart(),
3683 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003684
John Wiegley01296292011-04-08 18:41:53 +00003685 ExprResult OrigArg0 = TheCall->getArg(0);
3686 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003687
Chris Lattner2da14fb2007-12-20 00:26:33 +00003688 // Do standard promotions between the two arguments, returning their common
3689 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003690 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003691 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3692 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003693
3694 // Make sure any conversions are pushed back into the call; this is
3695 // type safe since unordered compare builtins are declared as "_Bool
3696 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003697 TheCall->setArg(0, OrigArg0.get());
3698 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003699
John Wiegley01296292011-04-08 18:41:53 +00003700 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003701 return false;
3702
Chris Lattner2da14fb2007-12-20 00:26:33 +00003703 // If the common type isn't a real floating type, then the arguments were
3704 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003705 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00003706 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003707 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00003708 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3709 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003710
Chris Lattner2da14fb2007-12-20 00:26:33 +00003711 return false;
3712}
3713
Benjamin Kramer634fc102010-02-15 22:42:31 +00003714/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3715/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00003716/// to check everything. We expect the last argument to be a floating point
3717/// value.
3718bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3719 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00003720 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003721 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00003722 if (TheCall->getNumArgs() > NumArgs)
3723 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003724 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003725 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00003726 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003727 (*(TheCall->arg_end()-1))->getLocEnd());
3728
Benjamin Kramer64aae502010-02-16 10:07:31 +00003729 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00003730
Eli Friedman7e4faac2009-08-31 20:06:00 +00003731 if (OrigArg->isTypeDependent())
3732 return false;
3733
Chris Lattner68784ef2010-05-06 05:50:07 +00003734 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00003735 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00003736 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003737 diag::err_typecheck_call_invalid_unary_fp)
3738 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003739
Chris Lattner68784ef2010-05-06 05:50:07 +00003740 // If this is an implicit conversion from float -> double, remove it.
3741 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3742 Expr *CastArg = Cast->getSubExpr();
3743 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3744 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
3745 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00003746 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00003747 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00003748 }
3749 }
3750
Eli Friedman7e4faac2009-08-31 20:06:00 +00003751 return false;
3752}
3753
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003754/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3755// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00003756ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00003757 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003758 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00003759 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00003760 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3761 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003762
Nate Begemana0110022010-06-08 00:16:34 +00003763 // Determine which of the following types of shufflevector we're checking:
3764 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00003765 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00003766 QualType resType = TheCall->getArg(0)->getType();
3767 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00003768
Douglas Gregorc25f7662009-05-19 22:10:17 +00003769 if (!TheCall->getArg(0)->isTypeDependent() &&
3770 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00003771 QualType LHSType = TheCall->getArg(0)->getType();
3772 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00003773
Craig Topperbaca3892013-07-29 06:47:04 +00003774 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3775 return ExprError(Diag(TheCall->getLocStart(),
3776 diag::err_shufflevector_non_vector)
3777 << SourceRange(TheCall->getArg(0)->getLocStart(),
3778 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003779
Nate Begemana0110022010-06-08 00:16:34 +00003780 numElements = LHSType->getAs<VectorType>()->getNumElements();
3781 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00003782
Nate Begemana0110022010-06-08 00:16:34 +00003783 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3784 // with mask. If so, verify that RHS is an integer vector type with the
3785 // same number of elts as lhs.
3786 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00003787 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00003788 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00003789 return ExprError(Diag(TheCall->getLocStart(),
3790 diag::err_shufflevector_incompatible_vector)
3791 << SourceRange(TheCall->getArg(1)->getLocStart(),
3792 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003793 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00003794 return ExprError(Diag(TheCall->getLocStart(),
3795 diag::err_shufflevector_incompatible_vector)
3796 << SourceRange(TheCall->getArg(0)->getLocStart(),
3797 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00003798 } else if (numElements != numResElements) {
3799 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00003800 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003801 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003802 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003803 }
3804
3805 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00003806 if (TheCall->getArg(i)->isTypeDependent() ||
3807 TheCall->getArg(i)->isValueDependent())
3808 continue;
3809
Nate Begemana0110022010-06-08 00:16:34 +00003810 llvm::APSInt Result(32);
3811 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3812 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003813 diag::err_shufflevector_nonconstant_argument)
3814 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003815
Craig Topper50ad5b72013-08-03 17:40:38 +00003816 // Allow -1 which will be translated to undef in the IR.
3817 if (Result.isSigned() && Result.isAllOnesValue())
3818 continue;
3819
Chris Lattner7ab824e2008-08-10 02:05:13 +00003820 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003821 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003822 diag::err_shufflevector_argument_too_large)
3823 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003824 }
3825
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003826 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003827
Chris Lattner7ab824e2008-08-10 02:05:13 +00003828 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003829 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00003830 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003831 }
3832
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003833 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3834 TheCall->getCallee()->getLocStart(),
3835 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003836}
Chris Lattner43be2e62007-12-19 23:59:04 +00003837
Hal Finkelc4d7c822013-09-18 03:29:45 +00003838/// SemaConvertVectorExpr - Handle __builtin_convertvector
3839ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3840 SourceLocation BuiltinLoc,
3841 SourceLocation RParenLoc) {
3842 ExprValueKind VK = VK_RValue;
3843 ExprObjectKind OK = OK_Ordinary;
3844 QualType DstTy = TInfo->getType();
3845 QualType SrcTy = E->getType();
3846
3847 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3848 return ExprError(Diag(BuiltinLoc,
3849 diag::err_convertvector_non_vector)
3850 << E->getSourceRange());
3851 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3852 return ExprError(Diag(BuiltinLoc,
3853 diag::err_convertvector_non_vector_type));
3854
3855 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3856 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3857 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3858 if (SrcElts != DstElts)
3859 return ExprError(Diag(BuiltinLoc,
3860 diag::err_convertvector_incompatible_vector)
3861 << E->getSourceRange());
3862 }
3863
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003864 return new (Context)
3865 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003866}
3867
Daniel Dunbarb7257262008-07-21 22:59:13 +00003868/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3869// This is declared to take (const void*, ...) and can take two
3870// optional constant int args.
3871bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003872 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003873
Chris Lattner3b054132008-11-19 05:08:23 +00003874 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003875 return Diag(TheCall->getLocEnd(),
3876 diag::err_typecheck_call_too_many_args_at_most)
3877 << 0 /*function call*/ << 3 << NumArgs
3878 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003879
3880 // Argument 0 is checked for us and the remaining arguments must be
3881 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003882 for (unsigned i = 1; i != NumArgs; ++i)
3883 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003884 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003885
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003886 return false;
3887}
3888
Hal Finkelf0417332014-07-17 14:25:55 +00003889/// SemaBuiltinAssume - Handle __assume (MS Extension).
3890// __assume does not evaluate its arguments, and should warn if its argument
3891// has side effects.
3892bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3893 Expr *Arg = TheCall->getArg(0);
3894 if (Arg->isInstantiationDependent()) return false;
3895
3896 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003897 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003898 << Arg->getSourceRange()
3899 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3900
3901 return false;
3902}
3903
3904/// Handle __builtin_assume_aligned. This is declared
3905/// as (const void*, size_t, ...) and can take one optional constant int arg.
3906bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3907 unsigned NumArgs = TheCall->getNumArgs();
3908
3909 if (NumArgs > 3)
3910 return Diag(TheCall->getLocEnd(),
3911 diag::err_typecheck_call_too_many_args_at_most)
3912 << 0 /*function call*/ << 3 << NumArgs
3913 << TheCall->getSourceRange();
3914
3915 // The alignment must be a constant integer.
3916 Expr *Arg = TheCall->getArg(1);
3917
3918 // We can't check the value of a dependent argument.
3919 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3920 llvm::APSInt Result;
3921 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3922 return true;
3923
3924 if (!Result.isPowerOf2())
3925 return Diag(TheCall->getLocStart(),
3926 diag::err_alignment_not_power_of_two)
3927 << Arg->getSourceRange();
3928 }
3929
3930 if (NumArgs > 2) {
3931 ExprResult Arg(TheCall->getArg(2));
3932 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3933 Context.getSizeType(), false);
3934 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3935 if (Arg.isInvalid()) return true;
3936 TheCall->setArg(2, Arg.get());
3937 }
Hal Finkelf0417332014-07-17 14:25:55 +00003938
3939 return false;
3940}
3941
Eric Christopher8d0c6212010-04-17 02:26:23 +00003942/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3943/// TheCall is a constant expression.
3944bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3945 llvm::APSInt &Result) {
3946 Expr *Arg = TheCall->getArg(ArgNum);
3947 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3948 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3949
3950 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3951
3952 if (!Arg->isIntegerConstantExpr(Result, Context))
3953 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00003954 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00003955
Chris Lattnerd545ad12009-09-23 06:06:36 +00003956 return false;
3957}
3958
Richard Sandiford28940af2014-04-16 08:47:51 +00003959/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3960/// TheCall is a constant expression in the range [Low, High].
3961bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3962 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00003963 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003964
3965 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00003966 Expr *Arg = TheCall->getArg(ArgNum);
3967 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003968 return false;
3969
Eric Christopher8d0c6212010-04-17 02:26:23 +00003970 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00003971 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003972 return true;
3973
Richard Sandiford28940af2014-04-16 08:47:51 +00003974 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00003975 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00003976 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00003977
3978 return false;
3979}
3980
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003981/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
3982/// TheCall is a constant expression is a multiple of Num..
3983bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
3984 unsigned Num) {
3985 llvm::APSInt Result;
3986
3987 // We can't check the value of a dependent argument.
3988 Expr *Arg = TheCall->getArg(ArgNum);
3989 if (Arg->isTypeDependent() || Arg->isValueDependent())
3990 return false;
3991
3992 // Check constant-ness first.
3993 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3994 return true;
3995
3996 if (Result.getSExtValue() % Num != 0)
3997 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
3998 << Num << Arg->getSourceRange();
3999
4000 return false;
4001}
4002
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004003/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4004/// TheCall is an ARM/AArch64 special register string literal.
4005bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4006 int ArgNum, unsigned ExpectedFieldNum,
4007 bool AllowName) {
4008 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4009 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4010 BuiltinID == ARM::BI__builtin_arm_rsr ||
4011 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4012 BuiltinID == ARM::BI__builtin_arm_wsr ||
4013 BuiltinID == ARM::BI__builtin_arm_wsrp;
4014 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4015 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4016 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4017 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4018 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4019 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4020 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4021
4022 // We can't check the value of a dependent argument.
4023 Expr *Arg = TheCall->getArg(ArgNum);
4024 if (Arg->isTypeDependent() || Arg->isValueDependent())
4025 return false;
4026
4027 // Check if the argument is a string literal.
4028 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4029 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4030 << Arg->getSourceRange();
4031
4032 // Check the type of special register given.
4033 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4034 SmallVector<StringRef, 6> Fields;
4035 Reg.split(Fields, ":");
4036
4037 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4038 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4039 << Arg->getSourceRange();
4040
4041 // If the string is the name of a register then we cannot check that it is
4042 // valid here but if the string is of one the forms described in ACLE then we
4043 // can check that the supplied fields are integers and within the valid
4044 // ranges.
4045 if (Fields.size() > 1) {
4046 bool FiveFields = Fields.size() == 5;
4047
4048 bool ValidString = true;
4049 if (IsARMBuiltin) {
4050 ValidString &= Fields[0].startswith_lower("cp") ||
4051 Fields[0].startswith_lower("p");
4052 if (ValidString)
4053 Fields[0] =
4054 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4055
4056 ValidString &= Fields[2].startswith_lower("c");
4057 if (ValidString)
4058 Fields[2] = Fields[2].drop_front(1);
4059
4060 if (FiveFields) {
4061 ValidString &= Fields[3].startswith_lower("c");
4062 if (ValidString)
4063 Fields[3] = Fields[3].drop_front(1);
4064 }
4065 }
4066
4067 SmallVector<int, 5> Ranges;
4068 if (FiveFields)
4069 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
4070 else
4071 Ranges.append({15, 7, 15});
4072
4073 for (unsigned i=0; i<Fields.size(); ++i) {
4074 int IntField;
4075 ValidString &= !Fields[i].getAsInteger(10, IntField);
4076 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4077 }
4078
4079 if (!ValidString)
4080 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4081 << Arg->getSourceRange();
4082
4083 } else if (IsAArch64Builtin && Fields.size() == 1) {
4084 // If the register name is one of those that appear in the condition below
4085 // and the special register builtin being used is one of the write builtins,
4086 // then we require that the argument provided for writing to the register
4087 // is an integer constant expression. This is because it will be lowered to
4088 // an MSR (immediate) instruction, so we need to know the immediate at
4089 // compile time.
4090 if (TheCall->getNumArgs() != 2)
4091 return false;
4092
4093 std::string RegLower = Reg.lower();
4094 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4095 RegLower != "pan" && RegLower != "uao")
4096 return false;
4097
4098 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4099 }
4100
4101 return false;
4102}
4103
Eli Friedmanc97d0142009-05-03 06:04:26 +00004104/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004105/// This checks that the target supports __builtin_longjmp and
4106/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004107bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004108 if (!Context.getTargetInfo().hasSjLjLowering())
4109 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4110 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4111
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004112 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004113 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004114
Eric Christopher8d0c6212010-04-17 02:26:23 +00004115 // TODO: This is less than ideal. Overload this to take a value.
4116 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4117 return true;
4118
4119 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004120 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4121 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4122
4123 return false;
4124}
4125
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004126/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4127/// This checks that the target supports __builtin_setjmp.
4128bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4129 if (!Context.getTargetInfo().hasSjLjLowering())
4130 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4131 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4132 return false;
4133}
4134
Richard Smithd7293d72013-08-05 18:49:43 +00004135namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004136class UncoveredArgHandler {
4137 enum { Unknown = -1, AllCovered = -2 };
4138 signed FirstUncoveredArg;
4139 SmallVector<const Expr *, 4> DiagnosticExprs;
4140
4141public:
4142 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4143
4144 bool hasUncoveredArg() const {
4145 return (FirstUncoveredArg >= 0);
4146 }
4147
4148 unsigned getUncoveredArg() const {
4149 assert(hasUncoveredArg() && "no uncovered argument");
4150 return FirstUncoveredArg;
4151 }
4152
4153 void setAllCovered() {
4154 // A string has been found with all arguments covered, so clear out
4155 // the diagnostics.
4156 DiagnosticExprs.clear();
4157 FirstUncoveredArg = AllCovered;
4158 }
4159
4160 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4161 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4162
4163 // Don't update if a previous string covers all arguments.
4164 if (FirstUncoveredArg == AllCovered)
4165 return;
4166
4167 // UncoveredArgHandler tracks the highest uncovered argument index
4168 // and with it all the strings that match this index.
4169 if (NewFirstUncoveredArg == FirstUncoveredArg)
4170 DiagnosticExprs.push_back(StrExpr);
4171 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4172 DiagnosticExprs.clear();
4173 DiagnosticExprs.push_back(StrExpr);
4174 FirstUncoveredArg = NewFirstUncoveredArg;
4175 }
4176 }
4177
4178 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4179};
4180
Richard Smithd7293d72013-08-05 18:49:43 +00004181enum StringLiteralCheckType {
4182 SLCT_NotALiteral,
4183 SLCT_UncheckedLiteral,
4184 SLCT_CheckedLiteral
4185};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004186} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00004187
Stephen Hines648c3692016-09-16 01:07:04 +00004188static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4189 BinaryOperatorKind BinOpKind,
4190 bool AddendIsRight) {
4191 unsigned BitWidth = Offset.getBitWidth();
4192 unsigned AddendBitWidth = Addend.getBitWidth();
4193 // There might be negative interim results.
4194 if (Addend.isUnsigned()) {
4195 Addend = Addend.zext(++AddendBitWidth);
4196 Addend.setIsSigned(true);
4197 }
4198 // Adjust the bit width of the APSInts.
4199 if (AddendBitWidth > BitWidth) {
4200 Offset = Offset.sext(AddendBitWidth);
4201 BitWidth = AddendBitWidth;
4202 } else if (BitWidth > AddendBitWidth) {
4203 Addend = Addend.sext(BitWidth);
4204 }
4205
4206 bool Ov = false;
4207 llvm::APSInt ResOffset = Offset;
4208 if (BinOpKind == BO_Add)
4209 ResOffset = Offset.sadd_ov(Addend, Ov);
4210 else {
4211 assert(AddendIsRight && BinOpKind == BO_Sub &&
4212 "operator must be add or sub with addend on the right");
4213 ResOffset = Offset.ssub_ov(Addend, Ov);
4214 }
4215
4216 // We add an offset to a pointer here so we should support an offset as big as
4217 // possible.
4218 if (Ov) {
4219 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00004220 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00004221 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4222 return;
4223 }
4224
4225 Offset = ResOffset;
4226}
4227
4228namespace {
4229// This is a wrapper class around StringLiteral to support offsetted string
4230// literals as format strings. It takes the offset into account when returning
4231// the string and its length or the source locations to display notes correctly.
4232class FormatStringLiteral {
4233 const StringLiteral *FExpr;
4234 int64_t Offset;
4235
4236 public:
4237 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4238 : FExpr(fexpr), Offset(Offset) {}
4239
4240 StringRef getString() const {
4241 return FExpr->getString().drop_front(Offset);
4242 }
4243
4244 unsigned getByteLength() const {
4245 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4246 }
4247 unsigned getLength() const { return FExpr->getLength() - Offset; }
4248 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4249
4250 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4251
4252 QualType getType() const { return FExpr->getType(); }
4253
4254 bool isAscii() const { return FExpr->isAscii(); }
4255 bool isWide() const { return FExpr->isWide(); }
4256 bool isUTF8() const { return FExpr->isUTF8(); }
4257 bool isUTF16() const { return FExpr->isUTF16(); }
4258 bool isUTF32() const { return FExpr->isUTF32(); }
4259 bool isPascal() const { return FExpr->isPascal(); }
4260
4261 SourceLocation getLocationOfByte(
4262 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4263 const TargetInfo &Target, unsigned *StartToken = nullptr,
4264 unsigned *StartTokenByteOffset = nullptr) const {
4265 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4266 StartToken, StartTokenByteOffset);
4267 }
4268
4269 SourceLocation getLocStart() const LLVM_READONLY {
4270 return FExpr->getLocStart().getLocWithOffset(Offset);
4271 }
4272 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4273};
4274} // end anonymous namespace
4275
4276static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004277 const Expr *OrigFormatExpr,
4278 ArrayRef<const Expr *> Args,
4279 bool HasVAListArg, unsigned format_idx,
4280 unsigned firstDataArg,
4281 Sema::FormatStringType Type,
4282 bool inFunctionCall,
4283 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004284 llvm::SmallBitVector &CheckedVarArgs,
4285 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004286
Richard Smith55ce3522012-06-25 20:30:08 +00004287// Determine if an expression is a string literal or constant string.
4288// If this function returns false on the arguments to a function expecting a
4289// format string, we will usually need to emit a warning.
4290// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00004291static StringLiteralCheckType
4292checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4293 bool HasVAListArg, unsigned format_idx,
4294 unsigned firstDataArg, Sema::FormatStringType Type,
4295 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004296 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004297 UncoveredArgHandler &UncoveredArg,
4298 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00004299 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00004300 assert(Offset.isSigned() && "invalid offset");
4301
Douglas Gregorc25f7662009-05-19 22:10:17 +00004302 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00004303 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004304
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004305 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00004306
Richard Smithd7293d72013-08-05 18:49:43 +00004307 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00004308 // Technically -Wformat-nonliteral does not warn about this case.
4309 // The behavior of printf and friends in this case is implementation
4310 // dependent. Ideally if the format string cannot be null then
4311 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00004312 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00004313
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004314 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00004315 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004316 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00004317 // The expression is a literal if both sub-expressions were, and it was
4318 // completely checked only if both sub-expressions were checked.
4319 const AbstractConditionalOperator *C =
4320 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004321
4322 // Determine whether it is necessary to check both sub-expressions, for
4323 // example, because the condition expression is a constant that can be
4324 // evaluated at compile time.
4325 bool CheckLeft = true, CheckRight = true;
4326
4327 bool Cond;
4328 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4329 if (Cond)
4330 CheckRight = false;
4331 else
4332 CheckLeft = false;
4333 }
4334
Stephen Hines648c3692016-09-16 01:07:04 +00004335 // We need to maintain the offsets for the right and the left hand side
4336 // separately to check if every possible indexed expression is a valid
4337 // string literal. They might have different offsets for different string
4338 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004339 StringLiteralCheckType Left;
4340 if (!CheckLeft)
4341 Left = SLCT_UncheckedLiteral;
4342 else {
4343 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4344 HasVAListArg, format_idx, firstDataArg,
4345 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004346 CheckedVarArgs, UncoveredArg, Offset);
4347 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004348 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004349 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004350 }
4351
Richard Smith55ce3522012-06-25 20:30:08 +00004352 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004353 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004354 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004355 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004356 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004357
4358 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004359 }
4360
4361 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00004362 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4363 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004364 }
4365
John McCallc07a0c72011-02-17 10:25:35 +00004366 case Stmt::OpaqueValueExprClass:
4367 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4368 E = src;
4369 goto tryAgain;
4370 }
Richard Smith55ce3522012-06-25 20:30:08 +00004371 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004372
Ted Kremeneka8890832011-02-24 23:03:04 +00004373 case Stmt::PredefinedExprClass:
4374 // While __func__, etc., are technically not string literals, they
4375 // cannot contain format specifiers and thus are not a security
4376 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004377 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004378
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004379 case Stmt::DeclRefExprClass: {
4380 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004381
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004382 // As an exception, do not flag errors for variables binding to
4383 // const string literals.
4384 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4385 bool isConstant = false;
4386 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004387
Richard Smithd7293d72013-08-05 18:49:43 +00004388 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4389 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004390 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004391 isConstant = T.isConstant(S.Context) &&
4392 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004393 } else if (T->isObjCObjectPointerType()) {
4394 // In ObjC, there is usually no "const ObjectPointer" type,
4395 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004396 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004397 }
Mike Stump11289f42009-09-09 15:08:12 +00004398
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004399 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004400 if (const Expr *Init = VD->getAnyInitializer()) {
4401 // Look through initializers like const char c[] = { "foo" }
4402 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4403 if (InitList->isStringLiteralInit())
4404 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4405 }
Richard Smithd7293d72013-08-05 18:49:43 +00004406 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004407 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004408 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004409 /*InFunctionCall*/ false, CheckedVarArgs,
4410 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004411 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004412 }
Mike Stump11289f42009-09-09 15:08:12 +00004413
Anders Carlssonb012ca92009-06-28 19:55:58 +00004414 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4415 // special check to see if the format string is a function parameter
4416 // of the function calling the printf function. If the function
4417 // has an attribute indicating it is a printf-like function, then we
4418 // should suppress warnings concerning non-literals being used in a call
4419 // to a vprintf function. For example:
4420 //
4421 // void
4422 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4423 // va_list ap;
4424 // va_start(ap, fmt);
4425 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4426 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00004427 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004428 if (HasVAListArg) {
4429 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4430 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4431 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004432 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004433 // adjust for implicit parameter
4434 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4435 if (MD->isInstance())
4436 ++PVIndex;
4437 // We also check if the formats are compatible.
4438 // We can't pass a 'scanf' string to a 'printf' function.
4439 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00004440 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00004441 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004442 }
4443 }
4444 }
4445 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004446 }
Mike Stump11289f42009-09-09 15:08:12 +00004447
Richard Smith55ce3522012-06-25 20:30:08 +00004448 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004449 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004450
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004451 case Stmt::CallExprClass:
4452 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004453 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004454 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4455 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4456 unsigned ArgIndex = FA->getFormatIdx();
4457 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4458 if (MD->isInstance())
4459 --ArgIndex;
4460 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00004461
Richard Smithd7293d72013-08-05 18:49:43 +00004462 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004463 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00004464 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004465 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004466 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4467 unsigned BuiltinID = FD->getBuiltinID();
4468 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4469 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4470 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00004471 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004472 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004473 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004474 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004475 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004476 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004477 }
4478 }
Mike Stump11289f42009-09-09 15:08:12 +00004479
Richard Smith55ce3522012-06-25 20:30:08 +00004480 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004481 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004482 case Stmt::ObjCStringLiteralClass:
4483 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00004484 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004485
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004486 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004487 StrE = ObjCFExpr->getString();
4488 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004489 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004490
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004491 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00004492 if (Offset.isNegative() || Offset > StrE->getLength()) {
4493 // TODO: It would be better to have an explicit warning for out of
4494 // bounds literals.
4495 return SLCT_NotALiteral;
4496 }
4497 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4498 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004499 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004500 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00004501 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004502 }
Mike Stump11289f42009-09-09 15:08:12 +00004503
Richard Smith55ce3522012-06-25 20:30:08 +00004504 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004505 }
Stephen Hines648c3692016-09-16 01:07:04 +00004506 case Stmt::BinaryOperatorClass: {
4507 llvm::APSInt LResult;
4508 llvm::APSInt RResult;
4509
4510 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4511
4512 // A string literal + an int offset is still a string literal.
4513 if (BinOp->isAdditiveOp()) {
4514 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4515 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4516
4517 if (LIsInt != RIsInt) {
4518 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4519
4520 if (LIsInt) {
4521 if (BinOpKind == BO_Add) {
4522 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4523 E = BinOp->getRHS();
4524 goto tryAgain;
4525 }
4526 } else {
4527 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4528 E = BinOp->getLHS();
4529 goto tryAgain;
4530 }
4531 }
Stephen Hines648c3692016-09-16 01:07:04 +00004532 }
George Burgess IVd273aab2016-09-22 00:00:26 +00004533
4534 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00004535 }
4536 case Stmt::UnaryOperatorClass: {
4537 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4538 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4539 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4540 llvm::APSInt IndexResult;
4541 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4542 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4543 E = ASE->getBase();
4544 goto tryAgain;
4545 }
4546 }
4547
4548 return SLCT_NotALiteral;
4549 }
Mike Stump11289f42009-09-09 15:08:12 +00004550
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004551 default:
Richard Smith55ce3522012-06-25 20:30:08 +00004552 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004553 }
4554}
4555
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004556Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00004557 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004558 .Case("scanf", FST_Scanf)
4559 .Cases("printf", "printf0", FST_Printf)
4560 .Cases("NSString", "CFString", FST_NSString)
4561 .Case("strftime", FST_Strftime)
4562 .Case("strfmon", FST_Strfmon)
4563 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004564 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004565 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004566 .Default(FST_Unknown);
4567}
4568
Jordan Rose3e0ec582012-07-19 18:10:23 +00004569/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00004570/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00004571/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004572bool Sema::CheckFormatArguments(const FormatAttr *Format,
4573 ArrayRef<const Expr *> Args,
4574 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004575 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004576 SourceLocation Loc, SourceRange Range,
4577 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00004578 FormatStringInfo FSI;
4579 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004580 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00004581 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00004582 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00004583 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004584}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00004585
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004586bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004587 bool HasVAListArg, unsigned format_idx,
4588 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004589 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004590 SourceLocation Loc, SourceRange Range,
4591 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004592 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004593 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004594 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00004595 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004596 }
Mike Stump11289f42009-09-09 15:08:12 +00004597
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004598 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004599
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004600 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00004601 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004602 // Dynamically generated format strings are difficult to
4603 // automatically vet at compile time. Requiring that format strings
4604 // are string literals: (1) permits the checking of format strings by
4605 // the compiler and thereby (2) can practically remove the source of
4606 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00004607
Mike Stump11289f42009-09-09 15:08:12 +00004608 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00004609 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00004610 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00004611 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004612 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00004613 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00004614 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4615 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004616 /*IsFunctionCall*/ true, CheckedVarArgs,
4617 UncoveredArg,
4618 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004619
4620 // Generate a diagnostic where an uncovered argument is detected.
4621 if (UncoveredArg.hasUncoveredArg()) {
4622 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4623 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4624 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4625 }
4626
Richard Smith55ce3522012-06-25 20:30:08 +00004627 if (CT != SLCT_NotALiteral)
4628 // Literal format string found, check done!
4629 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00004630
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004631 // Strftime is particular as it always uses a single 'time' argument,
4632 // so it is safe to pass a non-literal string.
4633 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00004634 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004635
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004636 // Do not emit diag when the string param is a macro expansion and the
4637 // format is either NSString or CFString. This is a hack to prevent
4638 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4639 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004640 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4641 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00004642 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004643
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004644 // If there are no arguments specified, warn with -Wformat-security, otherwise
4645 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004646 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00004647 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4648 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004649 switch (Type) {
4650 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004651 break;
4652 case FST_Kprintf:
4653 case FST_FreeBSDKPrintf:
4654 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00004655 Diag(FormatLoc, diag::note_format_security_fixit)
4656 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004657 break;
4658 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00004659 Diag(FormatLoc, diag::note_format_security_fixit)
4660 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004661 break;
4662 }
4663 } else {
4664 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004665 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004666 }
Richard Smith55ce3522012-06-25 20:30:08 +00004667 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004668}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004669
Ted Kremenekab278de2010-01-28 23:39:18 +00004670namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00004671class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4672protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00004673 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00004674 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00004675 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00004676 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00004677 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00004678 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00004679 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004680 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00004681 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00004682 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00004683 bool usesPositionalArgs;
4684 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004685 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00004686 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00004687 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004688 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004689
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004690public:
Stephen Hines648c3692016-09-16 01:07:04 +00004691 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00004692 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004693 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004694 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004695 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004696 Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004697 llvm::SmallBitVector &CheckedVarArgs,
4698 UncoveredArgHandler &UncoveredArg)
Ted Kremenekab278de2010-01-28 23:39:18 +00004699 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004700 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
4701 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004702 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00004703 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00004704 inFunctionCall(inFunctionCall), CallType(callType),
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004705 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00004706 CoveredArgs.resize(numDataArgs);
4707 CoveredArgs.reset();
4708 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004709
Ted Kremenek019d2242010-01-29 01:50:07 +00004710 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004711
Ted Kremenek02087932010-07-16 02:11:22 +00004712 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004713 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004714
Jordan Rose92303592012-09-08 04:00:03 +00004715 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004716 const analyze_format_string::FormatSpecifier &FS,
4717 const analyze_format_string::ConversionSpecifier &CS,
4718 const char *startSpecifier, unsigned specifierLen,
4719 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00004720
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004721 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004722 const analyze_format_string::FormatSpecifier &FS,
4723 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004724
4725 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004726 const analyze_format_string::ConversionSpecifier &CS,
4727 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004728
Craig Toppere14c0f82014-03-12 04:55:44 +00004729 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004730
Craig Toppere14c0f82014-03-12 04:55:44 +00004731 void HandleInvalidPosition(const char *startSpecifier,
4732 unsigned specifierLen,
4733 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004734
Craig Toppere14c0f82014-03-12 04:55:44 +00004735 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004736
Craig Toppere14c0f82014-03-12 04:55:44 +00004737 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004738
Richard Trieu03cf7b72011-10-28 00:41:25 +00004739 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00004740 static void
4741 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4742 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4743 bool IsStringLocation, Range StringRange,
4744 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004745
Ted Kremenek02087932010-07-16 02:11:22 +00004746protected:
Ted Kremenekce815422010-07-19 21:25:57 +00004747 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4748 const char *startSpec,
4749 unsigned specifierLen,
4750 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004751
4752 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4753 const char *startSpec,
4754 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00004755
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004756 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00004757 CharSourceRange getSpecifierRange(const char *startSpecifier,
4758 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00004759 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004760
Ted Kremenek5739de72010-01-29 01:06:55 +00004761 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004762
4763 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4764 const analyze_format_string::ConversionSpecifier &CS,
4765 const char *startSpecifier, unsigned specifierLen,
4766 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004767
4768 template <typename Range>
4769 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4770 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004771 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00004772};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004773} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004774
Ted Kremenek02087932010-07-16 02:11:22 +00004775SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00004776 return OrigFormatExpr->getSourceRange();
4777}
4778
Ted Kremenek02087932010-07-16 02:11:22 +00004779CharSourceRange CheckFormatHandler::
4780getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00004781 SourceLocation Start = getLocationOfByte(startSpecifier);
4782 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
4783
4784 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004785 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00004786
4787 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004788}
4789
Ted Kremenek02087932010-07-16 02:11:22 +00004790SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00004791 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
4792 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00004793}
4794
Ted Kremenek02087932010-07-16 02:11:22 +00004795void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4796 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00004797 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4798 getLocationOfByte(startSpecifier),
4799 /*IsStringLocation*/true,
4800 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00004801}
4802
Jordan Rose92303592012-09-08 04:00:03 +00004803void CheckFormatHandler::HandleInvalidLengthModifier(
4804 const analyze_format_string::FormatSpecifier &FS,
4805 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00004806 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00004807 using namespace analyze_format_string;
4808
4809 const LengthModifier &LM = FS.getLengthModifier();
4810 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4811
4812 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004813 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00004814 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004815 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004816 getLocationOfByte(LM.getStart()),
4817 /*IsStringLocation*/true,
4818 getSpecifierRange(startSpecifier, specifierLen));
4819
4820 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4821 << FixedLM->toString()
4822 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4823
4824 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004825 FixItHint Hint;
4826 if (DiagID == diag::warn_format_nonsensical_length)
4827 Hint = FixItHint::CreateRemoval(LMRange);
4828
4829 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004830 getLocationOfByte(LM.getStart()),
4831 /*IsStringLocation*/true,
4832 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00004833 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00004834 }
4835}
4836
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004837void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00004838 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004839 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004840 using namespace analyze_format_string;
4841
4842 const LengthModifier &LM = FS.getLengthModifier();
4843 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4844
4845 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004846 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00004847 if (FixedLM) {
4848 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4849 << LM.toString() << 0,
4850 getLocationOfByte(LM.getStart()),
4851 /*IsStringLocation*/true,
4852 getSpecifierRange(startSpecifier, specifierLen));
4853
4854 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4855 << FixedLM->toString()
4856 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4857
4858 } else {
4859 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4860 << LM.toString() << 0,
4861 getLocationOfByte(LM.getStart()),
4862 /*IsStringLocation*/true,
4863 getSpecifierRange(startSpecifier, specifierLen));
4864 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004865}
4866
4867void CheckFormatHandler::HandleNonStandardConversionSpecifier(
4868 const analyze_format_string::ConversionSpecifier &CS,
4869 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00004870 using namespace analyze_format_string;
4871
4872 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00004873 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00004874 if (FixedCS) {
4875 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4876 << CS.toString() << /*conversion specifier*/1,
4877 getLocationOfByte(CS.getStart()),
4878 /*IsStringLocation*/true,
4879 getSpecifierRange(startSpecifier, specifierLen));
4880
4881 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
4882 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
4883 << FixedCS->toString()
4884 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
4885 } else {
4886 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4887 << CS.toString() << /*conversion specifier*/1,
4888 getLocationOfByte(CS.getStart()),
4889 /*IsStringLocation*/true,
4890 getSpecifierRange(startSpecifier, specifierLen));
4891 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004892}
4893
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004894void CheckFormatHandler::HandlePosition(const char *startPos,
4895 unsigned posLen) {
4896 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
4897 getLocationOfByte(startPos),
4898 /*IsStringLocation*/true,
4899 getSpecifierRange(startPos, posLen));
4900}
4901
Ted Kremenekd1668192010-02-27 01:41:03 +00004902void
Ted Kremenek02087932010-07-16 02:11:22 +00004903CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
4904 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004905 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
4906 << (unsigned) p,
4907 getLocationOfByte(startPos), /*IsStringLocation*/true,
4908 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00004909}
4910
Ted Kremenek02087932010-07-16 02:11:22 +00004911void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00004912 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004913 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
4914 getLocationOfByte(startPos),
4915 /*IsStringLocation*/true,
4916 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00004917}
4918
Ted Kremenek02087932010-07-16 02:11:22 +00004919void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004920 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00004921 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004922 EmitFormatDiagnostic(
4923 S.PDiag(diag::warn_printf_format_string_contains_null_char),
4924 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
4925 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00004926 }
Ted Kremenek02087932010-07-16 02:11:22 +00004927}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004928
Jordan Rose58bbe422012-07-19 18:10:08 +00004929// Note that this may return NULL if there was an error parsing or building
4930// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00004931const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004932 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00004933}
4934
4935void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004936 // Does the number of data arguments exceed the number of
4937 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00004938 if (!HasVAListArg) {
4939 // Find any arguments that weren't covered.
4940 CoveredArgs.flip();
4941 signed notCoveredArg = CoveredArgs.find_first();
4942 if (notCoveredArg >= 0) {
4943 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004944 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
4945 } else {
4946 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00004947 }
4948 }
4949}
4950
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004951void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
4952 const Expr *ArgExpr) {
4953 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
4954 "Invalid state");
4955
4956 if (!ArgExpr)
4957 return;
4958
4959 SourceLocation Loc = ArgExpr->getLocStart();
4960
4961 if (S.getSourceManager().isInSystemMacro(Loc))
4962 return;
4963
4964 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
4965 for (auto E : DiagnosticExprs)
4966 PDiag << E->getSourceRange();
4967
4968 CheckFormatHandler::EmitFormatDiagnostic(
4969 S, IsFunctionCall, DiagnosticExprs[0],
4970 PDiag, Loc, /*IsStringLocation*/false,
4971 DiagnosticExprs[0]->getSourceRange());
4972}
4973
Ted Kremenekce815422010-07-19 21:25:57 +00004974bool
4975CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
4976 SourceLocation Loc,
4977 const char *startSpec,
4978 unsigned specifierLen,
4979 const char *csStart,
4980 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00004981 bool keepGoing = true;
4982 if (argIndex < NumDataArgs) {
4983 // Consider the argument coverered, even though the specifier doesn't
4984 // make sense.
4985 CoveredArgs.set(argIndex);
4986 }
4987 else {
4988 // If argIndex exceeds the number of data arguments we
4989 // don't issue a warning because that is just a cascade of warnings (and
4990 // they may have intended '%%' anyway). We don't want to continue processing
4991 // the format string after this point, however, as we will like just get
4992 // gibberish when trying to match arguments.
4993 keepGoing = false;
4994 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00004995
4996 StringRef Specifier(csStart, csLen);
4997
4998 // If the specifier in non-printable, it could be the first byte of a UTF-8
4999 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5000 // hex value.
5001 std::string CodePointStr;
5002 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005003 llvm::UTF32 CodePoint;
5004 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5005 const llvm::UTF8 *E =
5006 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5007 llvm::ConversionResult Result =
5008 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005009
Justin Lebar90910552016-09-30 00:38:45 +00005010 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005011 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005012 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005013 }
5014
5015 llvm::raw_string_ostream OS(CodePointStr);
5016 if (CodePoint < 256)
5017 OS << "\\x" << llvm::format("%02x", CodePoint);
5018 else if (CodePoint <= 0xFFFF)
5019 OS << "\\u" << llvm::format("%04x", CodePoint);
5020 else
5021 OS << "\\U" << llvm::format("%08x", CodePoint);
5022 OS.flush();
5023 Specifier = CodePointStr;
5024 }
5025
5026 EmitFormatDiagnostic(
5027 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5028 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5029
Ted Kremenekce815422010-07-19 21:25:57 +00005030 return keepGoing;
5031}
5032
Richard Trieu03cf7b72011-10-28 00:41:25 +00005033void
5034CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5035 const char *startSpec,
5036 unsigned specifierLen) {
5037 EmitFormatDiagnostic(
5038 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5039 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5040}
5041
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005042bool
5043CheckFormatHandler::CheckNumArgs(
5044 const analyze_format_string::FormatSpecifier &FS,
5045 const analyze_format_string::ConversionSpecifier &CS,
5046 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5047
5048 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005049 PartialDiagnostic PDiag = FS.usesPositionalArg()
5050 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5051 << (argIndex+1) << NumDataArgs)
5052 : S.PDiag(diag::warn_printf_insufficient_data_args);
5053 EmitFormatDiagnostic(
5054 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5055 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005056
5057 // Since more arguments than conversion tokens are given, by extension
5058 // all arguments are covered, so mark this as so.
5059 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005060 return false;
5061 }
5062 return true;
5063}
5064
Richard Trieu03cf7b72011-10-28 00:41:25 +00005065template<typename Range>
5066void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5067 SourceLocation Loc,
5068 bool IsStringLocation,
5069 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005070 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005071 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005072 Loc, IsStringLocation, StringRange, FixIt);
5073}
5074
5075/// \brief If the format string is not within the funcion call, emit a note
5076/// so that the function call and string are in diagnostic messages.
5077///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005078/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005079/// call and only one diagnostic message will be produced. Otherwise, an
5080/// extra note will be emitted pointing to location of the format string.
5081///
5082/// \param ArgumentExpr the expression that is passed as the format string
5083/// argument in the function call. Used for getting locations when two
5084/// diagnostics are emitted.
5085///
5086/// \param PDiag the callee should already have provided any strings for the
5087/// diagnostic message. This function only adds locations and fixits
5088/// to diagnostics.
5089///
5090/// \param Loc primary location for diagnostic. If two diagnostics are
5091/// required, one will be at Loc and a new SourceLocation will be created for
5092/// the other one.
5093///
5094/// \param IsStringLocation if true, Loc points to the format string should be
5095/// used for the note. Otherwise, Loc points to the argument list and will
5096/// be used with PDiag.
5097///
5098/// \param StringRange some or all of the string to highlight. This is
5099/// templated so it can accept either a CharSourceRange or a SourceRange.
5100///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005101/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005102template <typename Range>
5103void CheckFormatHandler::EmitFormatDiagnostic(
5104 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5105 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5106 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005107 if (InFunctionCall) {
5108 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5109 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005110 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00005111 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005112 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5113 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00005114
5115 const Sema::SemaDiagnosticBuilder &Note =
5116 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5117 diag::note_format_string_defined);
5118
5119 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005120 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005121 }
5122}
5123
Ted Kremenek02087932010-07-16 02:11:22 +00005124//===--- CHECK: Printf format string checking ------------------------------===//
5125
5126namespace {
5127class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005128 bool ObjCContext;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005129
Ted Kremenek02087932010-07-16 02:11:22 +00005130public:
Stephen Hines648c3692016-09-16 01:07:04 +00005131 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Ted Kremenek02087932010-07-16 02:11:22 +00005132 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005133 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00005134 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005135 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005136 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005137 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005138 llvm::SmallBitVector &CheckedVarArgs,
5139 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00005140 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
5141 numDataArgs, beg, hasVAListArg, Args,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005142 formatIdx, inFunctionCall, CallType, CheckedVarArgs,
5143 UncoveredArg),
Richard Smithd7293d72013-08-05 18:49:43 +00005144 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00005145 {}
5146
Ted Kremenek02087932010-07-16 02:11:22 +00005147 bool HandleInvalidPrintfConversionSpecifier(
5148 const analyze_printf::PrintfSpecifier &FS,
5149 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005150 unsigned specifierLen) override;
5151
Ted Kremenek02087932010-07-16 02:11:22 +00005152 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5153 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005154 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005155 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5156 const char *StartSpecifier,
5157 unsigned SpecifierLen,
5158 const Expr *E);
5159
Ted Kremenek02087932010-07-16 02:11:22 +00005160 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5161 const char *startSpecifier, unsigned specifierLen);
5162 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5163 const analyze_printf::OptionalAmount &Amt,
5164 unsigned type,
5165 const char *startSpecifier, unsigned specifierLen);
5166 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5167 const analyze_printf::OptionalFlag &flag,
5168 const char *startSpecifier, unsigned specifierLen);
5169 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5170 const analyze_printf::OptionalFlag &ignoredFlag,
5171 const analyze_printf::OptionalFlag &flag,
5172 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005173 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00005174 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00005175
5176 void HandleEmptyObjCModifierFlag(const char *startFlag,
5177 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005178
Ted Kremenek2b417712015-07-02 05:39:16 +00005179 void HandleInvalidObjCModifierFlag(const char *startFlag,
5180 unsigned flagLen) override;
5181
5182 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5183 const char *flagsEnd,
5184 const char *conversionPosition)
5185 override;
5186};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005187} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00005188
5189bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5190 const analyze_printf::PrintfSpecifier &FS,
5191 const char *startSpecifier,
5192 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005193 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005194 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005195
Ted Kremenekce815422010-07-19 21:25:57 +00005196 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5197 getLocationOfByte(CS.getStart()),
5198 startSpecifier, specifierLen,
5199 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00005200}
5201
Ted Kremenek02087932010-07-16 02:11:22 +00005202bool CheckPrintfHandler::HandleAmount(
5203 const analyze_format_string::OptionalAmount &Amt,
5204 unsigned k, const char *startSpecifier,
5205 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005206 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005207 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00005208 unsigned argIndex = Amt.getArgIndex();
5209 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005210 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5211 << k,
5212 getLocationOfByte(Amt.getStart()),
5213 /*IsStringLocation*/true,
5214 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005215 // Don't do any more checking. We will just emit
5216 // spurious errors.
5217 return false;
5218 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005219
Ted Kremenek5739de72010-01-29 01:06:55 +00005220 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00005221 // Although not in conformance with C99, we also allow the argument to be
5222 // an 'unsigned int' as that is a reasonably safe case. GCC also
5223 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00005224 CoveredArgs.set(argIndex);
5225 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005226 if (!Arg)
5227 return false;
5228
Ted Kremenek5739de72010-01-29 01:06:55 +00005229 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005230
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005231 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5232 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005233
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005234 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005235 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005236 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00005237 << T << Arg->getSourceRange(),
5238 getLocationOfByte(Amt.getStart()),
5239 /*IsStringLocation*/true,
5240 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005241 // Don't do any more checking. We will just emit
5242 // spurious errors.
5243 return false;
5244 }
5245 }
5246 }
5247 return true;
5248}
Ted Kremenek5739de72010-01-29 01:06:55 +00005249
Tom Careb49ec692010-06-17 19:00:27 +00005250void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00005251 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005252 const analyze_printf::OptionalAmount &Amt,
5253 unsigned type,
5254 const char *startSpecifier,
5255 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005256 const analyze_printf::PrintfConversionSpecifier &CS =
5257 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00005258
Richard Trieu03cf7b72011-10-28 00:41:25 +00005259 FixItHint fixit =
5260 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5261 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5262 Amt.getConstantLength()))
5263 : FixItHint();
5264
5265 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5266 << type << CS.toString(),
5267 getLocationOfByte(Amt.getStart()),
5268 /*IsStringLocation*/true,
5269 getSpecifierRange(startSpecifier, specifierLen),
5270 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00005271}
5272
Ted Kremenek02087932010-07-16 02:11:22 +00005273void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005274 const analyze_printf::OptionalFlag &flag,
5275 const char *startSpecifier,
5276 unsigned specifierLen) {
5277 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005278 const analyze_printf::PrintfConversionSpecifier &CS =
5279 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00005280 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5281 << flag.toString() << CS.toString(),
5282 getLocationOfByte(flag.getPosition()),
5283 /*IsStringLocation*/true,
5284 getSpecifierRange(startSpecifier, specifierLen),
5285 FixItHint::CreateRemoval(
5286 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005287}
5288
5289void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00005290 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005291 const analyze_printf::OptionalFlag &ignoredFlag,
5292 const analyze_printf::OptionalFlag &flag,
5293 const char *startSpecifier,
5294 unsigned specifierLen) {
5295 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005296 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5297 << ignoredFlag.toString() << flag.toString(),
5298 getLocationOfByte(ignoredFlag.getPosition()),
5299 /*IsStringLocation*/true,
5300 getSpecifierRange(startSpecifier, specifierLen),
5301 FixItHint::CreateRemoval(
5302 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005303}
5304
Ted Kremenek2b417712015-07-02 05:39:16 +00005305// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5306// bool IsStringLocation, Range StringRange,
5307// ArrayRef<FixItHint> Fixit = None);
5308
5309void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5310 unsigned flagLen) {
5311 // Warn about an empty flag.
5312 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5313 getLocationOfByte(startFlag),
5314 /*IsStringLocation*/true,
5315 getSpecifierRange(startFlag, flagLen));
5316}
5317
5318void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5319 unsigned flagLen) {
5320 // Warn about an invalid flag.
5321 auto Range = getSpecifierRange(startFlag, flagLen);
5322 StringRef flag(startFlag, flagLen);
5323 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5324 getLocationOfByte(startFlag),
5325 /*IsStringLocation*/true,
5326 Range, FixItHint::CreateRemoval(Range));
5327}
5328
5329void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5330 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5331 // Warn about using '[...]' without a '@' conversion.
5332 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5333 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5334 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5335 getLocationOfByte(conversionPosition),
5336 /*IsStringLocation*/true,
5337 Range, FixItHint::CreateRemoval(Range));
5338}
5339
Richard Smith55ce3522012-06-25 20:30:08 +00005340// Determines if the specified is a C++ class or struct containing
5341// a member with the specified name and kind (e.g. a CXXMethodDecl named
5342// "c_str()").
5343template<typename MemberKind>
5344static llvm::SmallPtrSet<MemberKind*, 1>
5345CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5346 const RecordType *RT = Ty->getAs<RecordType>();
5347 llvm::SmallPtrSet<MemberKind*, 1> Results;
5348
5349 if (!RT)
5350 return Results;
5351 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005352 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005353 return Results;
5354
Alp Tokerb6cc5922014-05-03 03:45:55 +00005355 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005356 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005357 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005358
5359 // We just need to include all members of the right kind turned up by the
5360 // filter, at this point.
5361 if (S.LookupQualifiedName(R, RT->getDecl()))
5362 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5363 NamedDecl *decl = (*I)->getUnderlyingDecl();
5364 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5365 Results.insert(FK);
5366 }
5367 return Results;
5368}
5369
Richard Smith2868a732014-02-28 01:36:39 +00005370/// Check if we could call '.c_str()' on an object.
5371///
5372/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5373/// allow the call, or if it would be ambiguous).
5374bool Sema::hasCStrMethod(const Expr *E) {
5375 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5376 MethodSet Results =
5377 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5378 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5379 MI != ME; ++MI)
5380 if ((*MI)->getMinRequiredArguments() == 0)
5381 return true;
5382 return false;
5383}
5384
Richard Smith55ce3522012-06-25 20:30:08 +00005385// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005386// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00005387// Returns true when a c_str() conversion method is found.
5388bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00005389 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00005390 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5391
5392 MethodSet Results =
5393 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5394
5395 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5396 MI != ME; ++MI) {
5397 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00005398 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00005399 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00005400 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00005401 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00005402 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5403 << "c_str()"
5404 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5405 return true;
5406 }
5407 }
5408
5409 return false;
5410}
5411
Ted Kremenekab278de2010-01-28 23:39:18 +00005412bool
Ted Kremenek02087932010-07-16 02:11:22 +00005413CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00005414 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00005415 const char *startSpecifier,
5416 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005417 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00005418 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005419 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00005420
Ted Kremenek6cd69422010-07-19 22:01:06 +00005421 if (FS.consumesDataArgument()) {
5422 if (atFirstArg) {
5423 atFirstArg = false;
5424 usesPositionalArgs = FS.usesPositionalArg();
5425 }
5426 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005427 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5428 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005429 return false;
5430 }
Ted Kremenek5739de72010-01-29 01:06:55 +00005431 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005432
Ted Kremenekd1668192010-02-27 01:41:03 +00005433 // First check if the field width, precision, and conversion specifier
5434 // have matching data arguments.
5435 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5436 startSpecifier, specifierLen)) {
5437 return false;
5438 }
5439
5440 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5441 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005442 return false;
5443 }
5444
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005445 if (!CS.consumesDataArgument()) {
5446 // FIXME: Technically specifying a precision or field width here
5447 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00005448 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005449 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005450
Ted Kremenek4a49d982010-02-26 19:18:41 +00005451 // Consume the argument.
5452 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00005453 if (argIndex < NumDataArgs) {
5454 // The check to see if the argIndex is valid will come later.
5455 // We set the bit here because we may exit early from this
5456 // function if we encounter some other error.
5457 CoveredArgs.set(argIndex);
5458 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00005459
Dimitry Andric6b5ed342015-02-19 22:32:33 +00005460 // FreeBSD kernel extensions.
5461 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5462 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5463 // We need at least two arguments.
5464 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5465 return false;
5466
5467 // Claim the second argument.
5468 CoveredArgs.set(argIndex + 1);
5469
5470 // Type check the first argument (int for %b, pointer for %D)
5471 const Expr *Ex = getDataArg(argIndex);
5472 const analyze_printf::ArgType &AT =
5473 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5474 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5475 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5476 EmitFormatDiagnostic(
5477 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5478 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5479 << false << Ex->getSourceRange(),
5480 Ex->getLocStart(), /*IsStringLocation*/false,
5481 getSpecifierRange(startSpecifier, specifierLen));
5482
5483 // Type check the second argument (char * for both %b and %D)
5484 Ex = getDataArg(argIndex + 1);
5485 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5486 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5487 EmitFormatDiagnostic(
5488 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5489 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5490 << false << Ex->getSourceRange(),
5491 Ex->getLocStart(), /*IsStringLocation*/false,
5492 getSpecifierRange(startSpecifier, specifierLen));
5493
5494 return true;
5495 }
5496
Ted Kremenek4a49d982010-02-26 19:18:41 +00005497 // Check for using an Objective-C specific conversion specifier
5498 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005499 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00005500 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5501 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00005502 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005503
Tom Careb49ec692010-06-17 19:00:27 +00005504 // Check for invalid use of field width
5505 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00005506 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00005507 startSpecifier, specifierLen);
5508 }
5509
5510 // Check for invalid use of precision
5511 if (!FS.hasValidPrecision()) {
5512 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5513 startSpecifier, specifierLen);
5514 }
5515
5516 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00005517 if (!FS.hasValidThousandsGroupingPrefix())
5518 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005519 if (!FS.hasValidLeadingZeros())
5520 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5521 if (!FS.hasValidPlusPrefix())
5522 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00005523 if (!FS.hasValidSpacePrefix())
5524 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005525 if (!FS.hasValidAlternativeForm())
5526 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5527 if (!FS.hasValidLeftJustified())
5528 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5529
5530 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00005531 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5532 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5533 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005534 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5535 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5536 startSpecifier, specifierLen);
5537
5538 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005539 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005540 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5541 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005542 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005543 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005544 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005545 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5546 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00005547
Jordan Rose92303592012-09-08 04:00:03 +00005548 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5549 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5550
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005551 // The remaining checks depend on the data arguments.
5552 if (HasVAListArg)
5553 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005554
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005555 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005556 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005557
Jordan Rose58bbe422012-07-19 18:10:08 +00005558 const Expr *Arg = getDataArg(argIndex);
5559 if (!Arg)
5560 return true;
5561
5562 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00005563}
5564
Jordan Roseaee34382012-09-05 22:56:26 +00005565static bool requiresParensToAddCast(const Expr *E) {
5566 // FIXME: We should have a general way to reason about operator
5567 // precedence and whether parens are actually needed here.
5568 // Take care of a few common cases where they aren't.
5569 const Expr *Inside = E->IgnoreImpCasts();
5570 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5571 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5572
5573 switch (Inside->getStmtClass()) {
5574 case Stmt::ArraySubscriptExprClass:
5575 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005576 case Stmt::CharacterLiteralClass:
5577 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005578 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005579 case Stmt::FloatingLiteralClass:
5580 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005581 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005582 case Stmt::ObjCArrayLiteralClass:
5583 case Stmt::ObjCBoolLiteralExprClass:
5584 case Stmt::ObjCBoxedExprClass:
5585 case Stmt::ObjCDictionaryLiteralClass:
5586 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005587 case Stmt::ObjCIvarRefExprClass:
5588 case Stmt::ObjCMessageExprClass:
5589 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005590 case Stmt::ObjCStringLiteralClass:
5591 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005592 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005593 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005594 case Stmt::UnaryOperatorClass:
5595 return false;
5596 default:
5597 return true;
5598 }
5599}
5600
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005601static std::pair<QualType, StringRef>
5602shouldNotPrintDirectly(const ASTContext &Context,
5603 QualType IntendedTy,
5604 const Expr *E) {
5605 // Use a 'while' to peel off layers of typedefs.
5606 QualType TyTy = IntendedTy;
5607 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5608 StringRef Name = UserTy->getDecl()->getName();
5609 QualType CastTy = llvm::StringSwitch<QualType>(Name)
5610 .Case("NSInteger", Context.LongTy)
5611 .Case("NSUInteger", Context.UnsignedLongTy)
5612 .Case("SInt32", Context.IntTy)
5613 .Case("UInt32", Context.UnsignedIntTy)
5614 .Default(QualType());
5615
5616 if (!CastTy.isNull())
5617 return std::make_pair(CastTy, Name);
5618
5619 TyTy = UserTy->desugar();
5620 }
5621
5622 // Strip parens if necessary.
5623 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5624 return shouldNotPrintDirectly(Context,
5625 PE->getSubExpr()->getType(),
5626 PE->getSubExpr());
5627
5628 // If this is a conditional expression, then its result type is constructed
5629 // via usual arithmetic conversions and thus there might be no necessary
5630 // typedef sugar there. Recurse to operands to check for NSInteger &
5631 // Co. usage condition.
5632 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5633 QualType TrueTy, FalseTy;
5634 StringRef TrueName, FalseName;
5635
5636 std::tie(TrueTy, TrueName) =
5637 shouldNotPrintDirectly(Context,
5638 CO->getTrueExpr()->getType(),
5639 CO->getTrueExpr());
5640 std::tie(FalseTy, FalseName) =
5641 shouldNotPrintDirectly(Context,
5642 CO->getFalseExpr()->getType(),
5643 CO->getFalseExpr());
5644
5645 if (TrueTy == FalseTy)
5646 return std::make_pair(TrueTy, TrueName);
5647 else if (TrueTy.isNull())
5648 return std::make_pair(FalseTy, FalseName);
5649 else if (FalseTy.isNull())
5650 return std::make_pair(TrueTy, TrueName);
5651 }
5652
5653 return std::make_pair(QualType(), StringRef());
5654}
5655
Richard Smith55ce3522012-06-25 20:30:08 +00005656bool
5657CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5658 const char *StartSpecifier,
5659 unsigned SpecifierLen,
5660 const Expr *E) {
5661 using namespace analyze_format_string;
5662 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005663 // Now type check the data expression that matches the
5664 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005665 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
5666 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00005667 if (!AT.isValid())
5668 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00005669
Jordan Rose598ec092012-12-05 18:44:40 +00005670 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00005671 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5672 ExprTy = TET->getUnderlyingExpr()->getType();
5673 }
5674
Seth Cantrellb4802962015-03-04 03:12:10 +00005675 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5676
5677 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00005678 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005679 }
Jordan Rose98709982012-06-04 22:48:57 +00005680
Jordan Rose22b74712012-09-05 22:56:19 +00005681 // Look through argument promotions for our error message's reported type.
5682 // This includes the integral and floating promotions, but excludes array
5683 // and function pointer decay; seeing that an argument intended to be a
5684 // string has type 'char [6]' is probably more confusing than 'char *'.
5685 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5686 if (ICE->getCastKind() == CK_IntegralCast ||
5687 ICE->getCastKind() == CK_FloatingCast) {
5688 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00005689 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00005690
5691 // Check if we didn't match because of an implicit cast from a 'char'
5692 // or 'short' to an 'int'. This is done because printf is a varargs
5693 // function.
5694 if (ICE->getType() == S.Context.IntTy ||
5695 ICE->getType() == S.Context.UnsignedIntTy) {
5696 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00005697 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00005698 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00005699 }
Jordan Rose98709982012-06-04 22:48:57 +00005700 }
Jordan Rose598ec092012-12-05 18:44:40 +00005701 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5702 // Special case for 'a', which has type 'int' in C.
5703 // Note, however, that we do /not/ want to treat multibyte constants like
5704 // 'MooV' as characters! This form is deprecated but still exists.
5705 if (ExprTy == S.Context.IntTy)
5706 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5707 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00005708 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005709
Jordan Rosebc53ed12014-05-31 04:12:14 +00005710 // Look through enums to their underlying type.
5711 bool IsEnum = false;
5712 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5713 ExprTy = EnumTy->getDecl()->getIntegerType();
5714 IsEnum = true;
5715 }
5716
Jordan Rose0e5badd2012-12-05 18:44:49 +00005717 // %C in an Objective-C context prints a unichar, not a wchar_t.
5718 // If the argument is an integer of some kind, believe the %C and suggest
5719 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00005720 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00005721 if (ObjCContext &&
5722 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5723 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5724 !ExprTy->isCharType()) {
5725 // 'unichar' is defined as a typedef of unsigned short, but we should
5726 // prefer using the typedef if it is visible.
5727 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00005728
5729 // While we are here, check if the value is an IntegerLiteral that happens
5730 // to be within the valid range.
5731 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5732 const llvm::APInt &V = IL->getValue();
5733 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5734 return true;
5735 }
5736
Jordan Rose0e5badd2012-12-05 18:44:49 +00005737 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5738 Sema::LookupOrdinaryName);
5739 if (S.LookupName(Result, S.getCurScope())) {
5740 NamedDecl *ND = Result.getFoundDecl();
5741 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5742 if (TD->getUnderlyingType() == IntendedTy)
5743 IntendedTy = S.Context.getTypedefType(TD);
5744 }
5745 }
5746 }
5747
5748 // Special-case some of Darwin's platform-independence types by suggesting
5749 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005750 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00005751 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005752 QualType CastTy;
5753 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5754 if (!CastTy.isNull()) {
5755 IntendedTy = CastTy;
5756 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00005757 }
5758 }
5759
Jordan Rose22b74712012-09-05 22:56:19 +00005760 // We may be able to offer a FixItHint if it is a supported type.
5761 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00005762 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00005763 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005764
Jordan Rose22b74712012-09-05 22:56:19 +00005765 if (success) {
5766 // Get the fix string from the fixed format specifier
5767 SmallString<16> buf;
5768 llvm::raw_svector_ostream os(buf);
5769 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005770
Jordan Roseaee34382012-09-05 22:56:26 +00005771 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5772
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005773 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00005774 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5775 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5776 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5777 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00005778 // In this case, the specifier is wrong and should be changed to match
5779 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00005780 EmitFormatDiagnostic(S.PDiag(diag)
5781 << AT.getRepresentativeTypeName(S.Context)
5782 << IntendedTy << IsEnum << E->getSourceRange(),
5783 E->getLocStart(),
5784 /*IsStringLocation*/ false, SpecRange,
5785 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00005786 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00005787 // The canonical type for formatting this value is different from the
5788 // actual type of the expression. (This occurs, for example, with Darwin's
5789 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
5790 // should be printed as 'long' for 64-bit compatibility.)
5791 // Rather than emitting a normal format/argument mismatch, we want to
5792 // add a cast to the recommended type (and correct the format string
5793 // if necessary).
5794 SmallString<16> CastBuf;
5795 llvm::raw_svector_ostream CastFix(CastBuf);
5796 CastFix << "(";
5797 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
5798 CastFix << ")";
5799
5800 SmallVector<FixItHint,4> Hints;
5801 if (!AT.matchesType(S.Context, IntendedTy))
5802 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
5803
5804 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
5805 // If there's already a cast present, just replace it.
5806 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
5807 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
5808
5809 } else if (!requiresParensToAddCast(E)) {
5810 // If the expression has high enough precedence,
5811 // just write the C-style cast.
5812 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5813 CastFix.str()));
5814 } else {
5815 // Otherwise, add parens around the expression as well as the cast.
5816 CastFix << "(";
5817 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5818 CastFix.str()));
5819
Alp Tokerb6cc5922014-05-03 03:45:55 +00005820 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00005821 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
5822 }
5823
Jordan Rose0e5badd2012-12-05 18:44:49 +00005824 if (ShouldNotPrintDirectly) {
5825 // The expression has a type that should not be printed directly.
5826 // We extract the name from the typedef because we don't want to show
5827 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005828 StringRef Name;
5829 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
5830 Name = TypedefTy->getDecl()->getName();
5831 else
5832 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00005833 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00005834 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00005835 << E->getSourceRange(),
5836 E->getLocStart(), /*IsStringLocation=*/false,
5837 SpecRange, Hints);
5838 } else {
5839 // In this case, the expression could be printed using a different
5840 // specifier, but we've decided that the specifier is probably correct
5841 // and we should cast instead. Just use the normal warning message.
5842 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00005843 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5844 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00005845 << E->getSourceRange(),
5846 E->getLocStart(), /*IsStringLocation*/false,
5847 SpecRange, Hints);
5848 }
Jordan Roseaee34382012-09-05 22:56:26 +00005849 }
Jordan Rose22b74712012-09-05 22:56:19 +00005850 } else {
5851 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
5852 SpecifierLen);
5853 // Since the warning for passing non-POD types to variadic functions
5854 // was deferred until now, we emit a warning for non-POD
5855 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00005856 switch (S.isValidVarArgType(ExprTy)) {
5857 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00005858 case Sema::VAK_ValidInCXX11: {
5859 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5860 if (match == analyze_printf::ArgType::NoMatchPedantic) {
5861 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5862 }
Richard Smithd7293d72013-08-05 18:49:43 +00005863
Seth Cantrellb4802962015-03-04 03:12:10 +00005864 EmitFormatDiagnostic(
5865 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
5866 << IsEnum << CSR << E->getSourceRange(),
5867 E->getLocStart(), /*IsStringLocation*/ false, CSR);
5868 break;
5869 }
Richard Smithd7293d72013-08-05 18:49:43 +00005870 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00005871 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00005872 EmitFormatDiagnostic(
5873 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005874 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00005875 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00005876 << CallType
5877 << AT.getRepresentativeTypeName(S.Context)
5878 << CSR
5879 << E->getSourceRange(),
5880 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00005881 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00005882 break;
5883
5884 case Sema::VAK_Invalid:
5885 if (ExprTy->isObjCObjectType())
5886 EmitFormatDiagnostic(
5887 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
5888 << S.getLangOpts().CPlusPlus11
5889 << ExprTy
5890 << CallType
5891 << AT.getRepresentativeTypeName(S.Context)
5892 << CSR
5893 << E->getSourceRange(),
5894 E->getLocStart(), /*IsStringLocation*/false, CSR);
5895 else
5896 // FIXME: If this is an initializer list, suggest removing the braces
5897 // or inserting a cast to the target type.
5898 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
5899 << isa<InitListExpr>(E) << ExprTy << CallType
5900 << AT.getRepresentativeTypeName(S.Context)
5901 << E->getSourceRange();
5902 break;
5903 }
5904
5905 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
5906 "format string specifier index out of range");
5907 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005908 }
5909
Ted Kremenekab278de2010-01-28 23:39:18 +00005910 return true;
5911}
5912
Ted Kremenek02087932010-07-16 02:11:22 +00005913//===--- CHECK: Scanf format string checking ------------------------------===//
5914
5915namespace {
5916class CheckScanfHandler : public CheckFormatHandler {
5917public:
Stephen Hines648c3692016-09-16 01:07:04 +00005918 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Ted Kremenek02087932010-07-16 02:11:22 +00005919 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005920 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005921 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005922 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005923 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005924 llvm::SmallBitVector &CheckedVarArgs,
5925 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00005926 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
5927 numDataArgs, beg, hasVAListArg,
5928 Args, formatIdx, inFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005929 CheckedVarArgs, UncoveredArg)
Jordan Rose3e0ec582012-07-19 18:10:23 +00005930 {}
Ted Kremenek02087932010-07-16 02:11:22 +00005931
5932 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
5933 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005934 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00005935
5936 bool HandleInvalidScanfConversionSpecifier(
5937 const analyze_scanf::ScanfSpecifier &FS,
5938 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005939 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005940
Craig Toppere14c0f82014-03-12 04:55:44 +00005941 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00005942};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005943} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005944
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005945void CheckScanfHandler::HandleIncompleteScanList(const char *start,
5946 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005947 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
5948 getLocationOfByte(end), /*IsStringLocation*/true,
5949 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005950}
5951
Ted Kremenekce815422010-07-19 21:25:57 +00005952bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
5953 const analyze_scanf::ScanfSpecifier &FS,
5954 const char *startSpecifier,
5955 unsigned specifierLen) {
5956
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005957 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005958 FS.getConversionSpecifier();
5959
5960 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5961 getLocationOfByte(CS.getStart()),
5962 startSpecifier, specifierLen,
5963 CS.getStart(), CS.getLength());
5964}
5965
Ted Kremenek02087932010-07-16 02:11:22 +00005966bool CheckScanfHandler::HandleScanfSpecifier(
5967 const analyze_scanf::ScanfSpecifier &FS,
5968 const char *startSpecifier,
5969 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00005970 using namespace analyze_scanf;
5971 using namespace analyze_format_string;
5972
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005973 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005974
Ted Kremenek6cd69422010-07-19 22:01:06 +00005975 // Handle case where '%' and '*' don't consume an argument. These shouldn't
5976 // be used to decide if we are using positional arguments consistently.
5977 if (FS.consumesDataArgument()) {
5978 if (atFirstArg) {
5979 atFirstArg = false;
5980 usesPositionalArgs = FS.usesPositionalArg();
5981 }
5982 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005983 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5984 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005985 return false;
5986 }
Ted Kremenek02087932010-07-16 02:11:22 +00005987 }
5988
5989 // Check if the field with is non-zero.
5990 const OptionalAmount &Amt = FS.getFieldWidth();
5991 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
5992 if (Amt.getConstantAmount() == 0) {
5993 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
5994 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00005995 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
5996 getLocationOfByte(Amt.getStart()),
5997 /*IsStringLocation*/true, R,
5998 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00005999 }
6000 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006001
Ted Kremenek02087932010-07-16 02:11:22 +00006002 if (!FS.consumesDataArgument()) {
6003 // FIXME: Technically specifying a precision or field width here
6004 // makes no sense. Worth issuing a warning at some point.
6005 return true;
6006 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006007
Ted Kremenek02087932010-07-16 02:11:22 +00006008 // Consume the argument.
6009 unsigned argIndex = FS.getArgIndex();
6010 if (argIndex < NumDataArgs) {
6011 // The check to see if the argIndex is valid will come later.
6012 // We set the bit here because we may exit early from this
6013 // function if we encounter some other error.
6014 CoveredArgs.set(argIndex);
6015 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006016
Ted Kremenek4407ea42010-07-20 20:04:47 +00006017 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006018 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006019 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6020 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006021 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006022 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006023 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006024 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6025 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006026
Jordan Rose92303592012-09-08 04:00:03 +00006027 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6028 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6029
Ted Kremenek02087932010-07-16 02:11:22 +00006030 // The remaining checks depend on the data arguments.
6031 if (HasVAListArg)
6032 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006033
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006034 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006035 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006036
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006037 // Check that the argument type matches the format specifier.
6038 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006039 if (!Ex)
6040 return true;
6041
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006042 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006043
6044 if (!AT.isValid()) {
6045 return true;
6046 }
6047
Seth Cantrellb4802962015-03-04 03:12:10 +00006048 analyze_format_string::ArgType::MatchKind match =
6049 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006050 if (match == analyze_format_string::ArgType::Match) {
6051 return true;
6052 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006053
Seth Cantrell79340072015-03-04 05:58:08 +00006054 ScanfSpecifier fixedFS = FS;
6055 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6056 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006057
Seth Cantrell79340072015-03-04 05:58:08 +00006058 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6059 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6060 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6061 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006062
Seth Cantrell79340072015-03-04 05:58:08 +00006063 if (success) {
6064 // Get the fix string from the fixed format specifier.
6065 SmallString<128> buf;
6066 llvm::raw_svector_ostream os(buf);
6067 fixedFS.toString(os);
6068
6069 EmitFormatDiagnostic(
6070 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6071 << Ex->getType() << false << Ex->getSourceRange(),
6072 Ex->getLocStart(),
6073 /*IsStringLocation*/ false,
6074 getSpecifierRange(startSpecifier, specifierLen),
6075 FixItHint::CreateReplacement(
6076 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6077 } else {
6078 EmitFormatDiagnostic(S.PDiag(diag)
6079 << AT.getRepresentativeTypeName(S.Context)
6080 << Ex->getType() << false << Ex->getSourceRange(),
6081 Ex->getLocStart(),
6082 /*IsStringLocation*/ false,
6083 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006084 }
6085
Ted Kremenek02087932010-07-16 02:11:22 +00006086 return true;
6087}
6088
Stephen Hines648c3692016-09-16 01:07:04 +00006089static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006090 const Expr *OrigFormatExpr,
6091 ArrayRef<const Expr *> Args,
6092 bool HasVAListArg, unsigned format_idx,
6093 unsigned firstDataArg,
6094 Sema::FormatStringType Type,
6095 bool inFunctionCall,
6096 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006097 llvm::SmallBitVector &CheckedVarArgs,
6098 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00006099 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00006100 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006101 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006102 S, inFunctionCall, Args[format_idx],
6103 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006104 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006105 return;
6106 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006107
Ted Kremenekab278de2010-01-28 23:39:18 +00006108 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006109 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00006110 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006111 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006112 const ConstantArrayType *T =
6113 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006114 assert(T && "String literal not of constant array type!");
6115 size_t TypeSize = T->getSize().getZExtValue();
6116 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006117 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006118
6119 // Emit a warning if the string literal is truncated and does not contain an
6120 // embedded null character.
6121 if (TypeSize <= StrRef.size() &&
6122 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6123 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006124 S, inFunctionCall, Args[format_idx],
6125 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006126 FExpr->getLocStart(),
6127 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6128 return;
6129 }
6130
Ted Kremenekab278de2010-01-28 23:39:18 +00006131 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006132 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006133 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006134 S, inFunctionCall, Args[format_idx],
6135 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006136 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006137 return;
6138 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006139
6140 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
6141 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) {
6142 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
6143 numDataArgs, (Type == Sema::FST_NSString ||
6144 Type == Sema::FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006145 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006146 inFunctionCall, CallType, CheckedVarArgs,
6147 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006148
Hans Wennborg23926bd2011-12-15 10:25:47 +00006149 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006150 S.getLangOpts(),
6151 S.Context.getTargetInfo(),
6152 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006153 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006154 } else if (Type == Sema::FST_Scanf) {
6155 CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006156 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006157 inFunctionCall, CallType, CheckedVarArgs,
6158 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006159
Hans Wennborg23926bd2011-12-15 10:25:47 +00006160 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006161 S.getLangOpts(),
6162 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006163 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006164 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006165}
6166
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006167bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6168 // Str - The format string. NOTE: this is NOT null-terminated!
6169 StringRef StrRef = FExpr->getString();
6170 const char *Str = StrRef.data();
6171 // Account for cases where the string literal is truncated in a declaration.
6172 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6173 assert(T && "String literal not of constant array type!");
6174 size_t TypeSize = T->getSize().getZExtValue();
6175 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6176 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6177 getLangOpts(),
6178 Context.getTargetInfo());
6179}
6180
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006181//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6182
6183// Returns the related absolute value function that is larger, of 0 if one
6184// does not exist.
6185static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6186 switch (AbsFunction) {
6187 default:
6188 return 0;
6189
6190 case Builtin::BI__builtin_abs:
6191 return Builtin::BI__builtin_labs;
6192 case Builtin::BI__builtin_labs:
6193 return Builtin::BI__builtin_llabs;
6194 case Builtin::BI__builtin_llabs:
6195 return 0;
6196
6197 case Builtin::BI__builtin_fabsf:
6198 return Builtin::BI__builtin_fabs;
6199 case Builtin::BI__builtin_fabs:
6200 return Builtin::BI__builtin_fabsl;
6201 case Builtin::BI__builtin_fabsl:
6202 return 0;
6203
6204 case Builtin::BI__builtin_cabsf:
6205 return Builtin::BI__builtin_cabs;
6206 case Builtin::BI__builtin_cabs:
6207 return Builtin::BI__builtin_cabsl;
6208 case Builtin::BI__builtin_cabsl:
6209 return 0;
6210
6211 case Builtin::BIabs:
6212 return Builtin::BIlabs;
6213 case Builtin::BIlabs:
6214 return Builtin::BIllabs;
6215 case Builtin::BIllabs:
6216 return 0;
6217
6218 case Builtin::BIfabsf:
6219 return Builtin::BIfabs;
6220 case Builtin::BIfabs:
6221 return Builtin::BIfabsl;
6222 case Builtin::BIfabsl:
6223 return 0;
6224
6225 case Builtin::BIcabsf:
6226 return Builtin::BIcabs;
6227 case Builtin::BIcabs:
6228 return Builtin::BIcabsl;
6229 case Builtin::BIcabsl:
6230 return 0;
6231 }
6232}
6233
6234// Returns the argument type of the absolute value function.
6235static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6236 unsigned AbsType) {
6237 if (AbsType == 0)
6238 return QualType();
6239
6240 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6241 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6242 if (Error != ASTContext::GE_None)
6243 return QualType();
6244
6245 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6246 if (!FT)
6247 return QualType();
6248
6249 if (FT->getNumParams() != 1)
6250 return QualType();
6251
6252 return FT->getParamType(0);
6253}
6254
6255// Returns the best absolute value function, or zero, based on type and
6256// current absolute value function.
6257static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6258 unsigned AbsFunctionKind) {
6259 unsigned BestKind = 0;
6260 uint64_t ArgSize = Context.getTypeSize(ArgType);
6261 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6262 Kind = getLargerAbsoluteValueFunction(Kind)) {
6263 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6264 if (Context.getTypeSize(ParamType) >= ArgSize) {
6265 if (BestKind == 0)
6266 BestKind = Kind;
6267 else if (Context.hasSameType(ParamType, ArgType)) {
6268 BestKind = Kind;
6269 break;
6270 }
6271 }
6272 }
6273 return BestKind;
6274}
6275
6276enum AbsoluteValueKind {
6277 AVK_Integer,
6278 AVK_Floating,
6279 AVK_Complex
6280};
6281
6282static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6283 if (T->isIntegralOrEnumerationType())
6284 return AVK_Integer;
6285 if (T->isRealFloatingType())
6286 return AVK_Floating;
6287 if (T->isAnyComplexType())
6288 return AVK_Complex;
6289
6290 llvm_unreachable("Type not integer, floating, or complex");
6291}
6292
6293// Changes the absolute value function to a different type. Preserves whether
6294// the function is a builtin.
6295static unsigned changeAbsFunction(unsigned AbsKind,
6296 AbsoluteValueKind ValueKind) {
6297 switch (ValueKind) {
6298 case AVK_Integer:
6299 switch (AbsKind) {
6300 default:
6301 return 0;
6302 case Builtin::BI__builtin_fabsf:
6303 case Builtin::BI__builtin_fabs:
6304 case Builtin::BI__builtin_fabsl:
6305 case Builtin::BI__builtin_cabsf:
6306 case Builtin::BI__builtin_cabs:
6307 case Builtin::BI__builtin_cabsl:
6308 return Builtin::BI__builtin_abs;
6309 case Builtin::BIfabsf:
6310 case Builtin::BIfabs:
6311 case Builtin::BIfabsl:
6312 case Builtin::BIcabsf:
6313 case Builtin::BIcabs:
6314 case Builtin::BIcabsl:
6315 return Builtin::BIabs;
6316 }
6317 case AVK_Floating:
6318 switch (AbsKind) {
6319 default:
6320 return 0;
6321 case Builtin::BI__builtin_abs:
6322 case Builtin::BI__builtin_labs:
6323 case Builtin::BI__builtin_llabs:
6324 case Builtin::BI__builtin_cabsf:
6325 case Builtin::BI__builtin_cabs:
6326 case Builtin::BI__builtin_cabsl:
6327 return Builtin::BI__builtin_fabsf;
6328 case Builtin::BIabs:
6329 case Builtin::BIlabs:
6330 case Builtin::BIllabs:
6331 case Builtin::BIcabsf:
6332 case Builtin::BIcabs:
6333 case Builtin::BIcabsl:
6334 return Builtin::BIfabsf;
6335 }
6336 case AVK_Complex:
6337 switch (AbsKind) {
6338 default:
6339 return 0;
6340 case Builtin::BI__builtin_abs:
6341 case Builtin::BI__builtin_labs:
6342 case Builtin::BI__builtin_llabs:
6343 case Builtin::BI__builtin_fabsf:
6344 case Builtin::BI__builtin_fabs:
6345 case Builtin::BI__builtin_fabsl:
6346 return Builtin::BI__builtin_cabsf;
6347 case Builtin::BIabs:
6348 case Builtin::BIlabs:
6349 case Builtin::BIllabs:
6350 case Builtin::BIfabsf:
6351 case Builtin::BIfabs:
6352 case Builtin::BIfabsl:
6353 return Builtin::BIcabsf;
6354 }
6355 }
6356 llvm_unreachable("Unable to convert function");
6357}
6358
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006359static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006360 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6361 if (!FnInfo)
6362 return 0;
6363
6364 switch (FDecl->getBuiltinID()) {
6365 default:
6366 return 0;
6367 case Builtin::BI__builtin_abs:
6368 case Builtin::BI__builtin_fabs:
6369 case Builtin::BI__builtin_fabsf:
6370 case Builtin::BI__builtin_fabsl:
6371 case Builtin::BI__builtin_labs:
6372 case Builtin::BI__builtin_llabs:
6373 case Builtin::BI__builtin_cabs:
6374 case Builtin::BI__builtin_cabsf:
6375 case Builtin::BI__builtin_cabsl:
6376 case Builtin::BIabs:
6377 case Builtin::BIlabs:
6378 case Builtin::BIllabs:
6379 case Builtin::BIfabs:
6380 case Builtin::BIfabsf:
6381 case Builtin::BIfabsl:
6382 case Builtin::BIcabs:
6383 case Builtin::BIcabsf:
6384 case Builtin::BIcabsl:
6385 return FDecl->getBuiltinID();
6386 }
6387 llvm_unreachable("Unknown Builtin type");
6388}
6389
6390// If the replacement is valid, emit a note with replacement function.
6391// Additionally, suggest including the proper header if not already included.
6392static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00006393 unsigned AbsKind, QualType ArgType) {
6394 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006395 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00006396 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006397 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6398 FunctionName = "std::abs";
6399 if (ArgType->isIntegralOrEnumerationType()) {
6400 HeaderName = "cstdlib";
6401 } else if (ArgType->isRealFloatingType()) {
6402 HeaderName = "cmath";
6403 } else {
6404 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006405 }
Richard Trieubeffb832014-04-15 23:47:53 +00006406
6407 // Lookup all std::abs
6408 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00006409 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00006410 R.suppressDiagnostics();
6411 S.LookupQualifiedName(R, Std);
6412
6413 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006414 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006415 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6416 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6417 } else {
6418 FDecl = dyn_cast<FunctionDecl>(I);
6419 }
6420 if (!FDecl)
6421 continue;
6422
6423 // Found std::abs(), check that they are the right ones.
6424 if (FDecl->getNumParams() != 1)
6425 continue;
6426
6427 // Check that the parameter type can handle the argument.
6428 QualType ParamType = FDecl->getParamDecl(0)->getType();
6429 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6430 S.Context.getTypeSize(ArgType) <=
6431 S.Context.getTypeSize(ParamType)) {
6432 // Found a function, don't need the header hint.
6433 EmitHeaderHint = false;
6434 break;
6435 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006436 }
Richard Trieubeffb832014-04-15 23:47:53 +00006437 }
6438 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00006439 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00006440 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6441
6442 if (HeaderName) {
6443 DeclarationName DN(&S.Context.Idents.get(FunctionName));
6444 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6445 R.suppressDiagnostics();
6446 S.LookupName(R, S.getCurScope());
6447
6448 if (R.isSingleResult()) {
6449 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6450 if (FD && FD->getBuiltinID() == AbsKind) {
6451 EmitHeaderHint = false;
6452 } else {
6453 return;
6454 }
6455 } else if (!R.empty()) {
6456 return;
6457 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006458 }
6459 }
6460
6461 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00006462 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006463
Richard Trieubeffb832014-04-15 23:47:53 +00006464 if (!HeaderName)
6465 return;
6466
6467 if (!EmitHeaderHint)
6468 return;
6469
Alp Toker5d96e0a2014-07-11 20:53:51 +00006470 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6471 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00006472}
6473
6474static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
6475 if (!FDecl)
6476 return false;
6477
6478 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
6479 return false;
6480
6481 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
6482
6483 while (ND && ND->isInlineNamespace()) {
6484 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006485 }
Richard Trieubeffb832014-04-15 23:47:53 +00006486
6487 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
6488 return false;
6489
6490 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
6491 return false;
6492
6493 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006494}
6495
6496// Warn when using the wrong abs() function.
6497void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
6498 const FunctionDecl *FDecl,
6499 IdentifierInfo *FnInfo) {
6500 if (Call->getNumArgs() != 1)
6501 return;
6502
6503 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00006504 bool IsStdAbs = IsFunctionStdAbs(FDecl);
6505 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006506 return;
6507
6508 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6509 QualType ParamType = Call->getArg(0)->getType();
6510
Alp Toker5d96e0a2014-07-11 20:53:51 +00006511 // Unsigned types cannot be negative. Suggest removing the absolute value
6512 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006513 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00006514 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00006515 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006516 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6517 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00006518 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006519 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6520 return;
6521 }
6522
David Majnemer7f77eb92015-11-15 03:04:34 +00006523 // Taking the absolute value of a pointer is very suspicious, they probably
6524 // wanted to index into an array, dereference a pointer, call a function, etc.
6525 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6526 unsigned DiagType = 0;
6527 if (ArgType->isFunctionType())
6528 DiagType = 1;
6529 else if (ArgType->isArrayType())
6530 DiagType = 2;
6531
6532 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6533 return;
6534 }
6535
Richard Trieubeffb832014-04-15 23:47:53 +00006536 // std::abs has overloads which prevent most of the absolute value problems
6537 // from occurring.
6538 if (IsStdAbs)
6539 return;
6540
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006541 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6542 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6543
6544 // The argument and parameter are the same kind. Check if they are the right
6545 // size.
6546 if (ArgValueKind == ParamValueKind) {
6547 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6548 return;
6549
6550 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6551 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6552 << FDecl << ArgType << ParamType;
6553
6554 if (NewAbsKind == 0)
6555 return;
6556
6557 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006558 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006559 return;
6560 }
6561
6562 // ArgValueKind != ParamValueKind
6563 // The wrong type of absolute value function was used. Attempt to find the
6564 // proper one.
6565 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6566 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6567 if (NewAbsKind == 0)
6568 return;
6569
6570 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6571 << FDecl << ParamValueKind << ArgValueKind;
6572
6573 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006574 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006575}
6576
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006577//===--- CHECK: Standard memory functions ---------------------------------===//
6578
Nico Weber0e6daef2013-12-26 23:38:39 +00006579/// \brief Takes the expression passed to the size_t parameter of functions
6580/// such as memcmp, strncat, etc and warns if it's a comparison.
6581///
6582/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6583static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6584 IdentifierInfo *FnName,
6585 SourceLocation FnLoc,
6586 SourceLocation RParenLoc) {
6587 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6588 if (!Size)
6589 return false;
6590
6591 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6592 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6593 return false;
6594
Nico Weber0e6daef2013-12-26 23:38:39 +00006595 SourceRange SizeRange = Size->getSourceRange();
6596 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6597 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00006598 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006599 << FnName << FixItHint::CreateInsertion(
6600 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00006601 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00006602 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00006603 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00006604 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6605 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00006606
6607 return true;
6608}
6609
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006610/// \brief Determine whether the given type is or contains a dynamic class type
6611/// (e.g., whether it has a vtable).
6612static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6613 bool &IsContained) {
6614 // Look through array types while ignoring qualifiers.
6615 const Type *Ty = T->getBaseElementTypeUnsafe();
6616 IsContained = false;
6617
6618 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6619 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00006620 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006621 return nullptr;
6622
6623 if (RD->isDynamicClass())
6624 return RD;
6625
6626 // Check all the fields. If any bases were dynamic, the class is dynamic.
6627 // It's impossible for a class to transitively contain itself by value, so
6628 // infinite recursion is impossible.
6629 for (auto *FD : RD->fields()) {
6630 bool SubContained;
6631 if (const CXXRecordDecl *ContainedRD =
6632 getContainedDynamicClass(FD->getType(), SubContained)) {
6633 IsContained = true;
6634 return ContainedRD;
6635 }
6636 }
6637
6638 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00006639}
6640
Chandler Carruth889ed862011-06-21 23:04:20 +00006641/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006642/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00006643static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00006644 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006645 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6646 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6647 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006648
Craig Topperc3ec1492014-05-26 06:22:03 +00006649 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006650}
6651
Chandler Carruth889ed862011-06-21 23:04:20 +00006652/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00006653static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006654 if (const UnaryExprOrTypeTraitExpr *SizeOf =
6655 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6656 if (SizeOf->getKind() == clang::UETT_SizeOf)
6657 return SizeOf->getTypeOfArgument();
6658
6659 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00006660}
6661
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006662/// \brief Check for dangerous or invalid arguments to memset().
6663///
Chandler Carruthac687262011-06-03 06:23:57 +00006664/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006665/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6666/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006667///
6668/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006669void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00006670 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006671 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00006672 assert(BId != 0);
6673
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006674 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00006675 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006676 unsigned ExpectedNumArgs =
6677 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00006678 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006679 return;
6680
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006681 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00006682 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006683 unsigned LenArg =
6684 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00006685 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006686
Nico Weber0e6daef2013-12-26 23:38:39 +00006687 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6688 Call->getLocStart(), Call->getRParenLoc()))
6689 return;
6690
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006691 // We have special checking when the length is a sizeof expression.
6692 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6693 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6694 llvm::FoldingSetNodeID SizeOfArgID;
6695
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00006696 // Although widely used, 'bzero' is not a standard function. Be more strict
6697 // with the argument types before allowing diagnostics and only allow the
6698 // form bzero(ptr, sizeof(...)).
6699 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6700 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
6701 return;
6702
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006703 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6704 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006705 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006706
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006707 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00006708 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006709 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00006710 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00006711
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006712 // Never warn about void type pointers. This can be used to suppress
6713 // false positives.
6714 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006715 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006716
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006717 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6718 // actually comparing the expressions for equality. Because computing the
6719 // expression IDs can be expensive, we only do this if the diagnostic is
6720 // enabled.
6721 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006722 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6723 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006724 // We only compute IDs for expressions if the warning is enabled, and
6725 // cache the sizeof arg's ID.
6726 if (SizeOfArgID == llvm::FoldingSetNodeID())
6727 SizeOfArg->Profile(SizeOfArgID, Context, true);
6728 llvm::FoldingSetNodeID DestID;
6729 Dest->Profile(DestID, Context, true);
6730 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00006731 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6732 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006733 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00006734 StringRef ReadableName = FnName->getName();
6735
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006736 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00006737 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006738 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00006739 if (!PointeeTy->isIncompleteType() &&
6740 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006741 ActionIdx = 2; // If the pointee's size is sizeof(char),
6742 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00006743
6744 // If the function is defined as a builtin macro, do not show macro
6745 // expansion.
6746 SourceLocation SL = SizeOfArg->getExprLoc();
6747 SourceRange DSR = Dest->getSourceRange();
6748 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006749 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00006750
6751 if (SM.isMacroArgExpansion(SL)) {
6752 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
6753 SL = SM.getSpellingLoc(SL);
6754 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
6755 SM.getSpellingLoc(DSR.getEnd()));
6756 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
6757 SM.getSpellingLoc(SSR.getEnd()));
6758 }
6759
Anna Zaksd08d9152012-05-30 23:14:52 +00006760 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006761 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00006762 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00006763 << PointeeTy
6764 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00006765 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00006766 << SSR);
6767 DiagRuntimeBehavior(SL, SizeOfArg,
6768 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
6769 << ActionIdx
6770 << SSR);
6771
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006772 break;
6773 }
6774 }
6775
6776 // Also check for cases where the sizeof argument is the exact same
6777 // type as the memory argument, and where it points to a user-defined
6778 // record type.
6779 if (SizeOfArgTy != QualType()) {
6780 if (PointeeTy->isRecordType() &&
6781 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
6782 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
6783 PDiag(diag::warn_sizeof_pointer_type_memaccess)
6784 << FnName << SizeOfArgTy << ArgIdx
6785 << PointeeTy << Dest->getSourceRange()
6786 << LenExpr->getSourceRange());
6787 break;
6788 }
Nico Weberc5e73862011-06-14 16:14:58 +00006789 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00006790 } else if (DestTy->isArrayType()) {
6791 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00006792 }
Nico Weberc5e73862011-06-14 16:14:58 +00006793
Nico Weberc44b35e2015-03-21 17:37:46 +00006794 if (PointeeTy == QualType())
6795 continue;
Anna Zaks22122702012-01-17 00:37:07 +00006796
Nico Weberc44b35e2015-03-21 17:37:46 +00006797 // Always complain about dynamic classes.
6798 bool IsContained;
6799 if (const CXXRecordDecl *ContainedRD =
6800 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00006801
Nico Weberc44b35e2015-03-21 17:37:46 +00006802 unsigned OperationType = 0;
6803 // "overwritten" if we're warning about the destination for any call
6804 // but memcmp; otherwise a verb appropriate to the call.
6805 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
6806 if (BId == Builtin::BImemcpy)
6807 OperationType = 1;
6808 else if(BId == Builtin::BImemmove)
6809 OperationType = 2;
6810 else if (BId == Builtin::BImemcmp)
6811 OperationType = 3;
6812 }
6813
John McCall31168b02011-06-15 23:02:42 +00006814 DiagRuntimeBehavior(
6815 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00006816 PDiag(diag::warn_dyn_class_memaccess)
6817 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
6818 << FnName << IsContained << ContainedRD << OperationType
6819 << Call->getCallee()->getSourceRange());
6820 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
6821 BId != Builtin::BImemset)
6822 DiagRuntimeBehavior(
6823 Dest->getExprLoc(), Dest,
6824 PDiag(diag::warn_arc_object_memaccess)
6825 << ArgIdx << FnName << PointeeTy
6826 << Call->getCallee()->getSourceRange());
6827 else
6828 continue;
6829
6830 DiagRuntimeBehavior(
6831 Dest->getExprLoc(), Dest,
6832 PDiag(diag::note_bad_memaccess_silence)
6833 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
6834 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006835 }
6836}
6837
Ted Kremenek6865f772011-08-18 20:55:45 +00006838// A little helper routine: ignore addition and subtraction of integer literals.
6839// This intentionally does not ignore all integer constant expressions because
6840// we don't want to remove sizeof().
6841static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
6842 Ex = Ex->IgnoreParenCasts();
6843
6844 for (;;) {
6845 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
6846 if (!BO || !BO->isAdditiveOp())
6847 break;
6848
6849 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
6850 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
6851
6852 if (isa<IntegerLiteral>(RHS))
6853 Ex = LHS;
6854 else if (isa<IntegerLiteral>(LHS))
6855 Ex = RHS;
6856 else
6857 break;
6858 }
6859
6860 return Ex;
6861}
6862
Anna Zaks13b08572012-08-08 21:42:23 +00006863static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
6864 ASTContext &Context) {
6865 // Only handle constant-sized or VLAs, but not flexible members.
6866 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
6867 // Only issue the FIXIT for arrays of size > 1.
6868 if (CAT->getSize().getSExtValue() <= 1)
6869 return false;
6870 } else if (!Ty->isVariableArrayType()) {
6871 return false;
6872 }
6873 return true;
6874}
6875
Ted Kremenek6865f772011-08-18 20:55:45 +00006876// Warn if the user has made the 'size' argument to strlcpy or strlcat
6877// be the size of the source, instead of the destination.
6878void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
6879 IdentifierInfo *FnName) {
6880
6881 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00006882 unsigned NumArgs = Call->getNumArgs();
6883 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00006884 return;
6885
6886 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
6887 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00006888 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00006889
6890 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
6891 Call->getLocStart(), Call->getRParenLoc()))
6892 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00006893
6894 // Look for 'strlcpy(dst, x, sizeof(x))'
6895 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
6896 CompareWithSrc = Ex;
6897 else {
6898 // Look for 'strlcpy(dst, x, strlen(x))'
6899 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00006900 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
6901 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00006902 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
6903 }
6904 }
6905
6906 if (!CompareWithSrc)
6907 return;
6908
6909 // Determine if the argument to sizeof/strlen is equal to the source
6910 // argument. In principle there's all kinds of things you could do
6911 // here, for instance creating an == expression and evaluating it with
6912 // EvaluateAsBooleanCondition, but this uses a more direct technique:
6913 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
6914 if (!SrcArgDRE)
6915 return;
6916
6917 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
6918 if (!CompareWithSrcDRE ||
6919 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
6920 return;
6921
6922 const Expr *OriginalSizeArg = Call->getArg(2);
6923 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
6924 << OriginalSizeArg->getSourceRange() << FnName;
6925
6926 // Output a FIXIT hint if the destination is an array (rather than a
6927 // pointer to an array). This could be enhanced to handle some
6928 // pointers if we know the actual size, like if DstArg is 'array+2'
6929 // we could say 'sizeof(array)-2'.
6930 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00006931 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00006932 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00006933
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006934 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00006935 llvm::raw_svector_ostream OS(sizeString);
6936 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006937 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00006938 OS << ")";
6939
6940 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
6941 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
6942 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00006943}
6944
Anna Zaks314cd092012-02-01 19:08:57 +00006945/// Check if two expressions refer to the same declaration.
6946static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
6947 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
6948 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
6949 return D1->getDecl() == D2->getDecl();
6950 return false;
6951}
6952
6953static const Expr *getStrlenExprArg(const Expr *E) {
6954 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6955 const FunctionDecl *FD = CE->getDirectCallee();
6956 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00006957 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00006958 return CE->getArg(0)->IgnoreParenCasts();
6959 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006960 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00006961}
6962
6963// Warn on anti-patterns as the 'size' argument to strncat.
6964// The correct size argument should look like following:
6965// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
6966void Sema::CheckStrncatArguments(const CallExpr *CE,
6967 IdentifierInfo *FnName) {
6968 // Don't crash if the user has the wrong number of arguments.
6969 if (CE->getNumArgs() < 3)
6970 return;
6971 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
6972 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
6973 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
6974
Nico Weber0e6daef2013-12-26 23:38:39 +00006975 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
6976 CE->getRParenLoc()))
6977 return;
6978
Anna Zaks314cd092012-02-01 19:08:57 +00006979 // Identify common expressions, which are wrongly used as the size argument
6980 // to strncat and may lead to buffer overflows.
6981 unsigned PatternType = 0;
6982 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
6983 // - sizeof(dst)
6984 if (referToTheSameDecl(SizeOfArg, DstArg))
6985 PatternType = 1;
6986 // - sizeof(src)
6987 else if (referToTheSameDecl(SizeOfArg, SrcArg))
6988 PatternType = 2;
6989 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
6990 if (BE->getOpcode() == BO_Sub) {
6991 const Expr *L = BE->getLHS()->IgnoreParenCasts();
6992 const Expr *R = BE->getRHS()->IgnoreParenCasts();
6993 // - sizeof(dst) - strlen(dst)
6994 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
6995 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
6996 PatternType = 1;
6997 // - sizeof(src) - (anything)
6998 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
6999 PatternType = 2;
7000 }
7001 }
7002
7003 if (PatternType == 0)
7004 return;
7005
Anna Zaks5069aa32012-02-03 01:27:37 +00007006 // Generate the diagnostic.
7007 SourceLocation SL = LenArg->getLocStart();
7008 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007009 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00007010
7011 // If the function is defined as a builtin macro, do not show macro expansion.
7012 if (SM.isMacroArgExpansion(SL)) {
7013 SL = SM.getSpellingLoc(SL);
7014 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7015 SM.getSpellingLoc(SR.getEnd()));
7016 }
7017
Anna Zaks13b08572012-08-08 21:42:23 +00007018 // Check if the destination is an array (rather than a pointer to an array).
7019 QualType DstTy = DstArg->getType();
7020 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7021 Context);
7022 if (!isKnownSizeArray) {
7023 if (PatternType == 1)
7024 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7025 else
7026 Diag(SL, diag::warn_strncat_src_size) << SR;
7027 return;
7028 }
7029
Anna Zaks314cd092012-02-01 19:08:57 +00007030 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00007031 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007032 else
Anna Zaks5069aa32012-02-03 01:27:37 +00007033 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007034
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007035 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00007036 llvm::raw_svector_ostream OS(sizeString);
7037 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007038 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007039 OS << ") - ";
7040 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007041 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007042 OS << ") - 1";
7043
Anna Zaks5069aa32012-02-03 01:27:37 +00007044 Diag(SL, diag::note_strncat_wrong_size)
7045 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00007046}
7047
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007048//===--- CHECK: Return Address of Stack Variable --------------------------===//
7049
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007050static const Expr *EvalVal(const Expr *E,
7051 SmallVectorImpl<const DeclRefExpr *> &refVars,
7052 const Decl *ParentDecl);
7053static const Expr *EvalAddr(const Expr *E,
7054 SmallVectorImpl<const DeclRefExpr *> &refVars,
7055 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007056
7057/// CheckReturnStackAddr - Check if a return statement returns the address
7058/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007059static void
7060CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7061 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00007062
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007063 const Expr *stackE = nullptr;
7064 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007065
7066 // Perform checking for returned stack addresses, local blocks,
7067 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00007068 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007069 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007070 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00007071 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007072 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007073 }
7074
Craig Topperc3ec1492014-05-26 06:22:03 +00007075 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007076 return; // Nothing suspicious was found.
7077
Richard Trieu81b6c562016-08-05 23:24:47 +00007078 // Parameters are initalized in the calling scope, so taking the address
7079 // of a parameter reference doesn't need a warning.
7080 for (auto *DRE : refVars)
7081 if (isa<ParmVarDecl>(DRE->getDecl()))
7082 return;
7083
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007084 SourceLocation diagLoc;
7085 SourceRange diagRange;
7086 if (refVars.empty()) {
7087 diagLoc = stackE->getLocStart();
7088 diagRange = stackE->getSourceRange();
7089 } else {
7090 // We followed through a reference variable. 'stackE' contains the
7091 // problematic expression but we will warn at the return statement pointing
7092 // at the reference variable. We will later display the "trail" of
7093 // reference variables using notes.
7094 diagLoc = refVars[0]->getLocStart();
7095 diagRange = refVars[0]->getSourceRange();
7096 }
7097
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007098 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7099 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00007100 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007101 << DR->getDecl()->getDeclName() << diagRange;
7102 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007103 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007104 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007105 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007106 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00007107 // If there is an LValue->RValue conversion, then the value of the
7108 // reference type is used, not the reference.
7109 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7110 if (ICE->getCastKind() == CK_LValueToRValue) {
7111 return;
7112 }
7113 }
Craig Topperda7b27f2015-11-17 05:40:09 +00007114 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7115 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007116 }
7117
7118 // Display the "trail" of reference variables that we followed until we
7119 // found the problematic expression using notes.
7120 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007121 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007122 // If this var binds to another reference var, show the range of the next
7123 // var, otherwise the var binds to the problematic expression, in which case
7124 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007125 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7126 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007127 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7128 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007129 }
7130}
7131
7132/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7133/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007134/// to a location on the stack, a local block, an address of a label, or a
7135/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007136/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007137/// encounter a subexpression that (1) clearly does not lead to one of the
7138/// above problematic expressions (2) is something we cannot determine leads to
7139/// a problematic expression based on such local checking.
7140///
7141/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7142/// the expression that they point to. Such variables are added to the
7143/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007144///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007145/// EvalAddr processes expressions that are pointers that are used as
7146/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007147/// At the base case of the recursion is a check for the above problematic
7148/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007149///
7150/// This implementation handles:
7151///
7152/// * pointer-to-pointer casts
7153/// * implicit conversions from array references to pointers
7154/// * taking the address of fields
7155/// * arbitrary interplay between "&" and "*" operators
7156/// * pointer arithmetic from an address of a stack variable
7157/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007158static const Expr *EvalAddr(const Expr *E,
7159 SmallVectorImpl<const DeclRefExpr *> &refVars,
7160 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007161 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00007162 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007163
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007164 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00007165 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00007166 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007167 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00007168 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00007169
Peter Collingbourne91147592011-04-15 00:35:48 +00007170 E = E->IgnoreParens();
7171
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007172 // Our "symbolic interpreter" is just a dispatch off the currently
7173 // viewed AST node. We then recursively traverse the AST by calling
7174 // EvalAddr and EvalVal appropriately.
7175 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007176 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007177 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007178
Richard Smith40f08eb2014-01-30 22:05:38 +00007179 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00007180 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00007181 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00007182
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007183 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007184 // If this is a reference variable, follow through to the expression that
7185 // it points to.
7186 if (V->hasLocalStorage() &&
7187 V->getType()->isReferenceType() && V->hasInit()) {
7188 // Add the reference variable to the "trail".
7189 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007190 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007191 }
7192
Craig Topperc3ec1492014-05-26 06:22:03 +00007193 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007194 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007195
Chris Lattner934edb22007-12-28 05:31:15 +00007196 case Stmt::UnaryOperatorClass: {
7197 // The only unary operator that make sense to handle here
7198 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007199 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007200
John McCalle3027922010-08-25 11:45:40 +00007201 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007202 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007203 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007204 }
Mike Stump11289f42009-09-09 15:08:12 +00007205
Chris Lattner934edb22007-12-28 05:31:15 +00007206 case Stmt::BinaryOperatorClass: {
7207 // Handle pointer arithmetic. All other binary operators are not valid
7208 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007209 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00007210 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00007211
John McCalle3027922010-08-25 11:45:40 +00007212 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00007213 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007214
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007215 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00007216
7217 // Determine which argument is the real pointer base. It could be
7218 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007219 if (!Base->getType()->isPointerType())
7220 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00007221
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007222 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007223 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007224 }
Steve Naroff2752a172008-09-10 19:17:48 +00007225
Chris Lattner934edb22007-12-28 05:31:15 +00007226 // For conditional operators we need to see if either the LHS or RHS are
7227 // valid DeclRefExpr*s. If one of them is valid, we return it.
7228 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007229 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007230
Chris Lattner934edb22007-12-28 05:31:15 +00007231 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007232 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007233 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007234 // In C++, we can have a throw-expression, which has 'void' type.
7235 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007236 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007237 return LHS;
7238 }
Chris Lattner934edb22007-12-28 05:31:15 +00007239
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007240 // In C++, we can have a throw-expression, which has 'void' type.
7241 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00007242 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007243
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007244 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007245 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007246
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007247 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00007248 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007249 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00007250 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007251
7252 case Stmt::AddrLabelExprClass:
7253 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00007254
John McCall28fc7092011-11-10 05:35:25 +00007255 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007256 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7257 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00007258
Ted Kremenekc3b4c522008-08-07 00:49:01 +00007259 // For casts, we need to handle conversions from arrays to
7260 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00007261 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00007262 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007263 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00007264 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00007265 case Stmt::CXXStaticCastExprClass:
7266 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00007267 case Stmt::CXXConstCastExprClass:
7268 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007269 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00007270 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00007271 case CK_LValueToRValue:
7272 case CK_NoOp:
7273 case CK_BaseToDerived:
7274 case CK_DerivedToBase:
7275 case CK_UncheckedDerivedToBase:
7276 case CK_Dynamic:
7277 case CK_CPointerToObjCPointerCast:
7278 case CK_BlockPointerToObjCPointerCast:
7279 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007280 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007281
7282 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007283 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007284
Richard Trieudadefde2014-07-02 04:39:38 +00007285 case CK_BitCast:
7286 if (SubExpr->getType()->isAnyPointerType() ||
7287 SubExpr->getType()->isBlockPointerType() ||
7288 SubExpr->getType()->isObjCQualifiedIdType())
7289 return EvalAddr(SubExpr, refVars, ParentDecl);
7290 else
7291 return nullptr;
7292
Eli Friedman8195ad72012-02-23 23:04:32 +00007293 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007294 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00007295 }
Chris Lattner934edb22007-12-28 05:31:15 +00007296 }
Mike Stump11289f42009-09-09 15:08:12 +00007297
Douglas Gregorfe314812011-06-21 17:03:29 +00007298 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007299 if (const Expr *Result =
7300 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7301 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00007302 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00007303 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007304
Chris Lattner934edb22007-12-28 05:31:15 +00007305 // Everything else: we simply don't reason about them.
7306 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007307 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00007308 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007309}
Mike Stump11289f42009-09-09 15:08:12 +00007310
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007311/// EvalVal - This function is complements EvalAddr in the mutual recursion.
7312/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007313static const Expr *EvalVal(const Expr *E,
7314 SmallVectorImpl<const DeclRefExpr *> &refVars,
7315 const Decl *ParentDecl) {
7316 do {
7317 // We should only be called for evaluating non-pointer expressions, or
7318 // expressions with a pointer type that are not used as references but
7319 // instead
7320 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00007321
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007322 // Our "symbolic interpreter" is just a dispatch off the currently
7323 // viewed AST node. We then recursively traverse the AST by calling
7324 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00007325
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007326 E = E->IgnoreParens();
7327 switch (E->getStmtClass()) {
7328 case Stmt::ImplicitCastExprClass: {
7329 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7330 if (IE->getValueKind() == VK_LValue) {
7331 E = IE->getSubExpr();
7332 continue;
7333 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007334 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007335 }
Richard Smith40f08eb2014-01-30 22:05:38 +00007336
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007337 case Stmt::ExprWithCleanupsClass:
7338 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7339 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007340
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007341 case Stmt::DeclRefExprClass: {
7342 // When we hit a DeclRefExpr we are looking at code that refers to a
7343 // variable's name. If it's not a reference variable we check if it has
7344 // local storage within the function, and if so, return the expression.
7345 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7346
7347 // If we leave the immediate function, the lifetime isn't about to end.
7348 if (DR->refersToEnclosingVariableOrCapture())
7349 return nullptr;
7350
7351 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7352 // Check if it refers to itself, e.g. "int& i = i;".
7353 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007354 return DR;
7355
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007356 if (V->hasLocalStorage()) {
7357 if (!V->getType()->isReferenceType())
7358 return DR;
7359
7360 // Reference variable, follow through to the expression that
7361 // it points to.
7362 if (V->hasInit()) {
7363 // Add the reference variable to the "trail".
7364 refVars.push_back(DR);
7365 return EvalVal(V->getInit(), refVars, V);
7366 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007367 }
7368 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007369
7370 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007371 }
Mike Stump11289f42009-09-09 15:08:12 +00007372
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007373 case Stmt::UnaryOperatorClass: {
7374 // The only unary operator that make sense to handle here
7375 // is Deref. All others don't resolve to a "name." This includes
7376 // handling all sorts of rvalues passed to a unary operator.
7377 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007378
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007379 if (U->getOpcode() == UO_Deref)
7380 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007381
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007382 return nullptr;
7383 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007384
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007385 case Stmt::ArraySubscriptExprClass: {
7386 // Array subscripts are potential references to data on the stack. We
7387 // retrieve the DeclRefExpr* for the array variable if it indeed
7388 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00007389 const auto *ASE = cast<ArraySubscriptExpr>(E);
7390 if (ASE->isTypeDependent())
7391 return nullptr;
7392 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007393 }
Mike Stump11289f42009-09-09 15:08:12 +00007394
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007395 case Stmt::OMPArraySectionExprClass: {
7396 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7397 ParentDecl);
7398 }
Mike Stump11289f42009-09-09 15:08:12 +00007399
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007400 case Stmt::ConditionalOperatorClass: {
7401 // For conditional operators we need to see if either the LHS or RHS are
7402 // non-NULL Expr's. If one is non-NULL, we return it.
7403 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007404
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007405 // Handle the GNU extension for missing LHS.
7406 if (const Expr *LHSExpr = C->getLHS()) {
7407 // In C++, we can have a throw-expression, which has 'void' type.
7408 if (!LHSExpr->getType()->isVoidType())
7409 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7410 return LHS;
7411 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007412
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007413 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007414 if (C->getRHS()->getType()->isVoidType())
7415 return nullptr;
7416
7417 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007418 }
7419
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007420 // Accesses to members are potential references to data on the stack.
7421 case Stmt::MemberExprClass: {
7422 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00007423
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007424 // Check for indirect access. We only want direct field accesses.
7425 if (M->isArrow())
7426 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007427
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007428 // Check whether the member type is itself a reference, in which case
7429 // we're not going to refer to the member, but to what the member refers
7430 // to.
7431 if (M->getMemberDecl()->getType()->isReferenceType())
7432 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007433
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007434 return EvalVal(M->getBase(), refVars, ParentDecl);
7435 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00007436
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007437 case Stmt::MaterializeTemporaryExprClass:
7438 if (const Expr *Result =
7439 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7440 refVars, ParentDecl))
7441 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007442 return E;
7443
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007444 default:
7445 // Check that we don't return or take the address of a reference to a
7446 // temporary. This is only useful in C++.
7447 if (!E->isTypeDependent() && E->isRValue())
7448 return E;
7449
7450 // Everything else: we simply don't reason about them.
7451 return nullptr;
7452 }
7453 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007454}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007455
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007456void
7457Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7458 SourceLocation ReturnLoc,
7459 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00007460 const AttrVec *Attrs,
7461 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007462 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7463
7464 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00007465 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7466 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00007467 CheckNonNullExpr(*this, RetValExp))
7468 Diag(ReturnLoc, diag::warn_null_ret)
7469 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00007470
7471 // C++11 [basic.stc.dynamic.allocation]p4:
7472 // If an allocation function declared with a non-throwing
7473 // exception-specification fails to allocate storage, it shall return
7474 // a null pointer. Any other allocation function that fails to allocate
7475 // storage shall indicate failure only by throwing an exception [...]
7476 if (FD) {
7477 OverloadedOperatorKind Op = FD->getOverloadedOperator();
7478 if (Op == OO_New || Op == OO_Array_New) {
7479 const FunctionProtoType *Proto
7480 = FD->getType()->castAs<FunctionProtoType>();
7481 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7482 CheckNonNullExpr(*this, RetValExp))
7483 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7484 << FD << getLangOpts().CPlusPlus11;
7485 }
7486 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007487}
7488
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007489//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7490
7491/// Check for comparisons of floating point operands using != and ==.
7492/// Issue a warning if these are no self-comparisons, as they are not likely
7493/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00007494void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00007495 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7496 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007497
7498 // Special case: check for x == x (which is OK).
7499 // Do not emit warnings for such cases.
7500 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7501 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7502 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00007503 return;
Mike Stump11289f42009-09-09 15:08:12 +00007504
Ted Kremenekeda40e22007-11-29 00:59:04 +00007505 // Special case: check for comparisons against literals that can be exactly
7506 // represented by APFloat. In such cases, do not emit a warning. This
7507 // is a heuristic: often comparison against such literals are used to
7508 // detect if a value in a variable has not changed. This clearly can
7509 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00007510 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7511 if (FLL->isExact())
7512 return;
7513 } else
7514 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7515 if (FLR->isExact())
7516 return;
Mike Stump11289f42009-09-09 15:08:12 +00007517
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007518 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00007519 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007520 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007521 return;
Mike Stump11289f42009-09-09 15:08:12 +00007522
David Blaikie1f4ff152012-07-16 20:47:22 +00007523 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007524 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007525 return;
Mike Stump11289f42009-09-09 15:08:12 +00007526
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007527 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00007528 Diag(Loc, diag::warn_floatingpoint_eq)
7529 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007530}
John McCallca01b222010-01-04 23:21:16 +00007531
John McCall70aa5392010-01-06 05:24:50 +00007532//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7533//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00007534
John McCall70aa5392010-01-06 05:24:50 +00007535namespace {
John McCallca01b222010-01-04 23:21:16 +00007536
John McCall70aa5392010-01-06 05:24:50 +00007537/// Structure recording the 'active' range of an integer-valued
7538/// expression.
7539struct IntRange {
7540 /// The number of bits active in the int.
7541 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00007542
John McCall70aa5392010-01-06 05:24:50 +00007543 /// True if the int is known not to have negative values.
7544 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00007545
John McCall70aa5392010-01-06 05:24:50 +00007546 IntRange(unsigned Width, bool NonNegative)
7547 : Width(Width), NonNegative(NonNegative)
7548 {}
John McCallca01b222010-01-04 23:21:16 +00007549
John McCall817d4af2010-11-10 23:38:19 +00007550 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00007551 static IntRange forBoolType() {
7552 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00007553 }
7554
John McCall817d4af2010-11-10 23:38:19 +00007555 /// Returns the range of an opaque value of the given integral type.
7556 static IntRange forValueOfType(ASTContext &C, QualType T) {
7557 return forValueOfCanonicalType(C,
7558 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00007559 }
7560
John McCall817d4af2010-11-10 23:38:19 +00007561 /// Returns the range of an opaque value of a canonical integral type.
7562 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00007563 assert(T->isCanonicalUnqualified());
7564
7565 if (const VectorType *VT = dyn_cast<VectorType>(T))
7566 T = VT->getElementType().getTypePtr();
7567 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7568 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007569 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7570 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00007571
David Majnemer6a426652013-06-07 22:07:20 +00007572 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00007573 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00007574 EnumDecl *Enum = ET->getDecl();
7575 if (!Enum->isCompleteDefinition())
7576 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00007577
David Majnemer6a426652013-06-07 22:07:20 +00007578 unsigned NumPositive = Enum->getNumPositiveBits();
7579 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00007580
David Majnemer6a426652013-06-07 22:07:20 +00007581 if (NumNegative == 0)
7582 return IntRange(NumPositive, true/*NonNegative*/);
7583 else
7584 return IntRange(std::max(NumPositive + 1, NumNegative),
7585 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00007586 }
John McCall70aa5392010-01-06 05:24:50 +00007587
7588 const BuiltinType *BT = cast<BuiltinType>(T);
7589 assert(BT->isInteger());
7590
7591 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7592 }
7593
John McCall817d4af2010-11-10 23:38:19 +00007594 /// Returns the "target" range of a canonical integral type, i.e.
7595 /// the range of values expressible in the type.
7596 ///
7597 /// This matches forValueOfCanonicalType except that enums have the
7598 /// full range of their type, not the range of their enumerators.
7599 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7600 assert(T->isCanonicalUnqualified());
7601
7602 if (const VectorType *VT = dyn_cast<VectorType>(T))
7603 T = VT->getElementType().getTypePtr();
7604 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7605 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007606 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7607 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007608 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00007609 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007610
7611 const BuiltinType *BT = cast<BuiltinType>(T);
7612 assert(BT->isInteger());
7613
7614 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7615 }
7616
7617 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00007618 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00007619 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00007620 L.NonNegative && R.NonNegative);
7621 }
7622
John McCall817d4af2010-11-10 23:38:19 +00007623 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00007624 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00007625 return IntRange(std::min(L.Width, R.Width),
7626 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00007627 }
7628};
7629
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007630IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007631 if (value.isSigned() && value.isNegative())
7632 return IntRange(value.getMinSignedBits(), false);
7633
7634 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00007635 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007636
7637 // isNonNegative() just checks the sign bit without considering
7638 // signedness.
7639 return IntRange(value.getActiveBits(), true);
7640}
7641
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007642IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7643 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007644 if (result.isInt())
7645 return GetValueRange(C, result.getInt(), MaxWidth);
7646
7647 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00007648 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7649 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7650 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7651 R = IntRange::join(R, El);
7652 }
John McCall70aa5392010-01-06 05:24:50 +00007653 return R;
7654 }
7655
7656 if (result.isComplexInt()) {
7657 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7658 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7659 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00007660 }
7661
7662 // This can happen with lossless casts to intptr_t of "based" lvalues.
7663 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00007664 // FIXME: The only reason we need to pass the type in here is to get
7665 // the sign right on this one case. It would be nice if APValue
7666 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007667 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00007668 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00007669}
John McCall70aa5392010-01-06 05:24:50 +00007670
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007671QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007672 QualType Ty = E->getType();
7673 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7674 Ty = AtomicRHS->getValueType();
7675 return Ty;
7676}
7677
John McCall70aa5392010-01-06 05:24:50 +00007678/// Pseudo-evaluate the given integer expression, estimating the
7679/// range of values it might take.
7680///
7681/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007682IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007683 E = E->IgnoreParens();
7684
7685 // Try a full evaluation first.
7686 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007687 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00007688 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007689
7690 // I think we only want to look through implicit casts here; if the
7691 // user has an explicit widening cast, we should treat the value as
7692 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007693 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00007694 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00007695 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7696
Eli Friedmane6d33952013-07-08 20:20:06 +00007697 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00007698
George Burgess IVdf1ed002016-01-13 01:52:39 +00007699 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7700 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00007701
John McCall70aa5392010-01-06 05:24:50 +00007702 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00007703 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00007704 return OutputTypeRange;
7705
7706 IntRange SubRange
7707 = GetExprRange(C, CE->getSubExpr(),
7708 std::min(MaxWidth, OutputTypeRange.Width));
7709
7710 // Bail out if the subexpr's range is as wide as the cast type.
7711 if (SubRange.Width >= OutputTypeRange.Width)
7712 return OutputTypeRange;
7713
7714 // Otherwise, we take the smaller width, and we're non-negative if
7715 // either the output type or the subexpr is.
7716 return IntRange(SubRange.Width,
7717 SubRange.NonNegative || OutputTypeRange.NonNegative);
7718 }
7719
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007720 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007721 // If we can fold the condition, just take that operand.
7722 bool CondResult;
7723 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7724 return GetExprRange(C, CondResult ? CO->getTrueExpr()
7725 : CO->getFalseExpr(),
7726 MaxWidth);
7727
7728 // Otherwise, conservatively merge.
7729 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7730 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7731 return IntRange::join(L, R);
7732 }
7733
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007734 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007735 switch (BO->getOpcode()) {
7736
7737 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00007738 case BO_LAnd:
7739 case BO_LOr:
7740 case BO_LT:
7741 case BO_GT:
7742 case BO_LE:
7743 case BO_GE:
7744 case BO_EQ:
7745 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00007746 return IntRange::forBoolType();
7747
John McCallc3688382011-07-13 06:35:24 +00007748 // The type of the assignments is the type of the LHS, so the RHS
7749 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00007750 case BO_MulAssign:
7751 case BO_DivAssign:
7752 case BO_RemAssign:
7753 case BO_AddAssign:
7754 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00007755 case BO_XorAssign:
7756 case BO_OrAssign:
7757 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00007758 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00007759
John McCallc3688382011-07-13 06:35:24 +00007760 // Simple assignments just pass through the RHS, which will have
7761 // been coerced to the LHS type.
7762 case BO_Assign:
7763 // TODO: bitfields?
7764 return GetExprRange(C, BO->getRHS(), MaxWidth);
7765
John McCall70aa5392010-01-06 05:24:50 +00007766 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00007767 case BO_PtrMemD:
7768 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00007769 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007770
John McCall2ce81ad2010-01-06 22:07:33 +00007771 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00007772 case BO_And:
7773 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00007774 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
7775 GetExprRange(C, BO->getRHS(), MaxWidth));
7776
John McCall70aa5392010-01-06 05:24:50 +00007777 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00007778 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00007779 // ...except that we want to treat '1 << (blah)' as logically
7780 // positive. It's an important idiom.
7781 if (IntegerLiteral *I
7782 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
7783 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007784 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00007785 return IntRange(R.Width, /*NonNegative*/ true);
7786 }
7787 }
7788 // fallthrough
7789
John McCalle3027922010-08-25 11:45:40 +00007790 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00007791 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007792
John McCall2ce81ad2010-01-06 22:07:33 +00007793 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00007794 case BO_Shr:
7795 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00007796 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7797
7798 // If the shift amount is a positive constant, drop the width by
7799 // that much.
7800 llvm::APSInt shift;
7801 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
7802 shift.isNonNegative()) {
7803 unsigned zext = shift.getZExtValue();
7804 if (zext >= L.Width)
7805 L.Width = (L.NonNegative ? 0 : 1);
7806 else
7807 L.Width -= zext;
7808 }
7809
7810 return L;
7811 }
7812
7813 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00007814 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00007815 return GetExprRange(C, BO->getRHS(), MaxWidth);
7816
John McCall2ce81ad2010-01-06 22:07:33 +00007817 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00007818 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00007819 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00007820 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007821 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007822
John McCall51431812011-07-14 22:39:48 +00007823 // The width of a division result is mostly determined by the size
7824 // of the LHS.
7825 case BO_Div: {
7826 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00007827 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007828 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7829
7830 // If the divisor is constant, use that.
7831 llvm::APSInt divisor;
7832 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
7833 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
7834 if (log2 >= L.Width)
7835 L.Width = (L.NonNegative ? 0 : 1);
7836 else
7837 L.Width = std::min(L.Width - log2, MaxWidth);
7838 return L;
7839 }
7840
7841 // Otherwise, just use the LHS's width.
7842 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7843 return IntRange(L.Width, L.NonNegative && R.NonNegative);
7844 }
7845
7846 // The result of a remainder can't be larger than the result of
7847 // either side.
7848 case BO_Rem: {
7849 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00007850 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007851 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7852 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7853
7854 IntRange meet = IntRange::meet(L, R);
7855 meet.Width = std::min(meet.Width, MaxWidth);
7856 return meet;
7857 }
7858
7859 // The default behavior is okay for these.
7860 case BO_Mul:
7861 case BO_Add:
7862 case BO_Xor:
7863 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00007864 break;
7865 }
7866
John McCall51431812011-07-14 22:39:48 +00007867 // The default case is to treat the operation as if it were closed
7868 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00007869 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7870 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
7871 return IntRange::join(L, R);
7872 }
7873
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007874 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007875 switch (UO->getOpcode()) {
7876 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00007877 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00007878 return IntRange::forBoolType();
7879
7880 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00007881 case UO_Deref:
7882 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00007883 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007884
7885 default:
7886 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
7887 }
7888 }
7889
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007890 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00007891 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
7892
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007893 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00007894 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00007895 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00007896
Eli Friedmane6d33952013-07-08 20:20:06 +00007897 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007898}
John McCall263a48b2010-01-04 23:31:57 +00007899
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007900IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007901 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00007902}
7903
John McCall263a48b2010-01-04 23:31:57 +00007904/// Checks whether the given value, which currently has the given
7905/// source semantics, has the same value when coerced through the
7906/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007907bool IsSameFloatAfterCast(const llvm::APFloat &value,
7908 const llvm::fltSemantics &Src,
7909 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00007910 llvm::APFloat truncated = value;
7911
7912 bool ignored;
7913 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
7914 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
7915
7916 return truncated.bitwiseIsEqual(value);
7917}
7918
7919/// Checks whether the given value, which currently has the given
7920/// source semantics, has the same value when coerced through the
7921/// target semantics.
7922///
7923/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007924bool IsSameFloatAfterCast(const APValue &value,
7925 const llvm::fltSemantics &Src,
7926 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00007927 if (value.isFloat())
7928 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
7929
7930 if (value.isVector()) {
7931 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
7932 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
7933 return false;
7934 return true;
7935 }
7936
7937 assert(value.isComplexFloat());
7938 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
7939 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
7940}
7941
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007942void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007943
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007944bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00007945 // Suppress cases where we are comparing against an enum constant.
7946 if (const DeclRefExpr *DR =
7947 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
7948 if (isa<EnumConstantDecl>(DR->getDecl()))
7949 return false;
7950
7951 // Suppress cases where the '0' value is expanded from a macro.
7952 if (E->getLocStart().isMacroID())
7953 return false;
7954
John McCallcc7e5bf2010-05-06 08:58:33 +00007955 llvm::APSInt Value;
7956 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
7957}
7958
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007959bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00007960 // Strip off implicit integral promotions.
7961 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00007962 if (ICE->getCastKind() != CK_IntegralCast &&
7963 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00007964 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00007965 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00007966 }
7967
7968 return E->getType()->isEnumeralType();
7969}
7970
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007971void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00007972 // Disable warning in template instantiations.
7973 if (!S.ActiveTemplateInstantiations.empty())
7974 return;
7975
John McCalle3027922010-08-25 11:45:40 +00007976 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00007977 if (E->isValueDependent())
7978 return;
7979
John McCalle3027922010-08-25 11:45:40 +00007980 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007981 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007982 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007983 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007984 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007985 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007986 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007987 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007988 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007989 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007990 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007991 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007992 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007993 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007994 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007995 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7996 }
7997}
7998
Benjamin Kramer7320b992016-06-15 14:20:56 +00007999void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8000 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008001 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00008002 // Disable warning in template instantiations.
8003 if (!S.ActiveTemplateInstantiations.empty())
8004 return;
8005
Richard Trieu0f097742014-04-04 04:13:47 +00008006 // TODO: Investigate using GetExprRange() to get tighter bounds
8007 // on the bit ranges.
8008 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00008009 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00008010 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00008011 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8012 unsigned OtherWidth = OtherRange.Width;
8013
8014 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8015
Richard Trieu560910c2012-11-14 22:50:24 +00008016 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00008017 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00008018 return;
8019
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008020 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00008021 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008022
Richard Trieu0f097742014-04-04 04:13:47 +00008023 // Used for diagnostic printout.
8024 enum {
8025 LiteralConstant = 0,
8026 CXXBoolLiteralTrue,
8027 CXXBoolLiteralFalse
8028 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008029
Richard Trieu0f097742014-04-04 04:13:47 +00008030 if (!OtherIsBooleanType) {
8031 QualType ConstantT = Constant->getType();
8032 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00008033
Richard Trieu0f097742014-04-04 04:13:47 +00008034 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8035 return;
8036 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8037 "comparison with non-integer type");
8038
8039 bool ConstantSigned = ConstantT->isSignedIntegerType();
8040 bool CommonSigned = CommonT->isSignedIntegerType();
8041
8042 bool EqualityOnly = false;
8043
8044 if (CommonSigned) {
8045 // The common type is signed, therefore no signed to unsigned conversion.
8046 if (!OtherRange.NonNegative) {
8047 // Check that the constant is representable in type OtherT.
8048 if (ConstantSigned) {
8049 if (OtherWidth >= Value.getMinSignedBits())
8050 return;
8051 } else { // !ConstantSigned
8052 if (OtherWidth >= Value.getActiveBits() + 1)
8053 return;
8054 }
8055 } else { // !OtherSigned
8056 // Check that the constant is representable in type OtherT.
8057 // Negative values are out of range.
8058 if (ConstantSigned) {
8059 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8060 return;
8061 } else { // !ConstantSigned
8062 if (OtherWidth >= Value.getActiveBits())
8063 return;
8064 }
Richard Trieu560910c2012-11-14 22:50:24 +00008065 }
Richard Trieu0f097742014-04-04 04:13:47 +00008066 } else { // !CommonSigned
8067 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00008068 if (OtherWidth >= Value.getActiveBits())
8069 return;
Craig Toppercf360162014-06-18 05:13:11 +00008070 } else { // OtherSigned
8071 assert(!ConstantSigned &&
8072 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00008073 // Check to see if the constant is representable in OtherT.
8074 if (OtherWidth > Value.getActiveBits())
8075 return;
8076 // Check to see if the constant is equivalent to a negative value
8077 // cast to CommonT.
8078 if (S.Context.getIntWidth(ConstantT) ==
8079 S.Context.getIntWidth(CommonT) &&
8080 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8081 return;
8082 // The constant value rests between values that OtherT can represent
8083 // after conversion. Relational comparison still works, but equality
8084 // comparisons will be tautological.
8085 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008086 }
8087 }
Richard Trieu0f097742014-04-04 04:13:47 +00008088
8089 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8090
8091 if (op == BO_EQ || op == BO_NE) {
8092 IsTrue = op == BO_NE;
8093 } else if (EqualityOnly) {
8094 return;
8095 } else if (RhsConstant) {
8096 if (op == BO_GT || op == BO_GE)
8097 IsTrue = !PositiveConstant;
8098 else // op == BO_LT || op == BO_LE
8099 IsTrue = PositiveConstant;
8100 } else {
8101 if (op == BO_LT || op == BO_LE)
8102 IsTrue = !PositiveConstant;
8103 else // op == BO_GT || op == BO_GE
8104 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008105 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008106 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00008107 // Other isKnownToHaveBooleanValue
8108 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8109 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8110 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8111
8112 static const struct LinkedConditions {
8113 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8114 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8115 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8116 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8117 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8118 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8119
8120 } TruthTable = {
8121 // Constant on LHS. | Constant on RHS. |
8122 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
8123 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8124 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8125 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8126 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8127 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8128 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8129 };
8130
8131 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8132
8133 enum ConstantValue ConstVal = Zero;
8134 if (Value.isUnsigned() || Value.isNonNegative()) {
8135 if (Value == 0) {
8136 LiteralOrBoolConstant =
8137 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8138 ConstVal = Zero;
8139 } else if (Value == 1) {
8140 LiteralOrBoolConstant =
8141 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8142 ConstVal = One;
8143 } else {
8144 LiteralOrBoolConstant = LiteralConstant;
8145 ConstVal = GT_One;
8146 }
8147 } else {
8148 ConstVal = LT_Zero;
8149 }
8150
8151 CompareBoolWithConstantResult CmpRes;
8152
8153 switch (op) {
8154 case BO_LT:
8155 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8156 break;
8157 case BO_GT:
8158 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8159 break;
8160 case BO_LE:
8161 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8162 break;
8163 case BO_GE:
8164 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8165 break;
8166 case BO_EQ:
8167 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8168 break;
8169 case BO_NE:
8170 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8171 break;
8172 default:
8173 CmpRes = Unkwn;
8174 break;
8175 }
8176
8177 if (CmpRes == AFals) {
8178 IsTrue = false;
8179 } else if (CmpRes == ATrue) {
8180 IsTrue = true;
8181 } else {
8182 return;
8183 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008184 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008185
8186 // If this is a comparison to an enum constant, include that
8187 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00008188 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008189 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8190 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8191
8192 SmallString<64> PrettySourceValue;
8193 llvm::raw_svector_ostream OS(PrettySourceValue);
8194 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00008195 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008196 else
8197 OS << Value;
8198
Richard Trieu0f097742014-04-04 04:13:47 +00008199 S.DiagRuntimeBehavior(
8200 E->getOperatorLoc(), E,
8201 S.PDiag(diag::warn_out_of_range_compare)
8202 << OS.str() << LiteralOrBoolConstant
8203 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8204 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008205}
8206
John McCallcc7e5bf2010-05-06 08:58:33 +00008207/// Analyze the operands of the given comparison. Implements the
8208/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008209void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00008210 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8211 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008212}
John McCall263a48b2010-01-04 23:31:57 +00008213
John McCallca01b222010-01-04 23:21:16 +00008214/// \brief Implements -Wsign-compare.
8215///
Richard Trieu82402a02011-09-15 21:56:47 +00008216/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008217void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008218 // The type the comparison is being performed in.
8219 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00008220
8221 // Only analyze comparison operators where both sides have been converted to
8222 // the same type.
8223 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8224 return AnalyzeImpConvsInComparison(S, E);
8225
8226 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00008227 if (E->isValueDependent())
8228 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008229
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008230 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8231 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008232
8233 bool IsComparisonConstant = false;
8234
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008235 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008236 // of 'true' or 'false'.
8237 if (T->isIntegralType(S.Context)) {
8238 llvm::APSInt RHSValue;
8239 bool IsRHSIntegralLiteral =
8240 RHS->isIntegerConstantExpr(RHSValue, S.Context);
8241 llvm::APSInt LHSValue;
8242 bool IsLHSIntegralLiteral =
8243 LHS->isIntegerConstantExpr(LHSValue, S.Context);
8244 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8245 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8246 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8247 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8248 else
8249 IsComparisonConstant =
8250 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008251 } else if (!T->hasUnsignedIntegerRepresentation())
8252 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008253
John McCallcc7e5bf2010-05-06 08:58:33 +00008254 // We don't do anything special if this isn't an unsigned integral
8255 // comparison: we're only interested in integral comparisons, and
8256 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00008257 //
8258 // We also don't care about value-dependent expressions or expressions
8259 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008260 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00008261 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008262
John McCallcc7e5bf2010-05-06 08:58:33 +00008263 // Check to see if one of the (unmodified) operands is of different
8264 // signedness.
8265 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00008266 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8267 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00008268 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00008269 signedOperand = LHS;
8270 unsignedOperand = RHS;
8271 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8272 signedOperand = RHS;
8273 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00008274 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00008275 CheckTrivialUnsignedComparison(S, E);
8276 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008277 }
8278
John McCallcc7e5bf2010-05-06 08:58:33 +00008279 // Otherwise, calculate the effective range of the signed operand.
8280 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00008281
John McCallcc7e5bf2010-05-06 08:58:33 +00008282 // Go ahead and analyze implicit conversions in the operands. Note
8283 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00008284 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8285 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00008286
John McCallcc7e5bf2010-05-06 08:58:33 +00008287 // If the signed range is non-negative, -Wsign-compare won't fire,
8288 // but we should still check for comparisons which are always true
8289 // or false.
8290 if (signedRange.NonNegative)
8291 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008292
8293 // For (in)equality comparisons, if the unsigned operand is a
8294 // constant which cannot collide with a overflowed signed operand,
8295 // then reinterpreting the signed operand as unsigned will not
8296 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00008297 if (E->isEqualityOp()) {
8298 unsigned comparisonWidth = S.Context.getIntWidth(T);
8299 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00008300
John McCallcc7e5bf2010-05-06 08:58:33 +00008301 // We should never be unable to prove that the unsigned operand is
8302 // non-negative.
8303 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8304
8305 if (unsignedRange.Width < comparisonWidth)
8306 return;
8307 }
8308
Douglas Gregorbfb4a212012-05-01 01:53:49 +00008309 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8310 S.PDiag(diag::warn_mixed_sign_comparison)
8311 << LHS->getType() << RHS->getType()
8312 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00008313}
8314
John McCall1f425642010-11-11 03:21:53 +00008315/// Analyzes an attempt to assign the given value to a bitfield.
8316///
8317/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008318bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8319 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00008320 assert(Bitfield->isBitField());
8321 if (Bitfield->isInvalidDecl())
8322 return false;
8323
John McCalldeebbcf2010-11-11 05:33:51 +00008324 // White-list bool bitfields.
8325 if (Bitfield->getType()->isBooleanType())
8326 return false;
8327
Douglas Gregor789adec2011-02-04 13:09:01 +00008328 // Ignore value- or type-dependent expressions.
8329 if (Bitfield->getBitWidth()->isValueDependent() ||
8330 Bitfield->getBitWidth()->isTypeDependent() ||
8331 Init->isValueDependent() ||
8332 Init->isTypeDependent())
8333 return false;
8334
John McCall1f425642010-11-11 03:21:53 +00008335 Expr *OriginalInit = Init->IgnoreParenImpCasts();
8336
Richard Smith5fab0c92011-12-28 19:48:30 +00008337 llvm::APSInt Value;
8338 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00008339 return false;
8340
John McCall1f425642010-11-11 03:21:53 +00008341 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00008342 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00008343
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008344 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00008345 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008346 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8347 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00008348
John McCall1f425642010-11-11 03:21:53 +00008349 if (OriginalWidth <= FieldWidth)
8350 return false;
8351
Eli Friedmanc267a322012-01-26 23:11:39 +00008352 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00008353 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00008354 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00008355
Eli Friedmanc267a322012-01-26 23:11:39 +00008356 // Check whether the stored value is equal to the original value.
8357 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00008358 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00008359 return false;
8360
Eli Friedmanc267a322012-01-26 23:11:39 +00008361 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00008362 // therefore don't strictly fit into a signed bitfield of width 1.
8363 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00008364 return false;
8365
John McCall1f425642010-11-11 03:21:53 +00008366 std::string PrettyValue = Value.toString(10);
8367 std::string PrettyTrunc = TruncatedValue.toString(10);
8368
8369 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8370 << PrettyValue << PrettyTrunc << OriginalInit->getType()
8371 << Init->getSourceRange();
8372
8373 return true;
8374}
8375
John McCalld2a53122010-11-09 23:24:47 +00008376/// Analyze the given simple or compound assignment for warning-worthy
8377/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008378void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00008379 // Just recurse on the LHS.
8380 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8381
8382 // We want to recurse on the RHS as normal unless we're assigning to
8383 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00008384 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008385 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00008386 E->getOperatorLoc())) {
8387 // Recurse, ignoring any implicit conversions on the RHS.
8388 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8389 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00008390 }
8391 }
8392
8393 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8394}
8395
John McCall263a48b2010-01-04 23:31:57 +00008396/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008397void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8398 SourceLocation CContext, unsigned diag,
8399 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008400 if (pruneControlFlow) {
8401 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8402 S.PDiag(diag)
8403 << SourceType << T << E->getSourceRange()
8404 << SourceRange(CContext));
8405 return;
8406 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00008407 S.Diag(E->getExprLoc(), diag)
8408 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8409}
8410
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008411/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008412void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8413 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008414 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008415}
8416
Richard Trieube234c32016-04-21 21:04:55 +00008417
8418/// Diagnose an implicit cast from a floating point value to an integer value.
8419void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8420
8421 SourceLocation CContext) {
8422 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
8423 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
8424
8425 Expr *InnerE = E->IgnoreParenImpCasts();
8426 // We also want to warn on, e.g., "int i = -1.234"
8427 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8428 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8429 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8430
8431 const bool IsLiteral =
8432 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8433
8434 llvm::APFloat Value(0.0);
8435 bool IsConstant =
8436 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8437 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00008438 return DiagnoseImpCast(S, E, T, CContext,
8439 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00008440 }
8441
Chandler Carruth016ef402011-04-10 08:36:24 +00008442 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00008443
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00008444 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8445 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00008446 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8447 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00008448 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00008449 if (IsLiteral) return;
8450 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8451 PruneWarnings);
8452 }
8453
8454 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00008455 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00008456 // Warn on floating point literal to integer.
8457 DiagID = diag::warn_impcast_literal_float_to_integer;
8458 } else if (IntegerValue == 0) {
8459 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
8460 return DiagnoseImpCast(S, E, T, CContext,
8461 diag::warn_impcast_float_integer, PruneWarnings);
8462 }
8463 // Warn on non-zero to zero conversion.
8464 DiagID = diag::warn_impcast_float_to_integer_zero;
8465 } else {
8466 if (IntegerValue.isUnsigned()) {
8467 if (!IntegerValue.isMaxValue()) {
8468 return DiagnoseImpCast(S, E, T, CContext,
8469 diag::warn_impcast_float_integer, PruneWarnings);
8470 }
8471 } else { // IntegerValue.isSigned()
8472 if (!IntegerValue.isMaxSignedValue() &&
8473 !IntegerValue.isMinSignedValue()) {
8474 return DiagnoseImpCast(S, E, T, CContext,
8475 diag::warn_impcast_float_integer, PruneWarnings);
8476 }
8477 }
8478 // Warn on evaluatable floating point expression to integer conversion.
8479 DiagID = diag::warn_impcast_float_to_integer;
8480 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008481
Eli Friedman07185912013-08-29 23:44:43 +00008482 // FIXME: Force the precision of the source value down so we don't print
8483 // digits which are usually useless (we don't really care here if we
8484 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
8485 // would automatically print the shortest representation, but it's a bit
8486 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00008487 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00008488 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
8489 precision = (precision * 59 + 195) / 196;
8490 Value.toString(PrettySourceValue, precision);
8491
David Blaikie9b88cc02012-05-15 17:18:27 +00008492 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00008493 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00008494 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00008495 else
David Blaikie9b88cc02012-05-15 17:18:27 +00008496 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00008497
Richard Trieube234c32016-04-21 21:04:55 +00008498 if (PruneWarnings) {
8499 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8500 S.PDiag(DiagID)
8501 << E->getType() << T.getUnqualifiedType()
8502 << PrettySourceValue << PrettyTargetValue
8503 << E->getSourceRange() << SourceRange(CContext));
8504 } else {
8505 S.Diag(E->getExprLoc(), DiagID)
8506 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8507 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8508 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008509}
8510
John McCall18a2c2c2010-11-09 22:22:12 +00008511std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8512 if (!Range.Width) return "0";
8513
8514 llvm::APSInt ValueInRange = Value;
8515 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00008516 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00008517 return ValueInRange.toString(10);
8518}
8519
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008520bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008521 if (!isa<ImplicitCastExpr>(Ex))
8522 return false;
8523
8524 Expr *InnerE = Ex->IgnoreParenImpCasts();
8525 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8526 const Type *Source =
8527 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8528 if (Target->isDependentType())
8529 return false;
8530
8531 const BuiltinType *FloatCandidateBT =
8532 dyn_cast<BuiltinType>(ToBool ? Source : Target);
8533 const Type *BoolCandidateType = ToBool ? Target : Source;
8534
8535 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8536 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8537}
8538
8539void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8540 SourceLocation CC) {
8541 unsigned NumArgs = TheCall->getNumArgs();
8542 for (unsigned i = 0; i < NumArgs; ++i) {
8543 Expr *CurrA = TheCall->getArg(i);
8544 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8545 continue;
8546
8547 bool IsSwapped = ((i > 0) &&
8548 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8549 IsSwapped |= ((i < (NumArgs - 1)) &&
8550 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8551 if (IsSwapped) {
8552 // Warn on this floating-point to bool conversion.
8553 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8554 CurrA->getType(), CC,
8555 diag::warn_impcast_floating_point_to_bool);
8556 }
8557 }
8558}
8559
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008560void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00008561 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
8562 E->getExprLoc()))
8563 return;
8564
Richard Trieu09d6b802016-01-08 23:35:06 +00008565 // Don't warn on functions which have return type nullptr_t.
8566 if (isa<CallExpr>(E))
8567 return;
8568
Richard Trieu5b993502014-10-15 03:42:06 +00008569 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
8570 const Expr::NullPointerConstantKind NullKind =
8571 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
8572 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
8573 return;
8574
8575 // Return if target type is a safe conversion.
8576 if (T->isAnyPointerType() || T->isBlockPointerType() ||
8577 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8578 return;
8579
8580 SourceLocation Loc = E->getSourceRange().getBegin();
8581
Richard Trieu0a5e1662016-02-13 00:58:53 +00008582 // Venture through the macro stacks to get to the source of macro arguments.
8583 // The new location is a better location than the complete location that was
8584 // passed in.
8585 while (S.SourceMgr.isMacroArgExpansion(Loc))
8586 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8587
8588 while (S.SourceMgr.isMacroArgExpansion(CC))
8589 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8590
Richard Trieu5b993502014-10-15 03:42:06 +00008591 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00008592 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8593 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8594 Loc, S.SourceMgr, S.getLangOpts());
8595 if (MacroName == "NULL")
8596 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00008597 }
8598
8599 // Only warn if the null and context location are in the same macro expansion.
8600 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8601 return;
8602
8603 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8604 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8605 << FixItHint::CreateReplacement(Loc,
8606 S.getFixItZeroLiteralForType(T, Loc));
8607}
8608
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008609void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8610 ObjCArrayLiteral *ArrayLiteral);
8611void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8612 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00008613
8614/// Check a single element within a collection literal against the
8615/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008616void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8617 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008618 // Skip a bitcast to 'id' or qualified 'id'.
8619 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8620 if (ICE->getCastKind() == CK_BitCast &&
8621 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8622 Element = ICE->getSubExpr();
8623 }
8624
8625 QualType ElementType = Element->getType();
8626 ExprResult ElementResult(Element);
8627 if (ElementType->getAs<ObjCObjectPointerType>() &&
8628 S.CheckSingleAssignmentConstraints(TargetElementType,
8629 ElementResult,
8630 false, false)
8631 != Sema::Compatible) {
8632 S.Diag(Element->getLocStart(),
8633 diag::warn_objc_collection_literal_element)
8634 << ElementType << ElementKind << TargetElementType
8635 << Element->getSourceRange();
8636 }
8637
8638 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8639 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8640 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8641 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8642}
8643
8644/// Check an Objective-C array literal being converted to the given
8645/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008646void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8647 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008648 if (!S.NSArrayDecl)
8649 return;
8650
8651 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8652 if (!TargetObjCPtr)
8653 return;
8654
8655 if (TargetObjCPtr->isUnspecialized() ||
8656 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8657 != S.NSArrayDecl->getCanonicalDecl())
8658 return;
8659
8660 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8661 if (TypeArgs.size() != 1)
8662 return;
8663
8664 QualType TargetElementType = TypeArgs[0];
8665 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8666 checkObjCCollectionLiteralElement(S, TargetElementType,
8667 ArrayLiteral->getElement(I),
8668 0);
8669 }
8670}
8671
8672/// Check an Objective-C dictionary literal being converted to the given
8673/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008674void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8675 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008676 if (!S.NSDictionaryDecl)
8677 return;
8678
8679 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8680 if (!TargetObjCPtr)
8681 return;
8682
8683 if (TargetObjCPtr->isUnspecialized() ||
8684 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8685 != S.NSDictionaryDecl->getCanonicalDecl())
8686 return;
8687
8688 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8689 if (TypeArgs.size() != 2)
8690 return;
8691
8692 QualType TargetKeyType = TypeArgs[0];
8693 QualType TargetObjectType = TypeArgs[1];
8694 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8695 auto Element = DictionaryLiteral->getKeyValueElement(I);
8696 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8697 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8698 }
8699}
8700
Richard Trieufc404c72016-02-05 23:02:38 +00008701// Helper function to filter out cases for constant width constant conversion.
8702// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008703bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8704 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00008705 // If initializing from a constant, and the constant starts with '0',
8706 // then it is a binary, octal, or hexadecimal. Allow these constants
8707 // to fill all the bits, even if there is a sign change.
8708 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8709 const char FirstLiteralCharacter =
8710 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8711 if (FirstLiteralCharacter == '0')
8712 return false;
8713 }
8714
8715 // If the CC location points to a '{', and the type is char, then assume
8716 // assume it is an array initialization.
8717 if (CC.isValid() && T->isCharType()) {
8718 const char FirstContextCharacter =
8719 S.getSourceManager().getCharacterData(CC)[0];
8720 if (FirstContextCharacter == '{')
8721 return false;
8722 }
8723
8724 return true;
8725}
8726
John McCallcc7e5bf2010-05-06 08:58:33 +00008727void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00008728 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008729 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00008730
John McCallcc7e5bf2010-05-06 08:58:33 +00008731 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
8732 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
8733 if (Source == Target) return;
8734 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00008735
Chandler Carruthc22845a2011-07-26 05:40:03 +00008736 // If the conversion context location is invalid don't complain. We also
8737 // don't want to emit a warning if the issue occurs from the expansion of
8738 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
8739 // delay this check as long as possible. Once we detect we are in that
8740 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008741 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00008742 return;
8743
Richard Trieu021baa32011-09-23 20:10:00 +00008744 // Diagnose implicit casts to bool.
8745 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
8746 if (isa<StringLiteral>(E))
8747 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00008748 // and expressions, for instance, assert(0 && "error here"), are
8749 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00008750 return DiagnoseImpCast(S, E, T, CC,
8751 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00008752 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
8753 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
8754 // This covers the literal expressions that evaluate to Objective-C
8755 // objects.
8756 return DiagnoseImpCast(S, E, T, CC,
8757 diag::warn_impcast_objective_c_literal_to_bool);
8758 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008759 if (Source->isPointerType() || Source->canDecayToPointerType()) {
8760 // Warn on pointer to bool conversion that is always true.
8761 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
8762 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00008763 }
Richard Trieu021baa32011-09-23 20:10:00 +00008764 }
John McCall263a48b2010-01-04 23:31:57 +00008765
Douglas Gregor5054cb02015-07-07 03:58:22 +00008766 // Check implicit casts from Objective-C collection literals to specialized
8767 // collection types, e.g., NSArray<NSString *> *.
8768 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
8769 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
8770 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
8771 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
8772
John McCall263a48b2010-01-04 23:31:57 +00008773 // Strip vector types.
8774 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008775 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008776 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008777 return;
John McCallacf0ee52010-10-08 02:01:28 +00008778 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008779 }
Chris Lattneree7286f2011-06-14 04:51:15 +00008780
8781 // If the vector cast is cast between two vectors of the same size, it is
8782 // a bitcast, not a conversion.
8783 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
8784 return;
John McCall263a48b2010-01-04 23:31:57 +00008785
8786 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
8787 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
8788 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00008789 if (auto VecTy = dyn_cast<VectorType>(Target))
8790 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00008791
8792 // Strip complex types.
8793 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008794 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008795 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008796 return;
8797
John McCallacf0ee52010-10-08 02:01:28 +00008798 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008799 }
John McCall263a48b2010-01-04 23:31:57 +00008800
8801 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
8802 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
8803 }
8804
8805 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
8806 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
8807
8808 // If the source is floating point...
8809 if (SourceBT && SourceBT->isFloatingPoint()) {
8810 // ...and the target is floating point...
8811 if (TargetBT && TargetBT->isFloatingPoint()) {
8812 // ...then warn if we're dropping FP rank.
8813
8814 // Builtin FP kinds are ordered by increasing FP rank.
8815 if (SourceBT->getKind() > TargetBT->getKind()) {
8816 // Don't warn about float constants that are precisely
8817 // representable in the target type.
8818 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008819 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00008820 // Value might be a float, a float vector, or a float complex.
8821 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00008822 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
8823 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00008824 return;
8825 }
8826
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008827 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008828 return;
8829
John McCallacf0ee52010-10-08 02:01:28 +00008830 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00008831 }
8832 // ... or possibly if we're increasing rank, too
8833 else if (TargetBT->getKind() > SourceBT->getKind()) {
8834 if (S.SourceMgr.isInSystemMacro(CC))
8835 return;
8836
8837 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00008838 }
8839 return;
8840 }
8841
Richard Trieube234c32016-04-21 21:04:55 +00008842 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00008843 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008844 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008845 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00008846
Richard Trieube234c32016-04-21 21:04:55 +00008847 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00008848 }
John McCall263a48b2010-01-04 23:31:57 +00008849
Richard Smith54894fd2015-12-30 01:06:52 +00008850 // Detect the case where a call result is converted from floating-point to
8851 // to bool, and the final argument to the call is converted from bool, to
8852 // discover this typo:
8853 //
8854 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
8855 //
8856 // FIXME: This is an incredibly special case; is there some more general
8857 // way to detect this class of misplaced-parentheses bug?
8858 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008859 // Check last argument of function call to see if it is an
8860 // implicit cast from a type matching the type the result
8861 // is being cast to.
8862 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00008863 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008864 Expr *LastA = CEx->getArg(NumArgs - 1);
8865 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00008866 if (isa<ImplicitCastExpr>(LastA) &&
8867 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008868 // Warn on this floating-point to bool conversion
8869 DiagnoseImpCast(S, E, T, CC,
8870 diag::warn_impcast_floating_point_to_bool);
8871 }
8872 }
8873 }
John McCall263a48b2010-01-04 23:31:57 +00008874 return;
8875 }
8876
Richard Trieu5b993502014-10-15 03:42:06 +00008877 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00008878
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00008879 S.DiscardMisalignedMemberAddress(Target, E);
8880
David Blaikie9366d2b2012-06-19 21:19:06 +00008881 if (!Source->isIntegerType() || !Target->isIntegerType())
8882 return;
8883
David Blaikie7555b6a2012-05-15 16:56:36 +00008884 // TODO: remove this early return once the false positives for constant->bool
8885 // in templates, macros, etc, are reduced or removed.
8886 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
8887 return;
8888
John McCallcc7e5bf2010-05-06 08:58:33 +00008889 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00008890 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00008891
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008892 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00008893 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008894 // TODO: this should happen for bitfield stores, too.
8895 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00008896 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008897 if (S.SourceMgr.isInSystemMacro(CC))
8898 return;
8899
John McCall18a2c2c2010-11-09 22:22:12 +00008900 std::string PrettySourceValue = Value.toString(10);
8901 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008902
Ted Kremenek33ba9952011-10-22 02:37:33 +00008903 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8904 S.PDiag(diag::warn_impcast_integer_precision_constant)
8905 << PrettySourceValue << PrettyTargetValue
8906 << E->getType() << T << E->getSourceRange()
8907 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00008908 return;
8909 }
8910
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008911 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
8912 if (S.SourceMgr.isInSystemMacro(CC))
8913 return;
8914
David Blaikie9455da02012-04-12 22:40:54 +00008915 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00008916 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
8917 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00008918 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00008919 }
8920
Richard Trieudcb55572016-01-29 23:51:16 +00008921 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
8922 SourceRange.NonNegative && Source->isSignedIntegerType()) {
8923 // Warn when doing a signed to signed conversion, warn if the positive
8924 // source value is exactly the width of the target type, which will
8925 // cause a negative value to be stored.
8926
8927 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00008928 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
8929 !S.SourceMgr.isInSystemMacro(CC)) {
8930 if (isSameWidthConstantConversion(S, E, T, CC)) {
8931 std::string PrettySourceValue = Value.toString(10);
8932 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00008933
Richard Trieufc404c72016-02-05 23:02:38 +00008934 S.DiagRuntimeBehavior(
8935 E->getExprLoc(), E,
8936 S.PDiag(diag::warn_impcast_integer_precision_constant)
8937 << PrettySourceValue << PrettyTargetValue << E->getType() << T
8938 << E->getSourceRange() << clang::SourceRange(CC));
8939 return;
Richard Trieudcb55572016-01-29 23:51:16 +00008940 }
8941 }
Richard Trieufc404c72016-02-05 23:02:38 +00008942
Richard Trieudcb55572016-01-29 23:51:16 +00008943 // Fall through for non-constants to give a sign conversion warning.
8944 }
8945
John McCallcc7e5bf2010-05-06 08:58:33 +00008946 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
8947 (!TargetRange.NonNegative && SourceRange.NonNegative &&
8948 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008949 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008950 return;
8951
John McCallcc7e5bf2010-05-06 08:58:33 +00008952 unsigned DiagID = diag::warn_impcast_integer_sign;
8953
8954 // Traditionally, gcc has warned about this under -Wsign-compare.
8955 // We also want to warn about it in -Wconversion.
8956 // So if -Wconversion is off, use a completely identical diagnostic
8957 // in the sign-compare group.
8958 // The conditional-checking code will
8959 if (ICContext) {
8960 DiagID = diag::warn_impcast_integer_sign_conditional;
8961 *ICContext = true;
8962 }
8963
John McCallacf0ee52010-10-08 02:01:28 +00008964 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00008965 }
8966
Douglas Gregora78f1932011-02-22 02:45:07 +00008967 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00008968 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
8969 // type, to give us better diagnostics.
8970 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00008971 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00008972 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8973 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
8974 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
8975 SourceType = S.Context.getTypeDeclType(Enum);
8976 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
8977 }
8978 }
8979
Douglas Gregora78f1932011-02-22 02:45:07 +00008980 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
8981 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00008982 if (SourceEnum->getDecl()->hasNameForLinkage() &&
8983 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008984 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008985 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008986 return;
8987
Douglas Gregor364f7db2011-03-12 00:14:31 +00008988 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00008989 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008990 }
John McCall263a48b2010-01-04 23:31:57 +00008991}
8992
David Blaikie18e9ac72012-05-15 21:57:38 +00008993void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8994 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008995
8996void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00008997 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008998 E = E->IgnoreParenImpCasts();
8999
9000 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00009001 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009002
John McCallacf0ee52010-10-08 02:01:28 +00009003 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009004 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009005 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00009006}
9007
David Blaikie18e9ac72012-05-15 21:57:38 +00009008void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9009 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00009010 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009011
9012 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00009013 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9014 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009015
9016 // If -Wconversion would have warned about either of the candidates
9017 // for a signedness conversion to the context type...
9018 if (!Suspicious) return;
9019
9020 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009021 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00009022 return;
9023
John McCallcc7e5bf2010-05-06 08:58:33 +00009024 // ...then check whether it would have warned about either of the
9025 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00009026 if (E->getType() == T) return;
9027
9028 Suspicious = false;
9029 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9030 E->getType(), CC, &Suspicious);
9031 if (!Suspicious)
9032 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00009033 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009034}
9035
Richard Trieu65724892014-11-15 06:37:39 +00009036/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9037/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009038void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00009039 if (S.getLangOpts().Bool)
9040 return;
9041 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9042}
9043
John McCallcc7e5bf2010-05-06 08:58:33 +00009044/// AnalyzeImplicitConversions - Find and report any interesting
9045/// implicit conversions in the given expression. There are a couple
9046/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009047void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00009048 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00009049 Expr *E = OrigE->IgnoreParenImpCasts();
9050
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00009051 if (E->isTypeDependent() || E->isValueDependent())
9052 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00009053
John McCallcc7e5bf2010-05-06 08:58:33 +00009054 // For conditional operators, we analyze the arguments as if they
9055 // were being fed directly into the output.
9056 if (isa<ConditionalOperator>(E)) {
9057 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00009058 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009059 return;
9060 }
9061
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009062 // Check implicit argument conversions for function calls.
9063 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9064 CheckImplicitArgumentConversions(S, Call, CC);
9065
John McCallcc7e5bf2010-05-06 08:58:33 +00009066 // Go ahead and check any implicit conversions we might have skipped.
9067 // The non-canonical typecheck is just an optimization;
9068 // CheckImplicitConversion will filter out dead implicit conversions.
9069 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009070 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009071
9072 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00009073
9074 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9075 // The bound subexpressions in a PseudoObjectExpr are not reachable
9076 // as transitive children.
9077 // FIXME: Use a more uniform representation for this.
9078 for (auto *SE : POE->semantics())
9079 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9080 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00009081 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00009082
John McCallcc7e5bf2010-05-06 08:58:33 +00009083 // Skip past explicit casts.
9084 if (isa<ExplicitCastExpr>(E)) {
9085 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00009086 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009087 }
9088
John McCalld2a53122010-11-09 23:24:47 +00009089 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9090 // Do a somewhat different check with comparison operators.
9091 if (BO->isComparisonOp())
9092 return AnalyzeComparison(S, BO);
9093
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009094 // And with simple assignments.
9095 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00009096 return AnalyzeAssignment(S, BO);
9097 }
John McCallcc7e5bf2010-05-06 08:58:33 +00009098
9099 // These break the otherwise-useful invariant below. Fortunately,
9100 // we don't really need to recurse into them, because any internal
9101 // expressions should have been analyzed already when they were
9102 // built into statements.
9103 if (isa<StmtExpr>(E)) return;
9104
9105 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00009106 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00009107
9108 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00009109 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00009110 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00009111 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00009112 for (Stmt *SubStmt : E->children()) {
9113 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00009114 if (!ChildExpr)
9115 continue;
9116
Richard Trieu955231d2014-01-25 01:10:35 +00009117 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00009118 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00009119 // Ignore checking string literals that are in logical and operators.
9120 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00009121 continue;
9122 AnalyzeImplicitConversions(S, ChildExpr, CC);
9123 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009124
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009125 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00009126 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9127 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009128 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00009129
9130 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9131 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009132 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009133 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009134
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009135 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9136 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00009137 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009138}
9139
9140} // end anonymous namespace
9141
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009142static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
9143 unsigned Start, unsigned End) {
9144 bool IllegalParams = false;
9145 for (unsigned I = Start; I <= End; ++I) {
9146 QualType Ty = TheCall->getArg(I)->getType();
9147 // Taking into account implicit conversions,
9148 // allow any integer within 32 bits range
9149 if (!Ty->isIntegerType() ||
9150 S.Context.getTypeSizeInChars(Ty).getQuantity() > 4) {
9151 S.Diag(TheCall->getArg(I)->getLocStart(),
9152 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9153 IllegalParams = true;
9154 }
9155 // Potentially emit standard warnings for implicit conversions if enabled
9156 // using -Wconversion.
9157 CheckImplicitConversion(S, TheCall->getArg(I), S.Context.UnsignedIntTy,
9158 TheCall->getArg(I)->getLocStart());
9159 }
9160 return IllegalParams;
9161}
9162
Richard Trieuc1888e02014-06-28 23:25:37 +00009163// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9164// Returns true when emitting a warning about taking the address of a reference.
9165static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00009166 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00009167 E = E->IgnoreParenImpCasts();
9168
9169 const FunctionDecl *FD = nullptr;
9170
9171 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9172 if (!DRE->getDecl()->getType()->isReferenceType())
9173 return false;
9174 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9175 if (!M->getMemberDecl()->getType()->isReferenceType())
9176 return false;
9177 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00009178 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00009179 return false;
9180 FD = Call->getDirectCallee();
9181 } else {
9182 return false;
9183 }
9184
9185 SemaRef.Diag(E->getExprLoc(), PD);
9186
9187 // If possible, point to location of function.
9188 if (FD) {
9189 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9190 }
9191
9192 return true;
9193}
9194
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009195// Returns true if the SourceLocation is expanded from any macro body.
9196// Returns false if the SourceLocation is invalid, is from not in a macro
9197// expansion, or is from expanded from a top-level macro argument.
9198static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9199 if (Loc.isInvalid())
9200 return false;
9201
9202 while (Loc.isMacroID()) {
9203 if (SM.isMacroBodyExpansion(Loc))
9204 return true;
9205 Loc = SM.getImmediateMacroCallerLoc(Loc);
9206 }
9207
9208 return false;
9209}
9210
Richard Trieu3bb8b562014-02-26 02:36:06 +00009211/// \brief Diagnose pointers that are always non-null.
9212/// \param E the expression containing the pointer
9213/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9214/// compared to a null pointer
9215/// \param IsEqual True when the comparison is equal to a null pointer
9216/// \param Range Extra SourceRange to highlight in the diagnostic
9217void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9218 Expr::NullPointerConstantKind NullKind,
9219 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00009220 if (!E)
9221 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009222
9223 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009224 if (E->getExprLoc().isMacroID()) {
9225 const SourceManager &SM = getSourceManager();
9226 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9227 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00009228 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009229 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009230 E = E->IgnoreImpCasts();
9231
9232 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9233
Richard Trieuf7432752014-06-06 21:39:26 +00009234 if (isa<CXXThisExpr>(E)) {
9235 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9236 : diag::warn_this_bool_conversion;
9237 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9238 return;
9239 }
9240
Richard Trieu3bb8b562014-02-26 02:36:06 +00009241 bool IsAddressOf = false;
9242
9243 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9244 if (UO->getOpcode() != UO_AddrOf)
9245 return;
9246 IsAddressOf = true;
9247 E = UO->getSubExpr();
9248 }
9249
Richard Trieuc1888e02014-06-28 23:25:37 +00009250 if (IsAddressOf) {
9251 unsigned DiagID = IsCompare
9252 ? diag::warn_address_of_reference_null_compare
9253 : diag::warn_address_of_reference_bool_conversion;
9254 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9255 << IsEqual;
9256 if (CheckForReference(*this, E, PD)) {
9257 return;
9258 }
9259 }
9260
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009261 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9262 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00009263 std::string Str;
9264 llvm::raw_string_ostream S(Str);
9265 E->printPretty(S, nullptr, getPrintingPolicy());
9266 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9267 : diag::warn_cast_nonnull_to_bool;
9268 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9269 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009270 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00009271 };
9272
9273 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9274 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9275 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009276 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9277 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009278 return;
9279 }
9280 }
9281 }
9282
Richard Trieu3bb8b562014-02-26 02:36:06 +00009283 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00009284 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009285 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9286 D = R->getDecl();
9287 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9288 D = M->getMemberDecl();
9289 }
9290
9291 // Weak Decls can be null.
9292 if (!D || D->isWeak())
9293 return;
George Burgess IV850269a2015-12-08 22:02:00 +00009294
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009295 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00009296 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9297 if (getCurFunction() &&
9298 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009299 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9300 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009301 return;
9302 }
9303
9304 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +00009305 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +00009306 assert(ParamIter != FD->param_end());
9307 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9308
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009309 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9310 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009311 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +00009312 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009313 }
George Burgess IV850269a2015-12-08 22:02:00 +00009314
9315 for (unsigned ArgNo : NonNull->args()) {
9316 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009317 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009318 return;
9319 }
George Burgess IV850269a2015-12-08 22:02:00 +00009320 }
9321 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009322 }
9323 }
George Burgess IV850269a2015-12-08 22:02:00 +00009324 }
9325
Richard Trieu3bb8b562014-02-26 02:36:06 +00009326 QualType T = D->getType();
9327 const bool IsArray = T->isArrayType();
9328 const bool IsFunction = T->isFunctionType();
9329
Richard Trieuc1888e02014-06-28 23:25:37 +00009330 // Address of function is used to silence the function warning.
9331 if (IsAddressOf && IsFunction) {
9332 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009333 }
9334
9335 // Found nothing.
9336 if (!IsAddressOf && !IsFunction && !IsArray)
9337 return;
9338
9339 // Pretty print the expression for the diagnostic.
9340 std::string Str;
9341 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00009342 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00009343
9344 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9345 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00009346 enum {
9347 AddressOf,
9348 FunctionPointer,
9349 ArrayPointer
9350 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009351 if (IsAddressOf)
9352 DiagType = AddressOf;
9353 else if (IsFunction)
9354 DiagType = FunctionPointer;
9355 else if (IsArray)
9356 DiagType = ArrayPointer;
9357 else
9358 llvm_unreachable("Could not determine diagnostic.");
9359 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9360 << Range << IsEqual;
9361
9362 if (!IsFunction)
9363 return;
9364
9365 // Suggest '&' to silence the function warning.
9366 Diag(E->getExprLoc(), diag::note_function_warning_silence)
9367 << FixItHint::CreateInsertion(E->getLocStart(), "&");
9368
9369 // Check to see if '()' fixit should be emitted.
9370 QualType ReturnType;
9371 UnresolvedSet<4> NonTemplateOverloads;
9372 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9373 if (ReturnType.isNull())
9374 return;
9375
9376 if (IsCompare) {
9377 // There are two cases here. If there is null constant, the only suggest
9378 // for a pointer return type. If the null is 0, then suggest if the return
9379 // type is a pointer or an integer type.
9380 if (!ReturnType->isPointerType()) {
9381 if (NullKind == Expr::NPCK_ZeroExpression ||
9382 NullKind == Expr::NPCK_ZeroLiteral) {
9383 if (!ReturnType->isIntegerType())
9384 return;
9385 } else {
9386 return;
9387 }
9388 }
9389 } else { // !IsCompare
9390 // For function to bool, only suggest if the function pointer has bool
9391 // return type.
9392 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9393 return;
9394 }
9395 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00009396 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00009397}
9398
John McCallcc7e5bf2010-05-06 08:58:33 +00009399/// Diagnoses "dangerous" implicit conversions within the given
9400/// expression (which is a full expression). Implements -Wconversion
9401/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009402///
9403/// \param CC the "context" location of the implicit conversion, i.e.
9404/// the most location of the syntactic entity requiring the implicit
9405/// conversion
9406void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009407 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00009408 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00009409 return;
9410
9411 // Don't diagnose for value- or type-dependent expressions.
9412 if (E->isTypeDependent() || E->isValueDependent())
9413 return;
9414
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009415 // Check for array bounds violations in cases where the check isn't triggered
9416 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9417 // ArraySubscriptExpr is on the RHS of a variable initialization.
9418 CheckArrayAccess(E);
9419
John McCallacf0ee52010-10-08 02:01:28 +00009420 // This is not the right CC for (e.g.) a variable initialization.
9421 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009422}
9423
Richard Trieu65724892014-11-15 06:37:39 +00009424/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9425/// Input argument E is a logical expression.
9426void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9427 ::CheckBoolLikeConversion(*this, E, CC);
9428}
9429
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009430/// Diagnose when expression is an integer constant expression and its evaluation
9431/// results in integer overflow
9432void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00009433 // Use a work list to deal with nested struct initializers.
9434 SmallVector<Expr *, 2> Exprs(1, E);
9435
9436 do {
9437 Expr *E = Exprs.pop_back_val();
9438
9439 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9440 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9441 continue;
9442 }
9443
9444 if (auto InitList = dyn_cast<InitListExpr>(E))
9445 Exprs.append(InitList->inits().begin(), InitList->inits().end());
9446 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009447}
9448
Richard Smithc406cb72013-01-17 01:17:56 +00009449namespace {
9450/// \brief Visitor for expressions which looks for unsequenced operations on the
9451/// same object.
9452class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009453 typedef EvaluatedExprVisitor<SequenceChecker> Base;
9454
Richard Smithc406cb72013-01-17 01:17:56 +00009455 /// \brief A tree of sequenced regions within an expression. Two regions are
9456 /// unsequenced if one is an ancestor or a descendent of the other. When we
9457 /// finish processing an expression with sequencing, such as a comma
9458 /// expression, we fold its tree nodes into its parent, since they are
9459 /// unsequenced with respect to nodes we will visit later.
9460 class SequenceTree {
9461 struct Value {
9462 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9463 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +00009464 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +00009465 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009466 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00009467
9468 public:
9469 /// \brief A region within an expression which may be sequenced with respect
9470 /// to some other region.
9471 class Seq {
9472 explicit Seq(unsigned N) : Index(N) {}
9473 unsigned Index;
9474 friend class SequenceTree;
9475 public:
9476 Seq() : Index(0) {}
9477 };
9478
9479 SequenceTree() { Values.push_back(Value(0)); }
9480 Seq root() const { return Seq(0); }
9481
9482 /// \brief Create a new sequence of operations, which is an unsequenced
9483 /// subset of \p Parent. This sequence of operations is sequenced with
9484 /// respect to other children of \p Parent.
9485 Seq allocate(Seq Parent) {
9486 Values.push_back(Value(Parent.Index));
9487 return Seq(Values.size() - 1);
9488 }
9489
9490 /// \brief Merge a sequence of operations into its parent.
9491 void merge(Seq S) {
9492 Values[S.Index].Merged = true;
9493 }
9494
9495 /// \brief Determine whether two operations are unsequenced. This operation
9496 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9497 /// should have been merged into its parent as appropriate.
9498 bool isUnsequenced(Seq Cur, Seq Old) {
9499 unsigned C = representative(Cur.Index);
9500 unsigned Target = representative(Old.Index);
9501 while (C >= Target) {
9502 if (C == Target)
9503 return true;
9504 C = Values[C].Parent;
9505 }
9506 return false;
9507 }
9508
9509 private:
9510 /// \brief Pick a representative for a sequence.
9511 unsigned representative(unsigned K) {
9512 if (Values[K].Merged)
9513 // Perform path compression as we go.
9514 return Values[K].Parent = representative(Values[K].Parent);
9515 return K;
9516 }
9517 };
9518
9519 /// An object for which we can track unsequenced uses.
9520 typedef NamedDecl *Object;
9521
9522 /// Different flavors of object usage which we track. We only track the
9523 /// least-sequenced usage of each kind.
9524 enum UsageKind {
9525 /// A read of an object. Multiple unsequenced reads are OK.
9526 UK_Use,
9527 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00009528 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00009529 UK_ModAsValue,
9530 /// A modification of an object which is not sequenced before the value
9531 /// computation of the expression, such as n++.
9532 UK_ModAsSideEffect,
9533
9534 UK_Count = UK_ModAsSideEffect + 1
9535 };
9536
9537 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00009538 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00009539 Expr *Use;
9540 SequenceTree::Seq Seq;
9541 };
9542
9543 struct UsageInfo {
9544 UsageInfo() : Diagnosed(false) {}
9545 Usage Uses[UK_Count];
9546 /// Have we issued a diagnostic for this variable already?
9547 bool Diagnosed;
9548 };
9549 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9550
9551 Sema &SemaRef;
9552 /// Sequenced regions within the expression.
9553 SequenceTree Tree;
9554 /// Declaration modifications and references which we have seen.
9555 UsageInfoMap UsageMap;
9556 /// The region we are currently within.
9557 SequenceTree::Seq Region;
9558 /// Filled in with declarations which were modified as a side-effect
9559 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009560 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00009561 /// Expressions to check later. We defer checking these to reduce
9562 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009563 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00009564
9565 /// RAII object wrapping the visitation of a sequenced subexpression of an
9566 /// expression. At the end of this process, the side-effects of the evaluation
9567 /// become sequenced with respect to the value computation of the result, so
9568 /// we downgrade any UK_ModAsSideEffect within the evaluation to
9569 /// UK_ModAsValue.
9570 struct SequencedSubexpression {
9571 SequencedSubexpression(SequenceChecker &Self)
9572 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9573 Self.ModAsSideEffect = &ModAsSideEffect;
9574 }
9575 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +00009576 for (auto &M : llvm::reverse(ModAsSideEffect)) {
9577 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +00009578 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +00009579 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9580 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +00009581 }
9582 Self.ModAsSideEffect = OldModAsSideEffect;
9583 }
9584
9585 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009586 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9587 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00009588 };
9589
Richard Smith40238f02013-06-20 22:21:56 +00009590 /// RAII object wrapping the visitation of a subexpression which we might
9591 /// choose to evaluate as a constant. If any subexpression is evaluated and
9592 /// found to be non-constant, this allows us to suppress the evaluation of
9593 /// the outer expression.
9594 class EvaluationTracker {
9595 public:
9596 EvaluationTracker(SequenceChecker &Self)
9597 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9598 Self.EvalTracker = this;
9599 }
9600 ~EvaluationTracker() {
9601 Self.EvalTracker = Prev;
9602 if (Prev)
9603 Prev->EvalOK &= EvalOK;
9604 }
9605
9606 bool evaluate(const Expr *E, bool &Result) {
9607 if (!EvalOK || E->isValueDependent())
9608 return false;
9609 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9610 return EvalOK;
9611 }
9612
9613 private:
9614 SequenceChecker &Self;
9615 EvaluationTracker *Prev;
9616 bool EvalOK;
9617 } *EvalTracker;
9618
Richard Smithc406cb72013-01-17 01:17:56 +00009619 /// \brief Find the object which is produced by the specified expression,
9620 /// if any.
9621 Object getObject(Expr *E, bool Mod) const {
9622 E = E->IgnoreParenCasts();
9623 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9624 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9625 return getObject(UO->getSubExpr(), Mod);
9626 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9627 if (BO->getOpcode() == BO_Comma)
9628 return getObject(BO->getRHS(), Mod);
9629 if (Mod && BO->isAssignmentOp())
9630 return getObject(BO->getLHS(), Mod);
9631 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9632 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9633 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9634 return ME->getMemberDecl();
9635 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9636 // FIXME: If this is a reference, map through to its value.
9637 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00009638 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00009639 }
9640
9641 /// \brief Note that an object was modified or used by an expression.
9642 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9643 Usage &U = UI.Uses[UK];
9644 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9645 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9646 ModAsSideEffect->push_back(std::make_pair(O, U));
9647 U.Use = Ref;
9648 U.Seq = Region;
9649 }
9650 }
9651 /// \brief Check whether a modification or use conflicts with a prior usage.
9652 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9653 bool IsModMod) {
9654 if (UI.Diagnosed)
9655 return;
9656
9657 const Usage &U = UI.Uses[OtherKind];
9658 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9659 return;
9660
9661 Expr *Mod = U.Use;
9662 Expr *ModOrUse = Ref;
9663 if (OtherKind == UK_Use)
9664 std::swap(Mod, ModOrUse);
9665
9666 SemaRef.Diag(Mod->getExprLoc(),
9667 IsModMod ? diag::warn_unsequenced_mod_mod
9668 : diag::warn_unsequenced_mod_use)
9669 << O << SourceRange(ModOrUse->getExprLoc());
9670 UI.Diagnosed = true;
9671 }
9672
9673 void notePreUse(Object O, Expr *Use) {
9674 UsageInfo &U = UsageMap[O];
9675 // Uses conflict with other modifications.
9676 checkUsage(O, U, Use, UK_ModAsValue, false);
9677 }
9678 void notePostUse(Object O, Expr *Use) {
9679 UsageInfo &U = UsageMap[O];
9680 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9681 addUsage(U, O, Use, UK_Use);
9682 }
9683
9684 void notePreMod(Object O, Expr *Mod) {
9685 UsageInfo &U = UsageMap[O];
9686 // Modifications conflict with other modifications and with uses.
9687 checkUsage(O, U, Mod, UK_ModAsValue, true);
9688 checkUsage(O, U, Mod, UK_Use, false);
9689 }
9690 void notePostMod(Object O, Expr *Use, UsageKind UK) {
9691 UsageInfo &U = UsageMap[O];
9692 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9693 addUsage(U, O, Use, UK);
9694 }
9695
9696public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009697 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00009698 : Base(S.Context), SemaRef(S), Region(Tree.root()),
9699 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009700 Visit(E);
9701 }
9702
9703 void VisitStmt(Stmt *S) {
9704 // Skip all statements which aren't expressions for now.
9705 }
9706
9707 void VisitExpr(Expr *E) {
9708 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00009709 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00009710 }
9711
9712 void VisitCastExpr(CastExpr *E) {
9713 Object O = Object();
9714 if (E->getCastKind() == CK_LValueToRValue)
9715 O = getObject(E->getSubExpr(), false);
9716
9717 if (O)
9718 notePreUse(O, E);
9719 VisitExpr(E);
9720 if (O)
9721 notePostUse(O, E);
9722 }
9723
9724 void VisitBinComma(BinaryOperator *BO) {
9725 // C++11 [expr.comma]p1:
9726 // Every value computation and side effect associated with the left
9727 // expression is sequenced before every value computation and side
9728 // effect associated with the right expression.
9729 SequenceTree::Seq LHS = Tree.allocate(Region);
9730 SequenceTree::Seq RHS = Tree.allocate(Region);
9731 SequenceTree::Seq OldRegion = Region;
9732
9733 {
9734 SequencedSubexpression SeqLHS(*this);
9735 Region = LHS;
9736 Visit(BO->getLHS());
9737 }
9738
9739 Region = RHS;
9740 Visit(BO->getRHS());
9741
9742 Region = OldRegion;
9743
9744 // Forget that LHS and RHS are sequenced. They are both unsequenced
9745 // with respect to other stuff.
9746 Tree.merge(LHS);
9747 Tree.merge(RHS);
9748 }
9749
9750 void VisitBinAssign(BinaryOperator *BO) {
9751 // The modification is sequenced after the value computation of the LHS
9752 // and RHS, so check it before inspecting the operands and update the
9753 // map afterwards.
9754 Object O = getObject(BO->getLHS(), true);
9755 if (!O)
9756 return VisitExpr(BO);
9757
9758 notePreMod(O, BO);
9759
9760 // C++11 [expr.ass]p7:
9761 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
9762 // only once.
9763 //
9764 // Therefore, for a compound assignment operator, O is considered used
9765 // everywhere except within the evaluation of E1 itself.
9766 if (isa<CompoundAssignOperator>(BO))
9767 notePreUse(O, BO);
9768
9769 Visit(BO->getLHS());
9770
9771 if (isa<CompoundAssignOperator>(BO))
9772 notePostUse(O, BO);
9773
9774 Visit(BO->getRHS());
9775
Richard Smith83e37bee2013-06-26 23:16:51 +00009776 // C++11 [expr.ass]p1:
9777 // the assignment is sequenced [...] before the value computation of the
9778 // assignment expression.
9779 // C11 6.5.16/3 has no such rule.
9780 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9781 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00009782 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009783
Richard Smithc406cb72013-01-17 01:17:56 +00009784 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
9785 VisitBinAssign(CAO);
9786 }
9787
9788 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9789 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9790 void VisitUnaryPreIncDec(UnaryOperator *UO) {
9791 Object O = getObject(UO->getSubExpr(), true);
9792 if (!O)
9793 return VisitExpr(UO);
9794
9795 notePreMod(O, UO);
9796 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00009797 // C++11 [expr.pre.incr]p1:
9798 // the expression ++x is equivalent to x+=1
9799 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9800 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00009801 }
9802
9803 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9804 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9805 void VisitUnaryPostIncDec(UnaryOperator *UO) {
9806 Object O = getObject(UO->getSubExpr(), true);
9807 if (!O)
9808 return VisitExpr(UO);
9809
9810 notePreMod(O, UO);
9811 Visit(UO->getSubExpr());
9812 notePostMod(O, UO, UK_ModAsSideEffect);
9813 }
9814
9815 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
9816 void VisitBinLOr(BinaryOperator *BO) {
9817 // The side-effects of the LHS of an '&&' are sequenced before the
9818 // value computation of the RHS, and hence before the value computation
9819 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
9820 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00009821 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00009822 {
9823 SequencedSubexpression Sequenced(*this);
9824 Visit(BO->getLHS());
9825 }
9826
9827 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009828 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00009829 if (!Result)
9830 Visit(BO->getRHS());
9831 } else {
9832 // Check for unsequenced operations in the RHS, treating it as an
9833 // entirely separate evaluation.
9834 //
9835 // FIXME: If there are operations in the RHS which are unsequenced
9836 // with respect to operations outside the RHS, and those operations
9837 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00009838 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00009839 }
Richard Smithc406cb72013-01-17 01:17:56 +00009840 }
9841 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00009842 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00009843 {
9844 SequencedSubexpression Sequenced(*this);
9845 Visit(BO->getLHS());
9846 }
9847
9848 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009849 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00009850 if (Result)
9851 Visit(BO->getRHS());
9852 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00009853 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00009854 }
Richard Smithc406cb72013-01-17 01:17:56 +00009855 }
9856
9857 // Only visit the condition, unless we can be sure which subexpression will
9858 // be chosen.
9859 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00009860 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00009861 {
9862 SequencedSubexpression Sequenced(*this);
9863 Visit(CO->getCond());
9864 }
Richard Smithc406cb72013-01-17 01:17:56 +00009865
9866 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009867 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00009868 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00009869 else {
Richard Smithd33f5202013-01-17 23:18:09 +00009870 WorkList.push_back(CO->getTrueExpr());
9871 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00009872 }
Richard Smithc406cb72013-01-17 01:17:56 +00009873 }
9874
Richard Smithe3dbfe02013-06-30 10:40:20 +00009875 void VisitCallExpr(CallExpr *CE) {
9876 // C++11 [intro.execution]p15:
9877 // When calling a function [...], every value computation and side effect
9878 // associated with any argument expression, or with the postfix expression
9879 // designating the called function, is sequenced before execution of every
9880 // expression or statement in the body of the function [and thus before
9881 // the value computation of its result].
9882 SequencedSubexpression Sequenced(*this);
9883 Base::VisitCallExpr(CE);
9884
9885 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
9886 }
9887
Richard Smithc406cb72013-01-17 01:17:56 +00009888 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009889 // This is a call, so all subexpressions are sequenced before the result.
9890 SequencedSubexpression Sequenced(*this);
9891
Richard Smithc406cb72013-01-17 01:17:56 +00009892 if (!CCE->isListInitialization())
9893 return VisitExpr(CCE);
9894
9895 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009896 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00009897 SequenceTree::Seq Parent = Region;
9898 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
9899 E = CCE->arg_end();
9900 I != E; ++I) {
9901 Region = Tree.allocate(Parent);
9902 Elts.push_back(Region);
9903 Visit(*I);
9904 }
9905
9906 // Forget that the initializers are sequenced.
9907 Region = Parent;
9908 for (unsigned I = 0; I < Elts.size(); ++I)
9909 Tree.merge(Elts[I]);
9910 }
9911
9912 void VisitInitListExpr(InitListExpr *ILE) {
9913 if (!SemaRef.getLangOpts().CPlusPlus11)
9914 return VisitExpr(ILE);
9915
9916 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009917 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00009918 SequenceTree::Seq Parent = Region;
9919 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
9920 Expr *E = ILE->getInit(I);
9921 if (!E) continue;
9922 Region = Tree.allocate(Parent);
9923 Elts.push_back(Region);
9924 Visit(E);
9925 }
9926
9927 // Forget that the initializers are sequenced.
9928 Region = Parent;
9929 for (unsigned I = 0; I < Elts.size(); ++I)
9930 Tree.merge(Elts[I]);
9931 }
9932};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009933} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +00009934
9935void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009936 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00009937 WorkList.push_back(E);
9938 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00009939 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00009940 SequenceChecker(*this, Item, WorkList);
9941 }
Richard Smithc406cb72013-01-17 01:17:56 +00009942}
9943
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009944void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
9945 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009946 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +00009947 if (!E->isInstantiationDependent())
9948 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009949 if (!IsConstexpr && !E->isValueDependent())
9950 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009951 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +00009952}
9953
John McCall1f425642010-11-11 03:21:53 +00009954void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
9955 FieldDecl *BitField,
9956 Expr *Init) {
9957 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
9958}
9959
David Majnemer61a5bbf2015-04-07 22:08:51 +00009960static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
9961 SourceLocation Loc) {
9962 if (!PType->isVariablyModifiedType())
9963 return;
9964 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
9965 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
9966 return;
9967 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00009968 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
9969 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
9970 return;
9971 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00009972 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
9973 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
9974 return;
9975 }
9976
9977 const ArrayType *AT = S.Context.getAsArrayType(PType);
9978 if (!AT)
9979 return;
9980
9981 if (AT->getSizeModifier() != ArrayType::Star) {
9982 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
9983 return;
9984 }
9985
9986 S.Diag(Loc, diag::err_array_star_in_function_definition);
9987}
9988
Mike Stump0c2ec772010-01-21 03:59:47 +00009989/// CheckParmsForFunctionDef - Check that the parameters of the given
9990/// function are appropriate for the definition of a function. This
9991/// takes care of any checks that cannot be performed on the
9992/// declaration itself, e.g., that the types of each of the function
9993/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +00009994bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +00009995 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009996 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +00009997 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009998 // C99 6.7.5.3p4: the parameters in a parameter type list in a
9999 // function declarator that is part of a function definition of
10000 // that function shall not have incomplete type.
10001 //
10002 // This is also C++ [dcl.fct]p6.
10003 if (!Param->isInvalidDecl() &&
10004 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010005 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010006 Param->setInvalidDecl();
10007 HasInvalidParm = true;
10008 }
10009
10010 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10011 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000010012 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000010013 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000010014 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000010015 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000010016 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000010017
10018 // C99 6.7.5.3p12:
10019 // If the function declarator is not part of a definition of that
10020 // function, parameters may have incomplete type and may use the [*]
10021 // notation in their sequences of declarator specifiers to specify
10022 // variable length array types.
10023 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000010024 // FIXME: This diagnostic should point the '[*]' if source-location
10025 // information is added for it.
10026 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010027
10028 // MSVC destroys objects passed by value in the callee. Therefore a
10029 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010030 // object's destructor. However, we don't perform any direct access check
10031 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +000010032 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10033 .getCXXABI()
10034 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +000010035 if (!Param->isInvalidDecl()) {
10036 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10037 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10038 if (!ClassDecl->isInvalidDecl() &&
10039 !ClassDecl->hasIrrelevantDestructor() &&
10040 !ClassDecl->isDependentContext()) {
10041 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10042 MarkFunctionReferenced(Param->getLocation(), Destructor);
10043 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10044 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010045 }
10046 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010047 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010048
10049 // Parameters with the pass_object_size attribute only need to be marked
10050 // constant at function definitions. Because we lack information about
10051 // whether we're on a declaration or definition when we're instantiating the
10052 // attribute, we need to check for constness here.
10053 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10054 if (!Param->getType().isConstQualified())
10055 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10056 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000010057 }
10058
10059 return HasInvalidParm;
10060}
John McCall2b5c1b22010-08-12 21:44:57 +000010061
10062/// CheckCastAlign - Implements -Wcast-align, which warns when a
10063/// pointer cast increases the alignment requirements.
10064void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10065 // This is actually a lot of work to potentially be doing on every
10066 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010067 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000010068 return;
10069
10070 // Ignore dependent types.
10071 if (T->isDependentType() || Op->getType()->isDependentType())
10072 return;
10073
10074 // Require that the destination be a pointer type.
10075 const PointerType *DestPtr = T->getAs<PointerType>();
10076 if (!DestPtr) return;
10077
10078 // If the destination has alignment 1, we're done.
10079 QualType DestPointee = DestPtr->getPointeeType();
10080 if (DestPointee->isIncompleteType()) return;
10081 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10082 if (DestAlign.isOne()) return;
10083
10084 // Require that the source be a pointer type.
10085 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10086 if (!SrcPtr) return;
10087 QualType SrcPointee = SrcPtr->getPointeeType();
10088
10089 // Whitelist casts from cv void*. We already implicitly
10090 // whitelisted casts to cv void*, since they have alignment 1.
10091 // Also whitelist casts involving incomplete types, which implicitly
10092 // includes 'void'.
10093 if (SrcPointee->isIncompleteType()) return;
10094
10095 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
10096 if (SrcAlign >= DestAlign) return;
10097
10098 Diag(TRange.getBegin(), diag::warn_cast_align)
10099 << Op->getType() << T
10100 << static_cast<unsigned>(SrcAlign.getQuantity())
10101 << static_cast<unsigned>(DestAlign.getQuantity())
10102 << TRange << Op->getSourceRange();
10103}
10104
Chandler Carruth28389f02011-08-05 09:10:50 +000010105/// \brief Check whether this array fits the idiom of a size-one tail padded
10106/// array member of a struct.
10107///
10108/// We avoid emitting out-of-bounds access warnings for such arrays as they are
10109/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000010110static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000010111 const NamedDecl *ND) {
10112 if (Size != 1 || !ND) return false;
10113
10114 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10115 if (!FD) return false;
10116
10117 // Don't consider sizes resulting from macro expansions or template argument
10118 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000010119
10120 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010121 while (TInfo) {
10122 TypeLoc TL = TInfo->getTypeLoc();
10123 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000010124 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10125 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010126 TInfo = TDL->getTypeSourceInfo();
10127 continue;
10128 }
David Blaikie6adc78e2013-02-18 22:06:02 +000010129 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10130 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000010131 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10132 return false;
10133 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010134 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000010135 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010136
10137 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000010138 if (!RD) return false;
10139 if (RD->isUnion()) return false;
10140 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10141 if (!CRD->isStandardLayout()) return false;
10142 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010143
Benjamin Kramer8c543672011-08-06 03:04:42 +000010144 // See if this is the last field decl in the record.
10145 const Decl *D = FD;
10146 while ((D = D->getNextDeclInContext()))
10147 if (isa<FieldDecl>(D))
10148 return false;
10149 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000010150}
10151
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010152void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010153 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000010154 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010155 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010156 if (IndexExpr->isValueDependent())
10157 return;
10158
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010159 const Type *EffectiveType =
10160 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010161 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010162 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010163 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010164 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000010165 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000010166
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010167 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000010168 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000010169 return;
Richard Smith13f67182011-12-16 19:31:14 +000010170 if (IndexNegated)
10171 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000010172
Craig Topperc3ec1492014-05-26 06:22:03 +000010173 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000010174 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10175 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +000010176 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +000010177 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +000010178
Ted Kremeneke4b316c2011-02-23 23:06:04 +000010179 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010180 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000010181 if (!size.isStrictlyPositive())
10182 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010183
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010184 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000010185 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010186 // Make sure we're comparing apples to apples when comparing index to size
10187 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10188 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000010189 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000010190 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010191 if (ptrarith_typesize != array_typesize) {
10192 // There's a cast to a different size type involved
10193 uint64_t ratio = array_typesize / ptrarith_typesize;
10194 // TODO: Be smarter about handling cases where array_typesize is not a
10195 // multiple of ptrarith_typesize
10196 if (ptrarith_typesize * ratio == array_typesize)
10197 size *= llvm::APInt(size.getBitWidth(), ratio);
10198 }
10199 }
10200
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010201 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010202 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010203 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010204 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010205
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010206 // For array subscripting the index must be less than size, but for pointer
10207 // arithmetic also allow the index (offset) to be equal to size since
10208 // computing the next address after the end of the array is legal and
10209 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010210 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000010211 return;
10212
10213 // Also don't warn for arrays of size 1 which are members of some
10214 // structure. These are often used to approximate flexible arrays in C89
10215 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010216 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000010217 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010218
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010219 // Suppress the warning if the subscript expression (as identified by the
10220 // ']' location) and the index expression are both from macro expansions
10221 // within a system header.
10222 if (ASE) {
10223 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10224 ASE->getRBracketLoc());
10225 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10226 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10227 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000010228 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010229 return;
10230 }
10231 }
10232
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010233 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010234 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010235 DiagID = diag::warn_array_index_exceeds_bounds;
10236
10237 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10238 PDiag(DiagID) << index.toString(10, true)
10239 << size.toString(10, true)
10240 << (unsigned)size.getLimitedValue(~0U)
10241 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010242 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010243 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010244 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010245 DiagID = diag::warn_ptr_arith_precedes_bounds;
10246 if (index.isNegative()) index = -index;
10247 }
10248
10249 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10250 PDiag(DiagID) << index.toString(10, true)
10251 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000010252 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000010253
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000010254 if (!ND) {
10255 // Try harder to find a NamedDecl to point at in the note.
10256 while (const ArraySubscriptExpr *ASE =
10257 dyn_cast<ArraySubscriptExpr>(BaseExpr))
10258 BaseExpr = ASE->getBase()->IgnoreParenCasts();
10259 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10260 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10261 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10262 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10263 }
10264
Chandler Carruth1af88f12011-02-17 21:10:52 +000010265 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010266 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10267 PDiag(diag::note_array_index_out_of_bounds)
10268 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000010269}
10270
Ted Kremenekdf26df72011-03-01 18:41:00 +000010271void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010272 int AllowOnePastEnd = 0;
10273 while (expr) {
10274 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000010275 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010276 case Stmt::ArraySubscriptExprClass: {
10277 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010278 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010279 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +000010280 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010281 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010282 case Stmt::OMPArraySectionExprClass: {
10283 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10284 if (ASE->getLowerBound())
10285 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10286 /*ASE=*/nullptr, AllowOnePastEnd > 0);
10287 return;
10288 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010289 case Stmt::UnaryOperatorClass: {
10290 // Only unwrap the * and & unary operators
10291 const UnaryOperator *UO = cast<UnaryOperator>(expr);
10292 expr = UO->getSubExpr();
10293 switch (UO->getOpcode()) {
10294 case UO_AddrOf:
10295 AllowOnePastEnd++;
10296 break;
10297 case UO_Deref:
10298 AllowOnePastEnd--;
10299 break;
10300 default:
10301 return;
10302 }
10303 break;
10304 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010305 case Stmt::ConditionalOperatorClass: {
10306 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10307 if (const Expr *lhs = cond->getLHS())
10308 CheckArrayAccess(lhs);
10309 if (const Expr *rhs = cond->getRHS())
10310 CheckArrayAccess(rhs);
10311 return;
10312 }
10313 default:
10314 return;
10315 }
Peter Collingbourne91147592011-04-15 00:35:48 +000010316 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010317}
John McCall31168b02011-06-15 23:02:42 +000010318
10319//===--- CHECK: Objective-C retain cycles ----------------------------------//
10320
10321namespace {
10322 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +000010323 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +000010324 VarDecl *Variable;
10325 SourceRange Range;
10326 SourceLocation Loc;
10327 bool Indirect;
10328
10329 void setLocsFrom(Expr *e) {
10330 Loc = e->getExprLoc();
10331 Range = e->getSourceRange();
10332 }
10333 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010334} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010335
10336/// Consider whether capturing the given variable can possibly lead to
10337/// a retain cycle.
10338static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010339 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000010340 // lifetime. In MRR, it's captured strongly if the variable is
10341 // __block and has an appropriate type.
10342 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10343 return false;
10344
10345 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010346 if (ref)
10347 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000010348 return true;
10349}
10350
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010351static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000010352 while (true) {
10353 e = e->IgnoreParens();
10354 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10355 switch (cast->getCastKind()) {
10356 case CK_BitCast:
10357 case CK_LValueBitCast:
10358 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000010359 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000010360 e = cast->getSubExpr();
10361 continue;
10362
John McCall31168b02011-06-15 23:02:42 +000010363 default:
10364 return false;
10365 }
10366 }
10367
10368 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10369 ObjCIvarDecl *ivar = ref->getDecl();
10370 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10371 return false;
10372
10373 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010374 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000010375 return false;
10376
10377 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10378 owner.Indirect = true;
10379 return true;
10380 }
10381
10382 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10383 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10384 if (!var) return false;
10385 return considerVariable(var, ref, owner);
10386 }
10387
John McCall31168b02011-06-15 23:02:42 +000010388 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10389 if (member->isArrow()) return false;
10390
10391 // Don't count this as an indirect ownership.
10392 e = member->getBase();
10393 continue;
10394 }
10395
John McCallfe96e0b2011-11-06 09:01:30 +000010396 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10397 // Only pay attention to pseudo-objects on property references.
10398 ObjCPropertyRefExpr *pre
10399 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10400 ->IgnoreParens());
10401 if (!pre) return false;
10402 if (pre->isImplicitProperty()) return false;
10403 ObjCPropertyDecl *property = pre->getExplicitProperty();
10404 if (!property->isRetaining() &&
10405 !(property->getPropertyIvarDecl() &&
10406 property->getPropertyIvarDecl()->getType()
10407 .getObjCLifetime() == Qualifiers::OCL_Strong))
10408 return false;
10409
10410 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010411 if (pre->isSuperReceiver()) {
10412 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10413 if (!owner.Variable)
10414 return false;
10415 owner.Loc = pre->getLocation();
10416 owner.Range = pre->getSourceRange();
10417 return true;
10418 }
John McCallfe96e0b2011-11-06 09:01:30 +000010419 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10420 ->getSourceExpr());
10421 continue;
10422 }
10423
John McCall31168b02011-06-15 23:02:42 +000010424 // Array ivars?
10425
10426 return false;
10427 }
10428}
10429
10430namespace {
10431 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10432 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10433 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010434 Context(Context), Variable(variable), Capturer(nullptr),
10435 VarWillBeReased(false) {}
10436 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000010437 VarDecl *Variable;
10438 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010439 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +000010440
10441 void VisitDeclRefExpr(DeclRefExpr *ref) {
10442 if (ref->getDecl() == Variable && !Capturer)
10443 Capturer = ref;
10444 }
10445
John McCall31168b02011-06-15 23:02:42 +000010446 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10447 if (Capturer) return;
10448 Visit(ref->getBase());
10449 if (Capturer && ref->isFreeIvar())
10450 Capturer = ref;
10451 }
10452
10453 void VisitBlockExpr(BlockExpr *block) {
10454 // Look inside nested blocks
10455 if (block->getBlockDecl()->capturesVariable(Variable))
10456 Visit(block->getBlockDecl()->getBody());
10457 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000010458
10459 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
10460 if (Capturer) return;
10461 if (OVE->getSourceExpr())
10462 Visit(OVE->getSourceExpr());
10463 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010464 void VisitBinaryOperator(BinaryOperator *BinOp) {
10465 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
10466 return;
10467 Expr *LHS = BinOp->getLHS();
10468 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
10469 if (DRE->getDecl() != Variable)
10470 return;
10471 if (Expr *RHS = BinOp->getRHS()) {
10472 RHS = RHS->IgnoreParenCasts();
10473 llvm::APSInt Value;
10474 VarWillBeReased =
10475 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
10476 }
10477 }
10478 }
John McCall31168b02011-06-15 23:02:42 +000010479 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010480} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010481
10482/// Check whether the given argument is a block which captures a
10483/// variable.
10484static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
10485 assert(owner.Variable && owner.Loc.isValid());
10486
10487 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000010488
10489 // Look through [^{...} copy] and Block_copy(^{...}).
10490 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
10491 Selector Cmd = ME->getSelector();
10492 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
10493 e = ME->getInstanceReceiver();
10494 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000010495 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000010496 e = e->IgnoreParenCasts();
10497 }
10498 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
10499 if (CE->getNumArgs() == 1) {
10500 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000010501 if (Fn) {
10502 const IdentifierInfo *FnI = Fn->getIdentifier();
10503 if (FnI && FnI->isStr("_Block_copy")) {
10504 e = CE->getArg(0)->IgnoreParenCasts();
10505 }
10506 }
Jordan Rose67e887c2012-09-17 17:54:30 +000010507 }
10508 }
10509
John McCall31168b02011-06-15 23:02:42 +000010510 BlockExpr *block = dyn_cast<BlockExpr>(e);
10511 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000010512 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000010513
10514 FindCaptureVisitor visitor(S.Context, owner.Variable);
10515 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010516 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000010517}
10518
10519static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10520 RetainCycleOwner &owner) {
10521 assert(capturer);
10522 assert(owner.Variable && owner.Loc.isValid());
10523
10524 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10525 << owner.Variable << capturer->getSourceRange();
10526 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10527 << owner.Indirect << owner.Range;
10528}
10529
10530/// Check for a keyword selector that starts with the word 'add' or
10531/// 'set'.
10532static bool isSetterLikeSelector(Selector sel) {
10533 if (sel.isUnarySelector()) return false;
10534
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010535 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000010536 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010537 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000010538 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010539 else if (str.startswith("add")) {
10540 // Specially whitelist 'addOperationWithBlock:'.
10541 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
10542 return false;
10543 str = str.substr(3);
10544 }
John McCall31168b02011-06-15 23:02:42 +000010545 else
10546 return false;
10547
10548 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000010549 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000010550}
10551
Benjamin Kramer3a743452015-03-09 15:03:32 +000010552static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
10553 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010554 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
10555 Message->getReceiverInterface(),
10556 NSAPI::ClassId_NSMutableArray);
10557 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010558 return None;
10559 }
10560
10561 Selector Sel = Message->getSelector();
10562
10563 Optional<NSAPI::NSArrayMethodKind> MKOpt =
10564 S.NSAPIObj->getNSArrayMethodKind(Sel);
10565 if (!MKOpt) {
10566 return None;
10567 }
10568
10569 NSAPI::NSArrayMethodKind MK = *MKOpt;
10570
10571 switch (MK) {
10572 case NSAPI::NSMutableArr_addObject:
10573 case NSAPI::NSMutableArr_insertObjectAtIndex:
10574 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
10575 return 0;
10576 case NSAPI::NSMutableArr_replaceObjectAtIndex:
10577 return 1;
10578
10579 default:
10580 return None;
10581 }
10582
10583 return None;
10584}
10585
10586static
10587Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10588 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010589 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10590 Message->getReceiverInterface(),
10591 NSAPI::ClassId_NSMutableDictionary);
10592 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010593 return None;
10594 }
10595
10596 Selector Sel = Message->getSelector();
10597
10598 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10599 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10600 if (!MKOpt) {
10601 return None;
10602 }
10603
10604 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10605
10606 switch (MK) {
10607 case NSAPI::NSMutableDict_setObjectForKey:
10608 case NSAPI::NSMutableDict_setValueForKey:
10609 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10610 return 0;
10611
10612 default:
10613 return None;
10614 }
10615
10616 return None;
10617}
10618
10619static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010620 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10621 Message->getReceiverInterface(),
10622 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000010623
Alex Denisov5dfac812015-08-06 04:51:14 +000010624 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10625 Message->getReceiverInterface(),
10626 NSAPI::ClassId_NSMutableOrderedSet);
10627 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010628 return None;
10629 }
10630
10631 Selector Sel = Message->getSelector();
10632
10633 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10634 if (!MKOpt) {
10635 return None;
10636 }
10637
10638 NSAPI::NSSetMethodKind MK = *MKOpt;
10639
10640 switch (MK) {
10641 case NSAPI::NSMutableSet_addObject:
10642 case NSAPI::NSOrderedSet_setObjectAtIndex:
10643 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10644 case NSAPI::NSOrderedSet_insertObjectAtIndex:
10645 return 0;
10646 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10647 return 1;
10648 }
10649
10650 return None;
10651}
10652
10653void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10654 if (!Message->isInstanceMessage()) {
10655 return;
10656 }
10657
10658 Optional<int> ArgOpt;
10659
10660 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10661 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10662 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10663 return;
10664 }
10665
10666 int ArgIndex = *ArgOpt;
10667
Alex Denisove1d882c2015-03-04 17:55:52 +000010668 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10669 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10670 Arg = OE->getSourceExpr()->IgnoreImpCasts();
10671 }
10672
Alex Denisov5dfac812015-08-06 04:51:14 +000010673 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010674 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010675 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010676 Diag(Message->getSourceRange().getBegin(),
10677 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000010678 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000010679 }
10680 }
Alex Denisov5dfac812015-08-06 04:51:14 +000010681 } else {
10682 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10683
10684 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10685 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10686 }
10687
10688 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10689 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10690 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10691 ValueDecl *Decl = ReceiverRE->getDecl();
10692 Diag(Message->getSourceRange().getBegin(),
10693 diag::warn_objc_circular_container)
10694 << Decl->getName() << Decl->getName();
10695 if (!ArgRE->isObjCSelfExpr()) {
10696 Diag(Decl->getLocation(),
10697 diag::note_objc_circular_container_declared_here)
10698 << Decl->getName();
10699 }
10700 }
10701 }
10702 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
10703 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
10704 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
10705 ObjCIvarDecl *Decl = IvarRE->getDecl();
10706 Diag(Message->getSourceRange().getBegin(),
10707 diag::warn_objc_circular_container)
10708 << Decl->getName() << Decl->getName();
10709 Diag(Decl->getLocation(),
10710 diag::note_objc_circular_container_declared_here)
10711 << Decl->getName();
10712 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010713 }
10714 }
10715 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010716}
10717
John McCall31168b02011-06-15 23:02:42 +000010718/// Check a message send to see if it's likely to cause a retain cycle.
10719void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
10720 // Only check instance methods whose selector looks like a setter.
10721 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
10722 return;
10723
10724 // Try to find a variable that the receiver is strongly owned by.
10725 RetainCycleOwner owner;
10726 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010727 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000010728 return;
10729 } else {
10730 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
10731 owner.Variable = getCurMethodDecl()->getSelfDecl();
10732 owner.Loc = msg->getSuperLoc();
10733 owner.Range = msg->getSuperLoc();
10734 }
10735
10736 // Check whether the receiver is captured by any of the arguments.
10737 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
10738 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
10739 return diagnoseRetainCycle(*this, capturer, owner);
10740}
10741
10742/// Check a property assign to see if it's likely to cause a retain cycle.
10743void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
10744 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010745 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000010746 return;
10747
10748 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
10749 diagnoseRetainCycle(*this, capturer, owner);
10750}
10751
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010752void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
10753 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000010754 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010755 return;
10756
10757 // Because we don't have an expression for the variable, we have to set the
10758 // location explicitly here.
10759 Owner.Loc = Var->getLocation();
10760 Owner.Range = Var->getSourceRange();
10761
10762 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
10763 diagnoseRetainCycle(*this, Capturer, Owner);
10764}
10765
Ted Kremenek9304da92012-12-21 08:04:28 +000010766static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
10767 Expr *RHS, bool isProperty) {
10768 // Check if RHS is an Objective-C object literal, which also can get
10769 // immediately zapped in a weak reference. Note that we explicitly
10770 // allow ObjCStringLiterals, since those are designed to never really die.
10771 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010772
Ted Kremenek64873352012-12-21 22:46:35 +000010773 // This enum needs to match with the 'select' in
10774 // warn_objc_arc_literal_assign (off-by-1).
10775 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
10776 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
10777 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010778
10779 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000010780 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000010781 << (isProperty ? 0 : 1)
10782 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010783
10784 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000010785}
10786
Ted Kremenekc1f014a2012-12-21 19:45:30 +000010787static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
10788 Qualifiers::ObjCLifetime LT,
10789 Expr *RHS, bool isProperty) {
10790 // Strip off any implicit cast added to get to the one ARC-specific.
10791 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
10792 if (cast->getCastKind() == CK_ARCConsumeObject) {
10793 S.Diag(Loc, diag::warn_arc_retained_assign)
10794 << (LT == Qualifiers::OCL_ExplicitNone)
10795 << (isProperty ? 0 : 1)
10796 << RHS->getSourceRange();
10797 return true;
10798 }
10799 RHS = cast->getSubExpr();
10800 }
10801
10802 if (LT == Qualifiers::OCL_Weak &&
10803 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
10804 return true;
10805
10806 return false;
10807}
10808
Ted Kremenekb36234d2012-12-21 08:04:20 +000010809bool Sema::checkUnsafeAssigns(SourceLocation Loc,
10810 QualType LHS, Expr *RHS) {
10811 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
10812
10813 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
10814 return false;
10815
10816 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
10817 return true;
10818
10819 return false;
10820}
10821
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010822void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
10823 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010824 QualType LHSType;
10825 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010826 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010827 ObjCPropertyRefExpr *PRE
10828 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
10829 if (PRE && !PRE->isImplicitProperty()) {
10830 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10831 if (PD)
10832 LHSType = PD->getType();
10833 }
10834
10835 if (LHSType.isNull())
10836 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000010837
10838 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
10839
10840 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010841 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000010842 getCurFunction()->markSafeWeakUse(LHS);
10843 }
10844
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010845 if (checkUnsafeAssigns(Loc, LHSType, RHS))
10846 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000010847
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010848 // FIXME. Check for other life times.
10849 if (LT != Qualifiers::OCL_None)
10850 return;
10851
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010852 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010853 if (PRE->isImplicitProperty())
10854 return;
10855 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10856 if (!PD)
10857 return;
10858
Bill Wendling44426052012-12-20 19:22:21 +000010859 unsigned Attributes = PD->getPropertyAttributes();
10860 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010861 // when 'assign' attribute was not explicitly specified
10862 // by user, ignore it and rely on property type itself
10863 // for lifetime info.
10864 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
10865 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
10866 LHSType->isObjCRetainableType())
10867 return;
10868
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010869 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000010870 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010871 Diag(Loc, diag::warn_arc_retained_property_assign)
10872 << RHS->getSourceRange();
10873 return;
10874 }
10875 RHS = cast->getSubExpr();
10876 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010877 }
Bill Wendling44426052012-12-20 19:22:21 +000010878 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000010879 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
10880 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000010881 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010882 }
10883}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010884
10885//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
10886
10887namespace {
10888bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
10889 SourceLocation StmtLoc,
10890 const NullStmt *Body) {
10891 // Do not warn if the body is a macro that expands to nothing, e.g:
10892 //
10893 // #define CALL(x)
10894 // if (condition)
10895 // CALL(0);
10896 //
10897 if (Body->hasLeadingEmptyMacro())
10898 return false;
10899
10900 // Get line numbers of statement and body.
10901 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000010902 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010903 &StmtLineInvalid);
10904 if (StmtLineInvalid)
10905 return false;
10906
10907 bool BodyLineInvalid;
10908 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
10909 &BodyLineInvalid);
10910 if (BodyLineInvalid)
10911 return false;
10912
10913 // Warn if null statement and body are on the same line.
10914 if (StmtLine != BodyLine)
10915 return false;
10916
10917 return true;
10918}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010919} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010920
10921void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
10922 const Stmt *Body,
10923 unsigned DiagID) {
10924 // Since this is a syntactic check, don't emit diagnostic for template
10925 // instantiations, this just adds noise.
10926 if (CurrentInstantiationScope)
10927 return;
10928
10929 // The body should be a null statement.
10930 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10931 if (!NBody)
10932 return;
10933
10934 // Do the usual checks.
10935 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10936 return;
10937
10938 Diag(NBody->getSemiLoc(), DiagID);
10939 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10940}
10941
10942void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
10943 const Stmt *PossibleBody) {
10944 assert(!CurrentInstantiationScope); // Ensured by caller
10945
10946 SourceLocation StmtLoc;
10947 const Stmt *Body;
10948 unsigned DiagID;
10949 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
10950 StmtLoc = FS->getRParenLoc();
10951 Body = FS->getBody();
10952 DiagID = diag::warn_empty_for_body;
10953 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
10954 StmtLoc = WS->getCond()->getSourceRange().getEnd();
10955 Body = WS->getBody();
10956 DiagID = diag::warn_empty_while_body;
10957 } else
10958 return; // Neither `for' nor `while'.
10959
10960 // The body should be a null statement.
10961 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10962 if (!NBody)
10963 return;
10964
10965 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010966 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010967 return;
10968
10969 // Do the usual checks.
10970 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10971 return;
10972
10973 // `for(...);' and `while(...);' are popular idioms, so in order to keep
10974 // noise level low, emit diagnostics only if for/while is followed by a
10975 // CompoundStmt, e.g.:
10976 // for (int i = 0; i < n; i++);
10977 // {
10978 // a(i);
10979 // }
10980 // or if for/while is followed by a statement with more indentation
10981 // than for/while itself:
10982 // for (int i = 0; i < n; i++);
10983 // a(i);
10984 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
10985 if (!ProbableTypo) {
10986 bool BodyColInvalid;
10987 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
10988 PossibleBody->getLocStart(),
10989 &BodyColInvalid);
10990 if (BodyColInvalid)
10991 return;
10992
10993 bool StmtColInvalid;
10994 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
10995 S->getLocStart(),
10996 &StmtColInvalid);
10997 if (StmtColInvalid)
10998 return;
10999
11000 if (BodyCol > StmtCol)
11001 ProbableTypo = true;
11002 }
11003
11004 if (ProbableTypo) {
11005 Diag(NBody->getSemiLoc(), DiagID);
11006 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11007 }
11008}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011009
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011010//===--- CHECK: Warn on self move with std::move. -------------------------===//
11011
11012/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11013void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11014 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011015 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11016 return;
11017
11018 if (!ActiveTemplateInstantiations.empty())
11019 return;
11020
11021 // Strip parens and casts away.
11022 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11023 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11024
11025 // Check for a call expression
11026 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11027 if (!CE || CE->getNumArgs() != 1)
11028 return;
11029
11030 // Check for a call to std::move
11031 const FunctionDecl *FD = CE->getDirectCallee();
11032 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11033 !FD->getIdentifier()->isStr("move"))
11034 return;
11035
11036 // Get argument from std::move
11037 RHSExpr = CE->getArg(0);
11038
11039 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11040 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11041
11042 // Two DeclRefExpr's, check that the decls are the same.
11043 if (LHSDeclRef && RHSDeclRef) {
11044 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11045 return;
11046 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11047 RHSDeclRef->getDecl()->getCanonicalDecl())
11048 return;
11049
11050 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11051 << LHSExpr->getSourceRange()
11052 << RHSExpr->getSourceRange();
11053 return;
11054 }
11055
11056 // Member variables require a different approach to check for self moves.
11057 // MemberExpr's are the same if every nested MemberExpr refers to the same
11058 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11059 // the base Expr's are CXXThisExpr's.
11060 const Expr *LHSBase = LHSExpr;
11061 const Expr *RHSBase = RHSExpr;
11062 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11063 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11064 if (!LHSME || !RHSME)
11065 return;
11066
11067 while (LHSME && RHSME) {
11068 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11069 RHSME->getMemberDecl()->getCanonicalDecl())
11070 return;
11071
11072 LHSBase = LHSME->getBase();
11073 RHSBase = RHSME->getBase();
11074 LHSME = dyn_cast<MemberExpr>(LHSBase);
11075 RHSME = dyn_cast<MemberExpr>(RHSBase);
11076 }
11077
11078 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11079 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11080 if (LHSDeclRef && RHSDeclRef) {
11081 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11082 return;
11083 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11084 RHSDeclRef->getDecl()->getCanonicalDecl())
11085 return;
11086
11087 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11088 << LHSExpr->getSourceRange()
11089 << RHSExpr->getSourceRange();
11090 return;
11091 }
11092
11093 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11094 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11095 << LHSExpr->getSourceRange()
11096 << RHSExpr->getSourceRange();
11097}
11098
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011099//===--- Layout compatibility ----------------------------------------------//
11100
11101namespace {
11102
11103bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11104
11105/// \brief Check if two enumeration types are layout-compatible.
11106bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11107 // C++11 [dcl.enum] p8:
11108 // Two enumeration types are layout-compatible if they have the same
11109 // underlying type.
11110 return ED1->isComplete() && ED2->isComplete() &&
11111 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11112}
11113
11114/// \brief Check if two fields are layout-compatible.
11115bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11116 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11117 return false;
11118
11119 if (Field1->isBitField() != Field2->isBitField())
11120 return false;
11121
11122 if (Field1->isBitField()) {
11123 // Make sure that the bit-fields are the same length.
11124 unsigned Bits1 = Field1->getBitWidthValue(C);
11125 unsigned Bits2 = Field2->getBitWidthValue(C);
11126
11127 if (Bits1 != Bits2)
11128 return false;
11129 }
11130
11131 return true;
11132}
11133
11134/// \brief Check if two standard-layout structs are layout-compatible.
11135/// (C++11 [class.mem] p17)
11136bool isLayoutCompatibleStruct(ASTContext &C,
11137 RecordDecl *RD1,
11138 RecordDecl *RD2) {
11139 // If both records are C++ classes, check that base classes match.
11140 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11141 // If one of records is a CXXRecordDecl we are in C++ mode,
11142 // thus the other one is a CXXRecordDecl, too.
11143 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11144 // Check number of base classes.
11145 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11146 return false;
11147
11148 // Check the base classes.
11149 for (CXXRecordDecl::base_class_const_iterator
11150 Base1 = D1CXX->bases_begin(),
11151 BaseEnd1 = D1CXX->bases_end(),
11152 Base2 = D2CXX->bases_begin();
11153 Base1 != BaseEnd1;
11154 ++Base1, ++Base2) {
11155 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11156 return false;
11157 }
11158 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11159 // If only RD2 is a C++ class, it should have zero base classes.
11160 if (D2CXX->getNumBases() > 0)
11161 return false;
11162 }
11163
11164 // Check the fields.
11165 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11166 Field2End = RD2->field_end(),
11167 Field1 = RD1->field_begin(),
11168 Field1End = RD1->field_end();
11169 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11170 if (!isLayoutCompatible(C, *Field1, *Field2))
11171 return false;
11172 }
11173 if (Field1 != Field1End || Field2 != Field2End)
11174 return false;
11175
11176 return true;
11177}
11178
11179/// \brief Check if two standard-layout unions are layout-compatible.
11180/// (C++11 [class.mem] p18)
11181bool isLayoutCompatibleUnion(ASTContext &C,
11182 RecordDecl *RD1,
11183 RecordDecl *RD2) {
11184 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011185 for (auto *Field2 : RD2->fields())
11186 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011187
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011188 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011189 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11190 I = UnmatchedFields.begin(),
11191 E = UnmatchedFields.end();
11192
11193 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011194 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011195 bool Result = UnmatchedFields.erase(*I);
11196 (void) Result;
11197 assert(Result);
11198 break;
11199 }
11200 }
11201 if (I == E)
11202 return false;
11203 }
11204
11205 return UnmatchedFields.empty();
11206}
11207
11208bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11209 if (RD1->isUnion() != RD2->isUnion())
11210 return false;
11211
11212 if (RD1->isUnion())
11213 return isLayoutCompatibleUnion(C, RD1, RD2);
11214 else
11215 return isLayoutCompatibleStruct(C, RD1, RD2);
11216}
11217
11218/// \brief Check if two types are layout-compatible in C++11 sense.
11219bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11220 if (T1.isNull() || T2.isNull())
11221 return false;
11222
11223 // C++11 [basic.types] p11:
11224 // If two types T1 and T2 are the same type, then T1 and T2 are
11225 // layout-compatible types.
11226 if (C.hasSameType(T1, T2))
11227 return true;
11228
11229 T1 = T1.getCanonicalType().getUnqualifiedType();
11230 T2 = T2.getCanonicalType().getUnqualifiedType();
11231
11232 const Type::TypeClass TC1 = T1->getTypeClass();
11233 const Type::TypeClass TC2 = T2->getTypeClass();
11234
11235 if (TC1 != TC2)
11236 return false;
11237
11238 if (TC1 == Type::Enum) {
11239 return isLayoutCompatible(C,
11240 cast<EnumType>(T1)->getDecl(),
11241 cast<EnumType>(T2)->getDecl());
11242 } else if (TC1 == Type::Record) {
11243 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11244 return false;
11245
11246 return isLayoutCompatible(C,
11247 cast<RecordType>(T1)->getDecl(),
11248 cast<RecordType>(T2)->getDecl());
11249 }
11250
11251 return false;
11252}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011253} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011254
11255//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11256
11257namespace {
11258/// \brief Given a type tag expression find the type tag itself.
11259///
11260/// \param TypeExpr Type tag expression, as it appears in user's code.
11261///
11262/// \param VD Declaration of an identifier that appears in a type tag.
11263///
11264/// \param MagicValue Type tag magic value.
11265bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11266 const ValueDecl **VD, uint64_t *MagicValue) {
11267 while(true) {
11268 if (!TypeExpr)
11269 return false;
11270
11271 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11272
11273 switch (TypeExpr->getStmtClass()) {
11274 case Stmt::UnaryOperatorClass: {
11275 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11276 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11277 TypeExpr = UO->getSubExpr();
11278 continue;
11279 }
11280 return false;
11281 }
11282
11283 case Stmt::DeclRefExprClass: {
11284 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11285 *VD = DRE->getDecl();
11286 return true;
11287 }
11288
11289 case Stmt::IntegerLiteralClass: {
11290 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11291 llvm::APInt MagicValueAPInt = IL->getValue();
11292 if (MagicValueAPInt.getActiveBits() <= 64) {
11293 *MagicValue = MagicValueAPInt.getZExtValue();
11294 return true;
11295 } else
11296 return false;
11297 }
11298
11299 case Stmt::BinaryConditionalOperatorClass:
11300 case Stmt::ConditionalOperatorClass: {
11301 const AbstractConditionalOperator *ACO =
11302 cast<AbstractConditionalOperator>(TypeExpr);
11303 bool Result;
11304 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11305 if (Result)
11306 TypeExpr = ACO->getTrueExpr();
11307 else
11308 TypeExpr = ACO->getFalseExpr();
11309 continue;
11310 }
11311 return false;
11312 }
11313
11314 case Stmt::BinaryOperatorClass: {
11315 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11316 if (BO->getOpcode() == BO_Comma) {
11317 TypeExpr = BO->getRHS();
11318 continue;
11319 }
11320 return false;
11321 }
11322
11323 default:
11324 return false;
11325 }
11326 }
11327}
11328
11329/// \brief Retrieve the C type corresponding to type tag TypeExpr.
11330///
11331/// \param TypeExpr Expression that specifies a type tag.
11332///
11333/// \param MagicValues Registered magic values.
11334///
11335/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11336/// kind.
11337///
11338/// \param TypeInfo Information about the corresponding C type.
11339///
11340/// \returns true if the corresponding C type was found.
11341bool GetMatchingCType(
11342 const IdentifierInfo *ArgumentKind,
11343 const Expr *TypeExpr, const ASTContext &Ctx,
11344 const llvm::DenseMap<Sema::TypeTagMagicValue,
11345 Sema::TypeTagData> *MagicValues,
11346 bool &FoundWrongKind,
11347 Sema::TypeTagData &TypeInfo) {
11348 FoundWrongKind = false;
11349
11350 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000011351 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011352
11353 uint64_t MagicValue;
11354
11355 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11356 return false;
11357
11358 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000011359 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011360 if (I->getArgumentKind() != ArgumentKind) {
11361 FoundWrongKind = true;
11362 return false;
11363 }
11364 TypeInfo.Type = I->getMatchingCType();
11365 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11366 TypeInfo.MustBeNull = I->getMustBeNull();
11367 return true;
11368 }
11369 return false;
11370 }
11371
11372 if (!MagicValues)
11373 return false;
11374
11375 llvm::DenseMap<Sema::TypeTagMagicValue,
11376 Sema::TypeTagData>::const_iterator I =
11377 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11378 if (I == MagicValues->end())
11379 return false;
11380
11381 TypeInfo = I->second;
11382 return true;
11383}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011384} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011385
11386void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11387 uint64_t MagicValue, QualType Type,
11388 bool LayoutCompatible,
11389 bool MustBeNull) {
11390 if (!TypeTagForDatatypeMagicValues)
11391 TypeTagForDatatypeMagicValues.reset(
11392 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11393
11394 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11395 (*TypeTagForDatatypeMagicValues)[Magic] =
11396 TypeTagData(Type, LayoutCompatible, MustBeNull);
11397}
11398
11399namespace {
11400bool IsSameCharType(QualType T1, QualType T2) {
11401 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11402 if (!BT1)
11403 return false;
11404
11405 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11406 if (!BT2)
11407 return false;
11408
11409 BuiltinType::Kind T1Kind = BT1->getKind();
11410 BuiltinType::Kind T2Kind = BT2->getKind();
11411
11412 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
11413 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
11414 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11415 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11416}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011417} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011418
11419void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11420 const Expr * const *ExprArgs) {
11421 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11422 bool IsPointerAttr = Attr->getIsPointer();
11423
11424 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11425 bool FoundWrongKind;
11426 TypeTagData TypeInfo;
11427 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11428 TypeTagForDatatypeMagicValues.get(),
11429 FoundWrongKind, TypeInfo)) {
11430 if (FoundWrongKind)
11431 Diag(TypeTagExpr->getExprLoc(),
11432 diag::warn_type_tag_for_datatype_wrong_kind)
11433 << TypeTagExpr->getSourceRange();
11434 return;
11435 }
11436
11437 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11438 if (IsPointerAttr) {
11439 // Skip implicit cast of pointer to `void *' (as a function argument).
11440 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000011441 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000011442 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011443 ArgumentExpr = ICE->getSubExpr();
11444 }
11445 QualType ArgumentType = ArgumentExpr->getType();
11446
11447 // Passing a `void*' pointer shouldn't trigger a warning.
11448 if (IsPointerAttr && ArgumentType->isVoidPointerType())
11449 return;
11450
11451 if (TypeInfo.MustBeNull) {
11452 // Type tag with matching void type requires a null pointer.
11453 if (!ArgumentExpr->isNullPointerConstant(Context,
11454 Expr::NPC_ValueDependentIsNotNull)) {
11455 Diag(ArgumentExpr->getExprLoc(),
11456 diag::warn_type_safety_null_pointer_required)
11457 << ArgumentKind->getName()
11458 << ArgumentExpr->getSourceRange()
11459 << TypeTagExpr->getSourceRange();
11460 }
11461 return;
11462 }
11463
11464 QualType RequiredType = TypeInfo.Type;
11465 if (IsPointerAttr)
11466 RequiredType = Context.getPointerType(RequiredType);
11467
11468 bool mismatch = false;
11469 if (!TypeInfo.LayoutCompatible) {
11470 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
11471
11472 // C++11 [basic.fundamental] p1:
11473 // Plain char, signed char, and unsigned char are three distinct types.
11474 //
11475 // But we treat plain `char' as equivalent to `signed char' or `unsigned
11476 // char' depending on the current char signedness mode.
11477 if (mismatch)
11478 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
11479 RequiredType->getPointeeType())) ||
11480 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
11481 mismatch = false;
11482 } else
11483 if (IsPointerAttr)
11484 mismatch = !isLayoutCompatible(Context,
11485 ArgumentType->getPointeeType(),
11486 RequiredType->getPointeeType());
11487 else
11488 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
11489
11490 if (mismatch)
11491 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000011492 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011493 << TypeInfo.LayoutCompatible << RequiredType
11494 << ArgumentExpr->getSourceRange()
11495 << TypeTagExpr->getSourceRange();
11496}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011497
11498void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11499 CharUnits Alignment) {
11500 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
11501}
11502
11503void Sema::DiagnoseMisalignedMembers() {
11504 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000011505 const NamedDecl *ND = m.RD;
11506 if (ND->getName().empty()) {
11507 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
11508 ND = TD;
11509 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011510 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000011511 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011512 }
11513 MisalignedMembers.clear();
11514}
11515
11516void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
11517 if (!T->isPointerType())
11518 return;
11519 if (isa<UnaryOperator>(E) &&
11520 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
11521 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11522 if (isa<MemberExpr>(Op)) {
11523 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
11524 MisalignedMember(Op));
11525 if (MA != MisalignedMembers.end() &&
11526 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)
11527 MisalignedMembers.erase(MA);
11528 }
11529 }
11530}
11531
11532void Sema::RefersToMemberWithReducedAlignment(
11533 Expr *E,
11534 std::function<void(Expr *, RecordDecl *, ValueDecl *, CharUnits)> Action) {
11535 const auto *ME = dyn_cast<MemberExpr>(E);
11536 while (ME && isa<FieldDecl>(ME->getMemberDecl())) {
11537 QualType BaseType = ME->getBase()->getType();
11538 if (ME->isArrow())
11539 BaseType = BaseType->getPointeeType();
11540 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
11541
11542 ValueDecl *MD = ME->getMemberDecl();
11543 bool ByteAligned = Context.getTypeAlignInChars(MD->getType()).isOne();
11544 if (ByteAligned) // Attribute packed does not have any effect.
11545 break;
11546
11547 if (!ByteAligned &&
11548 (RD->hasAttr<PackedAttr>() || (MD->hasAttr<PackedAttr>()))) {
11549 CharUnits Alignment = std::min(Context.getTypeAlignInChars(MD->getType()),
11550 Context.getTypeAlignInChars(BaseType));
11551 // Notify that this expression designates a member with reduced alignment
11552 Action(E, RD, MD, Alignment);
11553 break;
11554 }
11555 ME = dyn_cast<MemberExpr>(ME->getBase());
11556 }
11557}
11558
11559void Sema::CheckAddressOfPackedMember(Expr *rhs) {
11560 using namespace std::placeholders;
11561 RefersToMemberWithReducedAlignment(
11562 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
11563 _2, _3, _4));
11564}
11565