blob: 078b826c918a0257b65c4050f20f0850f0b3eb7a [file] [log] [blame]
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattnerb87b1b32007-08-10 20:18:51 +000015#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000017#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000020#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000021#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000022#include "clang/AST/ExprObjC.h"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000023#include "clang/AST/ExprOpenMP.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000030#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000035#include "clang/Sema/SemaInternal.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000036#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000037#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "llvm/ADT/SmallString.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000039#include "llvm/Support/ConvertUTF.h"
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +000040#include "llvm/Support/Format.h"
41#include "llvm/Support/Locale.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000042#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000043
Chris Lattnerb87b1b32007-08-10 20:18:51 +000044using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000045using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000046
Chris Lattnera26fb342009-02-18 17:49:48 +000047SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
48 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000049 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
50 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000051}
52
John McCallbebede42011-02-26 05:39:39 +000053/// Checks that a call expression's argument count is the desired number.
54/// This is useful when doing custom type-checking. Returns true on error.
55static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
56 unsigned argCount = call->getNumArgs();
57 if (argCount == desiredArgCount) return false;
58
59 if (argCount < desiredArgCount)
60 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
61 << 0 /*function call*/ << desiredArgCount << argCount
62 << call->getSourceRange();
63
64 // Highlight all the excess arguments.
65 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
66 call->getArg(argCount - 1)->getLocEnd());
67
68 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
69 << 0 /*function call*/ << desiredArgCount << argCount
70 << call->getArg(1)->getSourceRange();
71}
72
Julien Lerouge4a5b4442012-04-28 17:39:16 +000073/// Check that the first argument to __builtin_annotation is an integer
74/// and the second argument is a non-wide string literal.
75static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
76 if (checkArgCount(S, TheCall, 2))
77 return true;
78
79 // First argument should be an integer.
80 Expr *ValArg = TheCall->getArg(0);
81 QualType Ty = ValArg->getType();
82 if (!Ty->isIntegerType()) {
83 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
84 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000085 return true;
86 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000087
88 // Second argument should be a constant string.
89 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
90 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
91 if (!Literal || !Literal->isAscii()) {
92 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
93 << StrArg->getSourceRange();
94 return true;
95 }
96
97 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000098 return false;
99}
100
Richard Smith6cbd65d2013-07-11 02:27:57 +0000101/// Check that the argument to __builtin_addressof is a glvalue, and set the
102/// result type to the corresponding pointer type.
103static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
104 if (checkArgCount(S, TheCall, 1))
105 return true;
106
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000107 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000108 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
109 if (ResultType.isNull())
110 return true;
111
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000112 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000113 TheCall->setType(ResultType);
114 return false;
115}
116
John McCall03107a42015-10-29 20:48:01 +0000117static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
118 if (checkArgCount(S, TheCall, 3))
119 return true;
120
121 // First two arguments should be integers.
122 for (unsigned I = 0; I < 2; ++I) {
123 Expr *Arg = TheCall->getArg(I);
124 QualType Ty = Arg->getType();
125 if (!Ty->isIntegerType()) {
126 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
127 << Ty << Arg->getSourceRange();
128 return true;
129 }
130 }
131
132 // Third argument should be a pointer to a non-const integer.
133 // IRGen correctly handles volatile, restrict, and address spaces, and
134 // the other qualifiers aren't possible.
135 {
136 Expr *Arg = TheCall->getArg(2);
137 QualType Ty = Arg->getType();
138 const auto *PtrTy = Ty->getAs<PointerType>();
139 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
140 !PtrTy->getPointeeType().isConstQualified())) {
141 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
142 << Ty << Arg->getSourceRange();
143 return true;
144 }
145 }
146
147 return false;
148}
149
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000150static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
151 CallExpr *TheCall, unsigned SizeIdx,
152 unsigned DstSizeIdx) {
153 if (TheCall->getNumArgs() <= SizeIdx ||
154 TheCall->getNumArgs() <= DstSizeIdx)
155 return;
156
157 const Expr *SizeArg = TheCall->getArg(SizeIdx);
158 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
159
160 llvm::APSInt Size, DstSize;
161
162 // find out if both sizes are known at compile time
163 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
164 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
165 return;
166
167 if (Size.ule(DstSize))
168 return;
169
170 // confirmed overflow so generate the diagnostic.
171 IdentifierInfo *FnName = FDecl->getIdentifier();
172 SourceLocation SL = TheCall->getLocStart();
173 SourceRange SR = TheCall->getSourceRange();
174
175 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
176}
177
Peter Collingbournef7706832014-12-12 23:41:25 +0000178static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
179 if (checkArgCount(S, BuiltinCall, 2))
180 return true;
181
182 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
183 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
184 Expr *Call = BuiltinCall->getArg(0);
185 Expr *Chain = BuiltinCall->getArg(1);
186
187 if (Call->getStmtClass() != Stmt::CallExprClass) {
188 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
189 << Call->getSourceRange();
190 return true;
191 }
192
193 auto CE = cast<CallExpr>(Call);
194 if (CE->getCallee()->getType()->isBlockPointerType()) {
195 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
196 << Call->getSourceRange();
197 return true;
198 }
199
200 const Decl *TargetDecl = CE->getCalleeDecl();
201 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
202 if (FD->getBuiltinID()) {
203 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
204 << Call->getSourceRange();
205 return true;
206 }
207
208 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
209 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
210 << Call->getSourceRange();
211 return true;
212 }
213
214 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
215 if (ChainResult.isInvalid())
216 return true;
217 if (!ChainResult.get()->getType()->isPointerType()) {
218 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
219 << Chain->getSourceRange();
220 return true;
221 }
222
David Majnemerced8bdf2015-02-25 17:36:15 +0000223 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000224 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
225 QualType BuiltinTy = S.Context.getFunctionType(
226 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
227 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
228
229 Builtin =
230 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
231
232 BuiltinCall->setType(CE->getType());
233 BuiltinCall->setValueKind(CE->getValueKind());
234 BuiltinCall->setObjectKind(CE->getObjectKind());
235 BuiltinCall->setCallee(Builtin);
236 BuiltinCall->setArg(1, ChainResult.get());
237
238 return false;
239}
240
Reid Kleckner1d59f992015-01-22 01:36:17 +0000241static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
242 Scope::ScopeFlags NeededScopeFlags,
243 unsigned DiagID) {
244 // Scopes aren't available during instantiation. Fortunately, builtin
245 // functions cannot be template args so they cannot be formed through template
246 // instantiation. Therefore checking once during the parse is sufficient.
247 if (!SemaRef.ActiveTemplateInstantiations.empty())
248 return false;
249
250 Scope *S = SemaRef.getCurScope();
251 while (S && !S->isSEHExceptScope())
252 S = S->getParent();
253 if (!S || !(S->getFlags() & NeededScopeFlags)) {
254 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
255 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
256 << DRE->getDecl()->getIdentifier();
257 return true;
258 }
259
260 return false;
261}
262
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000263static inline bool isBlockPointer(Expr *Arg) {
264 return Arg->getType()->isBlockPointerType();
265}
266
267/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
268/// void*, which is a requirement of device side enqueue.
269static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
270 const BlockPointerType *BPT =
271 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
272 ArrayRef<QualType> Params =
273 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
274 unsigned ArgCounter = 0;
275 bool IllegalParams = false;
276 // Iterate through the block parameters until either one is found that is not
277 // a local void*, or the block is valid.
278 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
279 I != E; ++I, ++ArgCounter) {
280 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
281 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
282 LangAS::opencl_local) {
283 // Get the location of the error. If a block literal has been passed
284 // (BlockExpr) then we can point straight to the offending argument,
285 // else we just point to the variable reference.
286 SourceLocation ErrorLoc;
287 if (isa<BlockExpr>(BlockArg)) {
288 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
289 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
290 } else if (isa<DeclRefExpr>(BlockArg)) {
291 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
292 }
293 S.Diag(ErrorLoc,
294 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
295 IllegalParams = true;
296 }
297 }
298
299 return IllegalParams;
300}
301
302/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
303/// get_kernel_work_group_size
304/// and get_kernel_preferred_work_group_size_multiple builtin functions.
305static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
306 if (checkArgCount(S, TheCall, 1))
307 return true;
308
309 Expr *BlockArg = TheCall->getArg(0);
310 if (!isBlockPointer(BlockArg)) {
311 S.Diag(BlockArg->getLocStart(),
312 diag::err_opencl_enqueue_kernel_expected_type) << "block";
313 return true;
314 }
315 return checkOpenCLBlockArgs(S, BlockArg);
316}
317
318static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
319 unsigned Start, unsigned End);
320
321/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
322/// 'local void*' parameter of passed block.
323static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
324 Expr *BlockArg,
325 unsigned NumNonVarArgs) {
326 const BlockPointerType *BPT =
327 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
328 unsigned NumBlockParams =
329 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
330 unsigned TotalNumArgs = TheCall->getNumArgs();
331
332 // For each argument passed to the block, a corresponding uint needs to
333 // be passed to describe the size of the local memory.
334 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
335 S.Diag(TheCall->getLocStart(),
336 diag::err_opencl_enqueue_kernel_local_size_args);
337 return true;
338 }
339
340 // Check that the sizes of the local memory are specified by integers.
341 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
342 TotalNumArgs - 1);
343}
344
345/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
346/// overload formats specified in Table 6.13.17.1.
347/// int enqueue_kernel(queue_t queue,
348/// kernel_enqueue_flags_t flags,
349/// const ndrange_t ndrange,
350/// void (^block)(void))
351/// int enqueue_kernel(queue_t queue,
352/// kernel_enqueue_flags_t flags,
353/// const ndrange_t ndrange,
354/// uint num_events_in_wait_list,
355/// clk_event_t *event_wait_list,
356/// clk_event_t *event_ret,
357/// void (^block)(void))
358/// int enqueue_kernel(queue_t queue,
359/// kernel_enqueue_flags_t flags,
360/// const ndrange_t ndrange,
361/// void (^block)(local void*, ...),
362/// uint size0, ...)
363/// int enqueue_kernel(queue_t queue,
364/// kernel_enqueue_flags_t flags,
365/// const ndrange_t ndrange,
366/// uint num_events_in_wait_list,
367/// clk_event_t *event_wait_list,
368/// clk_event_t *event_ret,
369/// void (^block)(local void*, ...),
370/// uint size0, ...)
371static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
372 unsigned NumArgs = TheCall->getNumArgs();
373
374 if (NumArgs < 4) {
375 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
376 return true;
377 }
378
379 Expr *Arg0 = TheCall->getArg(0);
380 Expr *Arg1 = TheCall->getArg(1);
381 Expr *Arg2 = TheCall->getArg(2);
382 Expr *Arg3 = TheCall->getArg(3);
383
384 // First argument always needs to be a queue_t type.
385 if (!Arg0->getType()->isQueueT()) {
386 S.Diag(TheCall->getArg(0)->getLocStart(),
387 diag::err_opencl_enqueue_kernel_expected_type)
388 << S.Context.OCLQueueTy;
389 return true;
390 }
391
392 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
393 if (!Arg1->getType()->isIntegerType()) {
394 S.Diag(TheCall->getArg(1)->getLocStart(),
395 diag::err_opencl_enqueue_kernel_expected_type)
396 << "'kernel_enqueue_flags_t' (i.e. uint)";
397 return true;
398 }
399
400 // Third argument is always an ndrange_t type.
401 if (!Arg2->getType()->isNDRangeT()) {
402 S.Diag(TheCall->getArg(2)->getLocStart(),
403 diag::err_opencl_enqueue_kernel_expected_type)
404 << S.Context.OCLNDRangeTy;
405 return true;
406 }
407
408 // With four arguments, there is only one form that the function could be
409 // called in: no events and no variable arguments.
410 if (NumArgs == 4) {
411 // check that the last argument is the right block type.
412 if (!isBlockPointer(Arg3)) {
413 S.Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
414 << "block";
415 return true;
416 }
417 // we have a block type, check the prototype
418 const BlockPointerType *BPT =
419 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
420 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
421 S.Diag(Arg3->getLocStart(),
422 diag::err_opencl_enqueue_kernel_blocks_no_args);
423 return true;
424 }
425 return false;
426 }
427 // we can have block + varargs.
428 if (isBlockPointer(Arg3))
429 return (checkOpenCLBlockArgs(S, Arg3) ||
430 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
431 // last two cases with either exactly 7 args or 7 args and varargs.
432 if (NumArgs >= 7) {
433 // check common block argument.
434 Expr *Arg6 = TheCall->getArg(6);
435 if (!isBlockPointer(Arg6)) {
436 S.Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
437 << "block";
438 return true;
439 }
440 if (checkOpenCLBlockArgs(S, Arg6))
441 return true;
442
443 // Forth argument has to be any integer type.
444 if (!Arg3->getType()->isIntegerType()) {
445 S.Diag(TheCall->getArg(3)->getLocStart(),
446 diag::err_opencl_enqueue_kernel_expected_type)
447 << "integer";
448 return true;
449 }
450 // check remaining common arguments.
451 Expr *Arg4 = TheCall->getArg(4);
452 Expr *Arg5 = TheCall->getArg(5);
453
454 // Fith argument is always passed as pointers to clk_event_t.
455 if (!Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
456 S.Diag(TheCall->getArg(4)->getLocStart(),
457 diag::err_opencl_enqueue_kernel_expected_type)
458 << S.Context.getPointerType(S.Context.OCLClkEventTy);
459 return true;
460 }
461
462 // Sixth argument is always passed as pointers to clk_event_t.
463 if (!(Arg5->getType()->isPointerType() &&
464 Arg5->getType()->getPointeeType()->isClkEventT())) {
465 S.Diag(TheCall->getArg(5)->getLocStart(),
466 diag::err_opencl_enqueue_kernel_expected_type)
467 << S.Context.getPointerType(S.Context.OCLClkEventTy);
468 return true;
469 }
470
471 if (NumArgs == 7)
472 return false;
473
474 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
475 }
476
477 // None of the specific case has been detected, give generic error
478 S.Diag(TheCall->getLocStart(),
479 diag::err_opencl_enqueue_kernel_incorrect_args);
480 return true;
481}
482
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000483/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000484static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000485 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000486}
487
488/// Returns true if pipe element type is different from the pointer.
489static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
490 const Expr *Arg0 = Call->getArg(0);
491 // First argument type should always be pipe.
492 if (!Arg0->getType()->isPipeType()) {
493 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000494 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000495 return true;
496 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000497 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000498 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
499 // Validates the access qualifier is compatible with the call.
500 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
501 // read_only and write_only, and assumed to be read_only if no qualifier is
502 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000503 switch (Call->getDirectCallee()->getBuiltinID()) {
504 case Builtin::BIread_pipe:
505 case Builtin::BIreserve_read_pipe:
506 case Builtin::BIcommit_read_pipe:
507 case Builtin::BIwork_group_reserve_read_pipe:
508 case Builtin::BIsub_group_reserve_read_pipe:
509 case Builtin::BIwork_group_commit_read_pipe:
510 case Builtin::BIsub_group_commit_read_pipe:
511 if (!(!AccessQual || AccessQual->isReadOnly())) {
512 S.Diag(Arg0->getLocStart(),
513 diag::err_opencl_builtin_pipe_invalid_access_modifier)
514 << "read_only" << Arg0->getSourceRange();
515 return true;
516 }
517 break;
518 case Builtin::BIwrite_pipe:
519 case Builtin::BIreserve_write_pipe:
520 case Builtin::BIcommit_write_pipe:
521 case Builtin::BIwork_group_reserve_write_pipe:
522 case Builtin::BIsub_group_reserve_write_pipe:
523 case Builtin::BIwork_group_commit_write_pipe:
524 case Builtin::BIsub_group_commit_write_pipe:
525 if (!(AccessQual && AccessQual->isWriteOnly())) {
526 S.Diag(Arg0->getLocStart(),
527 diag::err_opencl_builtin_pipe_invalid_access_modifier)
528 << "write_only" << Arg0->getSourceRange();
529 return true;
530 }
531 break;
532 default:
533 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000534 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000535 return false;
536}
537
538/// Returns true if pipe element type is different from the pointer.
539static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
540 const Expr *Arg0 = Call->getArg(0);
541 const Expr *ArgIdx = Call->getArg(Idx);
542 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000543 const QualType EltTy = PipeTy->getElementType();
544 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000545 // The Idx argument should be a pointer and the type of the pointer and
546 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000547 if (!ArgTy ||
548 !S.Context.hasSameType(
549 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000550 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000551 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000552 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000553 return true;
554 }
555 return false;
556}
557
558// \brief Performs semantic analysis for the read/write_pipe call.
559// \param S Reference to the semantic analyzer.
560// \param Call A pointer to the builtin call.
561// \return True if a semantic error has been found, false otherwise.
562static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000563 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
564 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000565 switch (Call->getNumArgs()) {
566 case 2: {
567 if (checkOpenCLPipeArg(S, Call))
568 return true;
569 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000570 // read/write_pipe(pipe T, T*).
571 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000572 if (checkOpenCLPipePacketType(S, Call, 1))
573 return true;
574 } break;
575
576 case 4: {
577 if (checkOpenCLPipeArg(S, Call))
578 return true;
579 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000580 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
581 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000582 if (!Call->getArg(1)->getType()->isReserveIDT()) {
583 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000584 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000585 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000586 return true;
587 }
588
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000589 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000590 const Expr *Arg2 = Call->getArg(2);
591 if (!Arg2->getType()->isIntegerType() &&
592 !Arg2->getType()->isUnsignedIntegerType()) {
593 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000594 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000595 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000596 return true;
597 }
598
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000599 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000600 if (checkOpenCLPipePacketType(S, Call, 3))
601 return true;
602 } break;
603 default:
604 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000605 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000606 return true;
607 }
608
609 return false;
610}
611
612// \brief Performs a semantic analysis on the {work_group_/sub_group_
613// /_}reserve_{read/write}_pipe
614// \param S Reference to the semantic analyzer.
615// \param Call The call to the builtin function to be analyzed.
616// \return True if a semantic error was found, false otherwise.
617static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
618 if (checkArgCount(S, Call, 2))
619 return true;
620
621 if (checkOpenCLPipeArg(S, Call))
622 return true;
623
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000624 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000625 if (!Call->getArg(1)->getType()->isIntegerType() &&
626 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
627 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000628 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000629 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000630 return true;
631 }
632
633 return false;
634}
635
636// \brief Performs a semantic analysis on {work_group_/sub_group_
637// /_}commit_{read/write}_pipe
638// \param S Reference to the semantic analyzer.
639// \param Call The call to the builtin function to be analyzed.
640// \return True if a semantic error was found, false otherwise.
641static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
642 if (checkArgCount(S, Call, 2))
643 return true;
644
645 if (checkOpenCLPipeArg(S, Call))
646 return true;
647
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000648 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000649 if (!Call->getArg(1)->getType()->isReserveIDT()) {
650 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000651 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000652 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000653 return true;
654 }
655
656 return false;
657}
658
659// \brief Performs a semantic analysis on the call to built-in Pipe
660// Query Functions.
661// \param S Reference to the semantic analyzer.
662// \param Call The call to the builtin function to be analyzed.
663// \return True if a semantic error was found, false otherwise.
664static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
665 if (checkArgCount(S, Call, 1))
666 return true;
667
668 if (!Call->getArg(0)->getType()->isPipeType()) {
669 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000670 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000671 return true;
672 }
673
674 return false;
675}
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +0000676// \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
Yaxun Liuf7449a12016-05-20 19:54:38 +0000677// \brief Performs semantic analysis for the to_global/local/private call.
678// \param S Reference to the semantic analyzer.
679// \param BuiltinID ID of the builtin function.
680// \param Call A pointer to the builtin call.
681// \return True if a semantic error has been found, false otherwise.
682static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
683 CallExpr *Call) {
Yaxun Liuf7449a12016-05-20 19:54:38 +0000684 if (Call->getNumArgs() != 1) {
685 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
686 << Call->getDirectCallee() << Call->getSourceRange();
687 return true;
688 }
689
690 auto RT = Call->getArg(0)->getType();
691 if (!RT->isPointerType() || RT->getPointeeType()
692 .getAddressSpace() == LangAS::opencl_constant) {
693 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
694 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
695 return true;
696 }
697
698 RT = RT->getPointeeType();
699 auto Qual = RT.getQualifiers();
700 switch (BuiltinID) {
701 case Builtin::BIto_global:
702 Qual.setAddressSpace(LangAS::opencl_global);
703 break;
704 case Builtin::BIto_local:
705 Qual.setAddressSpace(LangAS::opencl_local);
706 break;
707 default:
708 Qual.removeAddressSpace();
709 }
710 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
711 RT.getUnqualifiedType(), Qual)));
712
713 return false;
714}
715
John McCalldadc5752010-08-24 06:29:42 +0000716ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000717Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
718 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000719 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000720
Chris Lattner3be167f2010-10-01 23:23:24 +0000721 // Find out if any arguments are required to be integer constant expressions.
722 unsigned ICEArguments = 0;
723 ASTContext::GetBuiltinTypeError Error;
724 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
725 if (Error != ASTContext::GE_None)
726 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
727
728 // If any arguments are required to be ICE's, check and diagnose.
729 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
730 // Skip arguments not required to be ICE's.
731 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
732
733 llvm::APSInt Result;
734 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
735 return true;
736 ICEArguments &= ~(1 << ArgNo);
737 }
738
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000739 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000740 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000741 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000742 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000743 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000744 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000745 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000746 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000747 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000748 if (SemaBuiltinVAStart(TheCall))
749 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000750 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000751 case Builtin::BI__va_start: {
752 switch (Context.getTargetInfo().getTriple().getArch()) {
753 case llvm::Triple::arm:
754 case llvm::Triple::thumb:
755 if (SemaBuiltinVAStartARM(TheCall))
756 return ExprError();
757 break;
758 default:
759 if (SemaBuiltinVAStart(TheCall))
760 return ExprError();
761 break;
762 }
763 break;
764 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000765 case Builtin::BI__builtin_isgreater:
766 case Builtin::BI__builtin_isgreaterequal:
767 case Builtin::BI__builtin_isless:
768 case Builtin::BI__builtin_islessequal:
769 case Builtin::BI__builtin_islessgreater:
770 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000771 if (SemaBuiltinUnorderedCompare(TheCall))
772 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000773 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000774 case Builtin::BI__builtin_fpclassify:
775 if (SemaBuiltinFPClassification(TheCall, 6))
776 return ExprError();
777 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000778 case Builtin::BI__builtin_isfinite:
779 case Builtin::BI__builtin_isinf:
780 case Builtin::BI__builtin_isinf_sign:
781 case Builtin::BI__builtin_isnan:
782 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000783 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000784 return ExprError();
785 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000786 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000787 return SemaBuiltinShuffleVector(TheCall);
788 // TheCall will be freed by the smart pointer here, but that's fine, since
789 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000790 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000791 if (SemaBuiltinPrefetch(TheCall))
792 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000793 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000794 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000795 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000796 if (SemaBuiltinAssume(TheCall))
797 return ExprError();
798 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000799 case Builtin::BI__builtin_assume_aligned:
800 if (SemaBuiltinAssumeAligned(TheCall))
801 return ExprError();
802 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000803 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000804 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000805 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000806 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000807 case Builtin::BI__builtin_longjmp:
808 if (SemaBuiltinLongjmp(TheCall))
809 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000810 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000811 case Builtin::BI__builtin_setjmp:
812 if (SemaBuiltinSetjmp(TheCall))
813 return ExprError();
814 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000815 case Builtin::BI_setjmp:
816 case Builtin::BI_setjmpex:
817 if (checkArgCount(*this, TheCall, 1))
818 return true;
819 break;
John McCallbebede42011-02-26 05:39:39 +0000820
821 case Builtin::BI__builtin_classify_type:
822 if (checkArgCount(*this, TheCall, 1)) return true;
823 TheCall->setType(Context.IntTy);
824 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000825 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000826 if (checkArgCount(*this, TheCall, 1)) return true;
827 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000828 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000829 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000830 case Builtin::BI__sync_fetch_and_add_1:
831 case Builtin::BI__sync_fetch_and_add_2:
832 case Builtin::BI__sync_fetch_and_add_4:
833 case Builtin::BI__sync_fetch_and_add_8:
834 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000835 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000836 case Builtin::BI__sync_fetch_and_sub_1:
837 case Builtin::BI__sync_fetch_and_sub_2:
838 case Builtin::BI__sync_fetch_and_sub_4:
839 case Builtin::BI__sync_fetch_and_sub_8:
840 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000841 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000842 case Builtin::BI__sync_fetch_and_or_1:
843 case Builtin::BI__sync_fetch_and_or_2:
844 case Builtin::BI__sync_fetch_and_or_4:
845 case Builtin::BI__sync_fetch_and_or_8:
846 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000847 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000848 case Builtin::BI__sync_fetch_and_and_1:
849 case Builtin::BI__sync_fetch_and_and_2:
850 case Builtin::BI__sync_fetch_and_and_4:
851 case Builtin::BI__sync_fetch_and_and_8:
852 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000853 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000854 case Builtin::BI__sync_fetch_and_xor_1:
855 case Builtin::BI__sync_fetch_and_xor_2:
856 case Builtin::BI__sync_fetch_and_xor_4:
857 case Builtin::BI__sync_fetch_and_xor_8:
858 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000859 case Builtin::BI__sync_fetch_and_nand:
860 case Builtin::BI__sync_fetch_and_nand_1:
861 case Builtin::BI__sync_fetch_and_nand_2:
862 case Builtin::BI__sync_fetch_and_nand_4:
863 case Builtin::BI__sync_fetch_and_nand_8:
864 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000865 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000866 case Builtin::BI__sync_add_and_fetch_1:
867 case Builtin::BI__sync_add_and_fetch_2:
868 case Builtin::BI__sync_add_and_fetch_4:
869 case Builtin::BI__sync_add_and_fetch_8:
870 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000871 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000872 case Builtin::BI__sync_sub_and_fetch_1:
873 case Builtin::BI__sync_sub_and_fetch_2:
874 case Builtin::BI__sync_sub_and_fetch_4:
875 case Builtin::BI__sync_sub_and_fetch_8:
876 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000877 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000878 case Builtin::BI__sync_and_and_fetch_1:
879 case Builtin::BI__sync_and_and_fetch_2:
880 case Builtin::BI__sync_and_and_fetch_4:
881 case Builtin::BI__sync_and_and_fetch_8:
882 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000883 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000884 case Builtin::BI__sync_or_and_fetch_1:
885 case Builtin::BI__sync_or_and_fetch_2:
886 case Builtin::BI__sync_or_and_fetch_4:
887 case Builtin::BI__sync_or_and_fetch_8:
888 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000889 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000890 case Builtin::BI__sync_xor_and_fetch_1:
891 case Builtin::BI__sync_xor_and_fetch_2:
892 case Builtin::BI__sync_xor_and_fetch_4:
893 case Builtin::BI__sync_xor_and_fetch_8:
894 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000895 case Builtin::BI__sync_nand_and_fetch:
896 case Builtin::BI__sync_nand_and_fetch_1:
897 case Builtin::BI__sync_nand_and_fetch_2:
898 case Builtin::BI__sync_nand_and_fetch_4:
899 case Builtin::BI__sync_nand_and_fetch_8:
900 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000901 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000902 case Builtin::BI__sync_val_compare_and_swap_1:
903 case Builtin::BI__sync_val_compare_and_swap_2:
904 case Builtin::BI__sync_val_compare_and_swap_4:
905 case Builtin::BI__sync_val_compare_and_swap_8:
906 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000907 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000908 case Builtin::BI__sync_bool_compare_and_swap_1:
909 case Builtin::BI__sync_bool_compare_and_swap_2:
910 case Builtin::BI__sync_bool_compare_and_swap_4:
911 case Builtin::BI__sync_bool_compare_and_swap_8:
912 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000913 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000914 case Builtin::BI__sync_lock_test_and_set_1:
915 case Builtin::BI__sync_lock_test_and_set_2:
916 case Builtin::BI__sync_lock_test_and_set_4:
917 case Builtin::BI__sync_lock_test_and_set_8:
918 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000919 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000920 case Builtin::BI__sync_lock_release_1:
921 case Builtin::BI__sync_lock_release_2:
922 case Builtin::BI__sync_lock_release_4:
923 case Builtin::BI__sync_lock_release_8:
924 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000925 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000926 case Builtin::BI__sync_swap_1:
927 case Builtin::BI__sync_swap_2:
928 case Builtin::BI__sync_swap_4:
929 case Builtin::BI__sync_swap_8:
930 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000931 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000932 case Builtin::BI__builtin_nontemporal_load:
933 case Builtin::BI__builtin_nontemporal_store:
934 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000935#define BUILTIN(ID, TYPE, ATTRS)
936#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
937 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000938 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000939#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000940 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000941 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000942 return ExprError();
943 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000944 case Builtin::BI__builtin_addressof:
945 if (SemaBuiltinAddressof(*this, TheCall))
946 return ExprError();
947 break;
John McCall03107a42015-10-29 20:48:01 +0000948 case Builtin::BI__builtin_add_overflow:
949 case Builtin::BI__builtin_sub_overflow:
950 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +0000951 if (SemaBuiltinOverflow(*this, TheCall))
952 return ExprError();
953 break;
Richard Smith760520b2014-06-03 23:27:44 +0000954 case Builtin::BI__builtin_operator_new:
955 case Builtin::BI__builtin_operator_delete:
956 if (!getLangOpts().CPlusPlus) {
957 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
958 << (BuiltinID == Builtin::BI__builtin_operator_new
959 ? "__builtin_operator_new"
960 : "__builtin_operator_delete")
961 << "C++";
962 return ExprError();
963 }
964 // CodeGen assumes it can find the global new and delete to call,
965 // so ensure that they are declared.
966 DeclareGlobalNewDelete();
967 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000968
969 // check secure string manipulation functions where overflows
970 // are detectable at compile time
971 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000972 case Builtin::BI__builtin___memmove_chk:
973 case Builtin::BI__builtin___memset_chk:
974 case Builtin::BI__builtin___strlcat_chk:
975 case Builtin::BI__builtin___strlcpy_chk:
976 case Builtin::BI__builtin___strncat_chk:
977 case Builtin::BI__builtin___strncpy_chk:
978 case Builtin::BI__builtin___stpncpy_chk:
979 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
980 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000981 case Builtin::BI__builtin___memccpy_chk:
982 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
983 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000984 case Builtin::BI__builtin___snprintf_chk:
985 case Builtin::BI__builtin___vsnprintf_chk:
986 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
987 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000988 case Builtin::BI__builtin_call_with_static_chain:
989 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
990 return ExprError();
991 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000992 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000993 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +0000994 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
995 diag::err_seh___except_block))
996 return ExprError();
997 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000998 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000999 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001000 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1001 diag::err_seh___except_filter))
1002 return ExprError();
1003 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001004 case Builtin::BI__GetExceptionInfo:
1005 if (checkArgCount(*this, TheCall, 1))
1006 return ExprError();
1007
1008 if (CheckCXXThrowOperand(
1009 TheCall->getLocStart(),
1010 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1011 TheCall))
1012 return ExprError();
1013
1014 TheCall->setType(Context.VoidPtrTy);
1015 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001016 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001017 case Builtin::BIread_pipe:
1018 case Builtin::BIwrite_pipe:
1019 // Since those two functions are declared with var args, we need a semantic
1020 // check for the argument.
1021 if (SemaBuiltinRWPipe(*this, TheCall))
1022 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001023 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001024 break;
1025 case Builtin::BIreserve_read_pipe:
1026 case Builtin::BIreserve_write_pipe:
1027 case Builtin::BIwork_group_reserve_read_pipe:
1028 case Builtin::BIwork_group_reserve_write_pipe:
1029 case Builtin::BIsub_group_reserve_read_pipe:
1030 case Builtin::BIsub_group_reserve_write_pipe:
1031 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1032 return ExprError();
1033 // Since return type of reserve_read/write_pipe built-in function is
1034 // reserve_id_t, which is not defined in the builtin def file , we used int
1035 // as return type and need to override the return type of these functions.
1036 TheCall->setType(Context.OCLReserveIDTy);
1037 break;
1038 case Builtin::BIcommit_read_pipe:
1039 case Builtin::BIcommit_write_pipe:
1040 case Builtin::BIwork_group_commit_read_pipe:
1041 case Builtin::BIwork_group_commit_write_pipe:
1042 case Builtin::BIsub_group_commit_read_pipe:
1043 case Builtin::BIsub_group_commit_write_pipe:
1044 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1045 return ExprError();
1046 break;
1047 case Builtin::BIget_pipe_num_packets:
1048 case Builtin::BIget_pipe_max_packets:
1049 if (SemaBuiltinPipePackets(*this, TheCall))
1050 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001051 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001052 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001053 case Builtin::BIto_global:
1054 case Builtin::BIto_local:
1055 case Builtin::BIto_private:
1056 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1057 return ExprError();
1058 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001059 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1060 case Builtin::BIenqueue_kernel:
1061 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1062 return ExprError();
1063 break;
1064 case Builtin::BIget_kernel_work_group_size:
1065 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1066 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1067 return ExprError();
Nate Begeman4904e322010-06-08 02:47:44 +00001068 }
Richard Smith760520b2014-06-03 23:27:44 +00001069
Nate Begeman4904e322010-06-08 02:47:44 +00001070 // Since the target specific builtins for each arch overlap, only check those
1071 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001072 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001073 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001074 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001075 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001076 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001077 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001078 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1079 return ExprError();
1080 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001081 case llvm::Triple::aarch64:
1082 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001083 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001084 return ExprError();
1085 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001086 case llvm::Triple::mips:
1087 case llvm::Triple::mipsel:
1088 case llvm::Triple::mips64:
1089 case llvm::Triple::mips64el:
1090 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1091 return ExprError();
1092 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001093 case llvm::Triple::systemz:
1094 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1095 return ExprError();
1096 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001097 case llvm::Triple::x86:
1098 case llvm::Triple::x86_64:
1099 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1100 return ExprError();
1101 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001102 case llvm::Triple::ppc:
1103 case llvm::Triple::ppc64:
1104 case llvm::Triple::ppc64le:
1105 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1106 return ExprError();
1107 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001108 default:
1109 break;
1110 }
1111 }
1112
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001113 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001114}
1115
Nate Begeman91e1fea2010-06-14 05:21:25 +00001116// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001117static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001118 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001119 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001120 switch (Type.getEltType()) {
1121 case NeonTypeFlags::Int8:
1122 case NeonTypeFlags::Poly8:
1123 return shift ? 7 : (8 << IsQuad) - 1;
1124 case NeonTypeFlags::Int16:
1125 case NeonTypeFlags::Poly16:
1126 return shift ? 15 : (4 << IsQuad) - 1;
1127 case NeonTypeFlags::Int32:
1128 return shift ? 31 : (2 << IsQuad) - 1;
1129 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001130 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001131 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001132 case NeonTypeFlags::Poly128:
1133 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001134 case NeonTypeFlags::Float16:
1135 assert(!shift && "cannot shift float types!");
1136 return (4 << IsQuad) - 1;
1137 case NeonTypeFlags::Float32:
1138 assert(!shift && "cannot shift float types!");
1139 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001140 case NeonTypeFlags::Float64:
1141 assert(!shift && "cannot shift float types!");
1142 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001143 }
David Blaikie8a40f702012-01-17 06:56:22 +00001144 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001145}
1146
Bob Wilsone4d77232011-11-08 05:04:11 +00001147/// getNeonEltType - Return the QualType corresponding to the elements of
1148/// the vector type specified by the NeonTypeFlags. This is used to check
1149/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001150static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001151 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001152 switch (Flags.getEltType()) {
1153 case NeonTypeFlags::Int8:
1154 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1155 case NeonTypeFlags::Int16:
1156 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1157 case NeonTypeFlags::Int32:
1158 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1159 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001160 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001161 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1162 else
1163 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1164 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001165 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001166 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001167 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001168 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001169 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001170 if (IsInt64Long)
1171 return Context.UnsignedLongTy;
1172 else
1173 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001174 case NeonTypeFlags::Poly128:
1175 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001176 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001177 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001178 case NeonTypeFlags::Float32:
1179 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001180 case NeonTypeFlags::Float64:
1181 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001182 }
David Blaikie8a40f702012-01-17 06:56:22 +00001183 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001184}
1185
Tim Northover12670412014-02-19 10:37:05 +00001186bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001187 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001188 uint64_t mask = 0;
1189 unsigned TV = 0;
1190 int PtrArgNum = -1;
1191 bool HasConstPtr = false;
1192 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001193#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001194#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001195#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001196 }
1197
1198 // For NEON intrinsics which are overloaded on vector element type, validate
1199 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001200 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001201 if (mask) {
1202 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1203 return true;
1204
1205 TV = Result.getLimitedValue(64);
1206 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1207 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001208 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001209 }
1210
1211 if (PtrArgNum >= 0) {
1212 // Check that pointer arguments have the specified type.
1213 Expr *Arg = TheCall->getArg(PtrArgNum);
1214 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1215 Arg = ICE->getSubExpr();
1216 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1217 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001218
Tim Northovera2ee4332014-03-29 15:09:45 +00001219 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +00001220 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +00001221 bool IsInt64Long =
1222 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1223 QualType EltTy =
1224 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001225 if (HasConstPtr)
1226 EltTy = EltTy.withConst();
1227 QualType LHSTy = Context.getPointerType(EltTy);
1228 AssignConvertType ConvTy;
1229 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1230 if (RHS.isInvalid())
1231 return true;
1232 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1233 RHS.get(), AA_Assigning))
1234 return true;
1235 }
1236
1237 // For NEON intrinsics which take an immediate value as part of the
1238 // instruction, range check them here.
1239 unsigned i = 0, l = 0, u = 0;
1240 switch (BuiltinID) {
1241 default:
1242 return false;
Tim Northover12670412014-02-19 10:37:05 +00001243#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001244#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001245#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001246 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001247
Richard Sandiford28940af2014-04-16 08:47:51 +00001248 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001249}
1250
Tim Northovera2ee4332014-03-29 15:09:45 +00001251bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1252 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001253 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001254 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001255 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001256 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001257 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001258 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1259 BuiltinID == AArch64::BI__builtin_arm_strex ||
1260 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001261 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001262 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001263 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1264 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1265 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001266
1267 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1268
1269 // Ensure that we have the proper number of arguments.
1270 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1271 return true;
1272
1273 // Inspect the pointer argument of the atomic builtin. This should always be
1274 // a pointer type, whose element is an integral scalar or pointer type.
1275 // Because it is a pointer type, we don't have to worry about any implicit
1276 // casts here.
1277 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1278 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1279 if (PointerArgRes.isInvalid())
1280 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001281 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001282
1283 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1284 if (!pointerType) {
1285 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1286 << PointerArg->getType() << PointerArg->getSourceRange();
1287 return true;
1288 }
1289
1290 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1291 // task is to insert the appropriate casts into the AST. First work out just
1292 // what the appropriate type is.
1293 QualType ValType = pointerType->getPointeeType();
1294 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1295 if (IsLdrex)
1296 AddrType.addConst();
1297
1298 // Issue a warning if the cast is dodgy.
1299 CastKind CastNeeded = CK_NoOp;
1300 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1301 CastNeeded = CK_BitCast;
1302 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1303 << PointerArg->getType()
1304 << Context.getPointerType(AddrType)
1305 << AA_Passing << PointerArg->getSourceRange();
1306 }
1307
1308 // Finally, do the cast and replace the argument with the corrected version.
1309 AddrType = Context.getPointerType(AddrType);
1310 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1311 if (PointerArgRes.isInvalid())
1312 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001313 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001314
1315 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1316
1317 // In general, we allow ints, floats and pointers to be loaded and stored.
1318 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1319 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1320 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1321 << PointerArg->getType() << PointerArg->getSourceRange();
1322 return true;
1323 }
1324
1325 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001326 if (Context.getTypeSize(ValType) > MaxWidth) {
1327 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001328 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1329 << PointerArg->getType() << PointerArg->getSourceRange();
1330 return true;
1331 }
1332
1333 switch (ValType.getObjCLifetime()) {
1334 case Qualifiers::OCL_None:
1335 case Qualifiers::OCL_ExplicitNone:
1336 // okay
1337 break;
1338
1339 case Qualifiers::OCL_Weak:
1340 case Qualifiers::OCL_Strong:
1341 case Qualifiers::OCL_Autoreleasing:
1342 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1343 << ValType << PointerArg->getSourceRange();
1344 return true;
1345 }
1346
Tim Northover6aacd492013-07-16 09:47:53 +00001347 if (IsLdrex) {
1348 TheCall->setType(ValType);
1349 return false;
1350 }
1351
1352 // Initialize the argument to be stored.
1353 ExprResult ValArg = TheCall->getArg(0);
1354 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1355 Context, ValType, /*consume*/ false);
1356 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1357 if (ValArg.isInvalid())
1358 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001359 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001360
1361 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1362 // but the custom checker bypasses all default analysis.
1363 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001364 return false;
1365}
1366
Nate Begeman4904e322010-06-08 02:47:44 +00001367bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +00001368 llvm::APSInt Result;
1369
Tim Northover6aacd492013-07-16 09:47:53 +00001370 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001371 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1372 BuiltinID == ARM::BI__builtin_arm_strex ||
1373 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001374 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001375 }
1376
Yi Kong26d104a2014-08-13 19:18:14 +00001377 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1378 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1379 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1380 }
1381
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001382 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1383 BuiltinID == ARM::BI__builtin_arm_wsr64)
1384 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1385
1386 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1387 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1388 BuiltinID == ARM::BI__builtin_arm_wsr ||
1389 BuiltinID == ARM::BI__builtin_arm_wsrp)
1390 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1391
Tim Northover12670412014-02-19 10:37:05 +00001392 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1393 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001394
Yi Kong4efadfb2014-07-03 16:01:25 +00001395 // For intrinsics which take an immediate value as part of the instruction,
1396 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001397 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001398 switch (BuiltinID) {
1399 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001400 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1401 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001402 case ARM::BI__builtin_arm_vcvtr_f:
1403 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001404 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001405 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001406 case ARM::BI__builtin_arm_isb:
1407 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001408 }
Nate Begemand773fe62010-06-13 04:47:52 +00001409
Nate Begemanf568b072010-08-03 21:32:34 +00001410 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001411 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001412}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001413
Tim Northover573cbee2014-05-24 12:52:07 +00001414bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001415 CallExpr *TheCall) {
1416 llvm::APSInt Result;
1417
Tim Northover573cbee2014-05-24 12:52:07 +00001418 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001419 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1420 BuiltinID == AArch64::BI__builtin_arm_strex ||
1421 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001422 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1423 }
1424
Yi Konga5548432014-08-13 19:18:20 +00001425 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1426 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1427 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1428 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1429 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1430 }
1431
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001432 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1433 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001434 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001435
1436 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1437 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1438 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1439 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1440 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1441
Tim Northovera2ee4332014-03-29 15:09:45 +00001442 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1443 return true;
1444
Yi Kong19a29ac2014-07-17 10:52:06 +00001445 // For intrinsics which take an immediate value as part of the instruction,
1446 // range check them here.
1447 unsigned i = 0, l = 0, u = 0;
1448 switch (BuiltinID) {
1449 default: return false;
1450 case AArch64::BI__builtin_arm_dmb:
1451 case AArch64::BI__builtin_arm_dsb:
1452 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1453 }
1454
Yi Kong19a29ac2014-07-17 10:52:06 +00001455 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001456}
1457
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001458bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1459 unsigned i = 0, l = 0, u = 0;
1460 switch (BuiltinID) {
1461 default: return false;
1462 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1463 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001464 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1465 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1466 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1467 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1468 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001469 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001470
Richard Sandiford28940af2014-04-16 08:47:51 +00001471 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001472}
1473
Kit Bartone50adcb2015-03-30 19:40:59 +00001474bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1475 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001476 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1477 BuiltinID == PPC::BI__builtin_divdeu ||
1478 BuiltinID == PPC::BI__builtin_bpermd;
1479 bool IsTarget64Bit = Context.getTargetInfo()
1480 .getTypeWidth(Context
1481 .getTargetInfo()
1482 .getIntPtrType()) == 64;
1483 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1484 BuiltinID == PPC::BI__builtin_divweu ||
1485 BuiltinID == PPC::BI__builtin_divde ||
1486 BuiltinID == PPC::BI__builtin_divdeu;
1487
1488 if (Is64BitBltin && !IsTarget64Bit)
1489 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1490 << TheCall->getSourceRange();
1491
1492 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1493 (BuiltinID == PPC::BI__builtin_bpermd &&
1494 !Context.getTargetInfo().hasFeature("bpermd")))
1495 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1496 << TheCall->getSourceRange();
1497
Kit Bartone50adcb2015-03-30 19:40:59 +00001498 switch (BuiltinID) {
1499 default: return false;
1500 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1501 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1502 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1503 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1504 case PPC::BI__builtin_tbegin:
1505 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1506 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1507 case PPC::BI__builtin_tabortwc:
1508 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1509 case PPC::BI__builtin_tabortwci:
1510 case PPC::BI__builtin_tabortdci:
1511 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1512 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1513 }
1514 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1515}
1516
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001517bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1518 CallExpr *TheCall) {
1519 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1520 Expr *Arg = TheCall->getArg(0);
1521 llvm::APSInt AbortCode(32);
1522 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1523 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1524 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1525 << Arg->getSourceRange();
1526 }
1527
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001528 // For intrinsics which take an immediate value as part of the instruction,
1529 // range check them here.
1530 unsigned i = 0, l = 0, u = 0;
1531 switch (BuiltinID) {
1532 default: return false;
1533 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1534 case SystemZ::BI__builtin_s390_verimb:
1535 case SystemZ::BI__builtin_s390_verimh:
1536 case SystemZ::BI__builtin_s390_verimf:
1537 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1538 case SystemZ::BI__builtin_s390_vfaeb:
1539 case SystemZ::BI__builtin_s390_vfaeh:
1540 case SystemZ::BI__builtin_s390_vfaef:
1541 case SystemZ::BI__builtin_s390_vfaebs:
1542 case SystemZ::BI__builtin_s390_vfaehs:
1543 case SystemZ::BI__builtin_s390_vfaefs:
1544 case SystemZ::BI__builtin_s390_vfaezb:
1545 case SystemZ::BI__builtin_s390_vfaezh:
1546 case SystemZ::BI__builtin_s390_vfaezf:
1547 case SystemZ::BI__builtin_s390_vfaezbs:
1548 case SystemZ::BI__builtin_s390_vfaezhs:
1549 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1550 case SystemZ::BI__builtin_s390_vfidb:
1551 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1552 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1553 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1554 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1555 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1556 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1557 case SystemZ::BI__builtin_s390_vstrcb:
1558 case SystemZ::BI__builtin_s390_vstrch:
1559 case SystemZ::BI__builtin_s390_vstrcf:
1560 case SystemZ::BI__builtin_s390_vstrczb:
1561 case SystemZ::BI__builtin_s390_vstrczh:
1562 case SystemZ::BI__builtin_s390_vstrczf:
1563 case SystemZ::BI__builtin_s390_vstrcbs:
1564 case SystemZ::BI__builtin_s390_vstrchs:
1565 case SystemZ::BI__builtin_s390_vstrcfs:
1566 case SystemZ::BI__builtin_s390_vstrczbs:
1567 case SystemZ::BI__builtin_s390_vstrczhs:
1568 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1569 }
1570 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001571}
1572
Craig Topper5ba2c502015-11-07 08:08:31 +00001573/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1574/// This checks that the target supports __builtin_cpu_supports and
1575/// that the string argument is constant and valid.
1576static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1577 Expr *Arg = TheCall->getArg(0);
1578
1579 // Check if the argument is a string literal.
1580 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1581 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1582 << Arg->getSourceRange();
1583
1584 // Check the contents of the string.
1585 StringRef Feature =
1586 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1587 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1588 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1589 << Arg->getSourceRange();
1590 return false;
1591}
1592
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001593bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topper39c87102016-05-18 03:18:12 +00001594 int i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001595 switch (BuiltinID) {
Richard Trieucc3949d2016-02-18 22:34:54 +00001596 default:
1597 return false;
Eric Christopherd9832702015-06-29 21:00:05 +00001598 case X86::BI__builtin_cpu_supports:
Craig Topper5ba2c502015-11-07 08:08:31 +00001599 return SemaBuiltinCpuSupports(*this, TheCall);
Charles Davisc7d5c942015-09-17 20:55:33 +00001600 case X86::BI__builtin_ms_va_start:
1601 return SemaBuiltinMSVAStart(TheCall);
Craig Topperfe22d592016-07-21 07:38:43 +00001602 case X86::BI__builtin_ia32_addcarryx_u64:
1603 case X86::BI__builtin_ia32_addcarry_u64:
1604 case X86::BI__builtin_ia32_subborrow_u64:
1605 case X86::BI__builtin_ia32_readeflags_u64:
1606 case X86::BI__builtin_ia32_writeeflags_u64:
1607 case X86::BI__builtin_ia32_bextr_u64:
1608 case X86::BI__builtin_ia32_bextri_u64:
1609 case X86::BI__builtin_ia32_bzhi_di:
1610 case X86::BI__builtin_ia32_pdep_di:
1611 case X86::BI__builtin_ia32_pext_di:
1612 case X86::BI__builtin_ia32_crc32di:
1613 case X86::BI__builtin_ia32_fxsave64:
1614 case X86::BI__builtin_ia32_fxrstor64:
1615 case X86::BI__builtin_ia32_xsave64:
1616 case X86::BI__builtin_ia32_xrstor64:
1617 case X86::BI__builtin_ia32_xsaveopt64:
1618 case X86::BI__builtin_ia32_xrstors64:
1619 case X86::BI__builtin_ia32_xsavec64:
1620 case X86::BI__builtin_ia32_xsaves64:
1621 case X86::BI__builtin_ia32_rdfsbase64:
1622 case X86::BI__builtin_ia32_rdgsbase64:
1623 case X86::BI__builtin_ia32_wrfsbase64:
1624 case X86::BI__builtin_ia32_wrgsbase64:
Craig Topper351ed422016-07-24 14:58:06 +00001625 case X86::BI__builtin_ia32_pbroadcastq512_gpr_mask:
1626 case X86::BI__builtin_ia32_pbroadcastq256_gpr_mask:
1627 case X86::BI__builtin_ia32_pbroadcastq128_gpr_mask:
Craig Topperfe22d592016-07-21 07:38:43 +00001628 case X86::BI__builtin_ia32_vcvtsd2si64:
1629 case X86::BI__builtin_ia32_vcvtsd2usi64:
1630 case X86::BI__builtin_ia32_vcvtss2si64:
1631 case X86::BI__builtin_ia32_vcvtss2usi64:
1632 case X86::BI__builtin_ia32_vcvttsd2si64:
1633 case X86::BI__builtin_ia32_vcvttsd2usi64:
1634 case X86::BI__builtin_ia32_vcvttss2si64:
1635 case X86::BI__builtin_ia32_vcvttss2usi64:
1636 case X86::BI__builtin_ia32_cvtss2si64:
1637 case X86::BI__builtin_ia32_cvttss2si64:
1638 case X86::BI__builtin_ia32_cvtsd2si64:
1639 case X86::BI__builtin_ia32_cvttsd2si64:
1640 case X86::BI__builtin_ia32_cvtsi2sd64:
1641 case X86::BI__builtin_ia32_cvtsi2ss64:
1642 case X86::BI__builtin_ia32_cvtusi2sd64:
1643 case X86::BI__builtin_ia32_cvtusi2ss64:
1644 case X86::BI__builtin_ia32_rdseed64_step: {
1645 // These builtins only work on x86-64 targets.
1646 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
1647 if (TT.getArch() != llvm::Triple::x86_64)
1648 return Diag(TheCall->getCallee()->getLocStart(),
1649 diag::err_x86_builtin_32_bit_tgt);
1650 return false;
1651 }
Craig Topper39c87102016-05-18 03:18:12 +00001652 case X86::BI__builtin_ia32_extractf64x4_mask:
1653 case X86::BI__builtin_ia32_extracti64x4_mask:
1654 case X86::BI__builtin_ia32_extractf32x8_mask:
1655 case X86::BI__builtin_ia32_extracti32x8_mask:
1656 case X86::BI__builtin_ia32_extractf64x2_256_mask:
1657 case X86::BI__builtin_ia32_extracti64x2_256_mask:
1658 case X86::BI__builtin_ia32_extractf32x4_256_mask:
1659 case X86::BI__builtin_ia32_extracti32x4_256_mask:
1660 i = 1; l = 0; u = 1;
1661 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00001662 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00001663 case X86::BI__builtin_ia32_extractf32x4_mask:
1664 case X86::BI__builtin_ia32_extracti32x4_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001665 case X86::BI__builtin_ia32_extractf64x2_512_mask:
1666 case X86::BI__builtin_ia32_extracti64x2_512_mask:
1667 i = 1; l = 0; u = 3;
1668 break;
1669 case X86::BI__builtin_ia32_insertf32x8_mask:
1670 case X86::BI__builtin_ia32_inserti32x8_mask:
1671 case X86::BI__builtin_ia32_insertf64x4_mask:
1672 case X86::BI__builtin_ia32_inserti64x4_mask:
1673 case X86::BI__builtin_ia32_insertf64x2_256_mask:
1674 case X86::BI__builtin_ia32_inserti64x2_256_mask:
1675 case X86::BI__builtin_ia32_insertf32x4_256_mask:
1676 case X86::BI__builtin_ia32_inserti32x4_256_mask:
1677 i = 2; l = 0; u = 1;
Richard Trieucc3949d2016-02-18 22:34:54 +00001678 break;
1679 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00001680 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
1681 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
1682 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
1683 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001684 case X86::BI__builtin_ia32_insertf64x2_512_mask:
1685 case X86::BI__builtin_ia32_inserti64x2_512_mask:
1686 case X86::BI__builtin_ia32_insertf32x4_mask:
1687 case X86::BI__builtin_ia32_inserti32x4_mask:
1688 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00001689 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00001690 case X86::BI__builtin_ia32_vpermil2pd:
1691 case X86::BI__builtin_ia32_vpermil2pd256:
1692 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00001693 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00001694 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00001695 break;
Craig Topper95b0d732015-01-25 23:30:05 +00001696 case X86::BI__builtin_ia32_cmpb128_mask:
1697 case X86::BI__builtin_ia32_cmpw128_mask:
1698 case X86::BI__builtin_ia32_cmpd128_mask:
1699 case X86::BI__builtin_ia32_cmpq128_mask:
1700 case X86::BI__builtin_ia32_cmpb256_mask:
1701 case X86::BI__builtin_ia32_cmpw256_mask:
1702 case X86::BI__builtin_ia32_cmpd256_mask:
1703 case X86::BI__builtin_ia32_cmpq256_mask:
1704 case X86::BI__builtin_ia32_cmpb512_mask:
1705 case X86::BI__builtin_ia32_cmpw512_mask:
1706 case X86::BI__builtin_ia32_cmpd512_mask:
1707 case X86::BI__builtin_ia32_cmpq512_mask:
1708 case X86::BI__builtin_ia32_ucmpb128_mask:
1709 case X86::BI__builtin_ia32_ucmpw128_mask:
1710 case X86::BI__builtin_ia32_ucmpd128_mask:
1711 case X86::BI__builtin_ia32_ucmpq128_mask:
1712 case X86::BI__builtin_ia32_ucmpb256_mask:
1713 case X86::BI__builtin_ia32_ucmpw256_mask:
1714 case X86::BI__builtin_ia32_ucmpd256_mask:
1715 case X86::BI__builtin_ia32_ucmpq256_mask:
1716 case X86::BI__builtin_ia32_ucmpb512_mask:
1717 case X86::BI__builtin_ia32_ucmpw512_mask:
1718 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00001719 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00001720 case X86::BI__builtin_ia32_vpcomub:
1721 case X86::BI__builtin_ia32_vpcomuw:
1722 case X86::BI__builtin_ia32_vpcomud:
1723 case X86::BI__builtin_ia32_vpcomuq:
1724 case X86::BI__builtin_ia32_vpcomb:
1725 case X86::BI__builtin_ia32_vpcomw:
1726 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00001727 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00001728 i = 2; l = 0; u = 7;
1729 break;
1730 case X86::BI__builtin_ia32_roundps:
1731 case X86::BI__builtin_ia32_roundpd:
1732 case X86::BI__builtin_ia32_roundps256:
1733 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00001734 i = 1; l = 0; u = 15;
1735 break;
1736 case X86::BI__builtin_ia32_roundss:
1737 case X86::BI__builtin_ia32_roundsd:
1738 case X86::BI__builtin_ia32_rangepd128_mask:
1739 case X86::BI__builtin_ia32_rangepd256_mask:
1740 case X86::BI__builtin_ia32_rangepd512_mask:
1741 case X86::BI__builtin_ia32_rangeps128_mask:
1742 case X86::BI__builtin_ia32_rangeps256_mask:
1743 case X86::BI__builtin_ia32_rangeps512_mask:
1744 case X86::BI__builtin_ia32_getmantsd_round_mask:
1745 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001746 i = 2; l = 0; u = 15;
1747 break;
1748 case X86::BI__builtin_ia32_cmpps:
1749 case X86::BI__builtin_ia32_cmpss:
1750 case X86::BI__builtin_ia32_cmppd:
1751 case X86::BI__builtin_ia32_cmpsd:
1752 case X86::BI__builtin_ia32_cmpps256:
1753 case X86::BI__builtin_ia32_cmppd256:
1754 case X86::BI__builtin_ia32_cmpps128_mask:
1755 case X86::BI__builtin_ia32_cmppd128_mask:
1756 case X86::BI__builtin_ia32_cmpps256_mask:
1757 case X86::BI__builtin_ia32_cmppd256_mask:
1758 case X86::BI__builtin_ia32_cmpps512_mask:
1759 case X86::BI__builtin_ia32_cmppd512_mask:
1760 case X86::BI__builtin_ia32_cmpsd_mask:
1761 case X86::BI__builtin_ia32_cmpss_mask:
1762 i = 2; l = 0; u = 31;
1763 break;
1764 case X86::BI__builtin_ia32_xabort:
1765 i = 0; l = -128; u = 255;
1766 break;
1767 case X86::BI__builtin_ia32_pshufw:
1768 case X86::BI__builtin_ia32_aeskeygenassist128:
1769 i = 1; l = -128; u = 255;
1770 break;
1771 case X86::BI__builtin_ia32_vcvtps2ph:
1772 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper39c87102016-05-18 03:18:12 +00001773 case X86::BI__builtin_ia32_rndscaleps_128_mask:
1774 case X86::BI__builtin_ia32_rndscalepd_128_mask:
1775 case X86::BI__builtin_ia32_rndscaleps_256_mask:
1776 case X86::BI__builtin_ia32_rndscalepd_256_mask:
1777 case X86::BI__builtin_ia32_rndscaleps_mask:
1778 case X86::BI__builtin_ia32_rndscalepd_mask:
1779 case X86::BI__builtin_ia32_reducepd128_mask:
1780 case X86::BI__builtin_ia32_reducepd256_mask:
1781 case X86::BI__builtin_ia32_reducepd512_mask:
1782 case X86::BI__builtin_ia32_reduceps128_mask:
1783 case X86::BI__builtin_ia32_reduceps256_mask:
1784 case X86::BI__builtin_ia32_reduceps512_mask:
1785 case X86::BI__builtin_ia32_prold512_mask:
1786 case X86::BI__builtin_ia32_prolq512_mask:
1787 case X86::BI__builtin_ia32_prold128_mask:
1788 case X86::BI__builtin_ia32_prold256_mask:
1789 case X86::BI__builtin_ia32_prolq128_mask:
1790 case X86::BI__builtin_ia32_prolq256_mask:
1791 case X86::BI__builtin_ia32_prord128_mask:
1792 case X86::BI__builtin_ia32_prord256_mask:
1793 case X86::BI__builtin_ia32_prorq128_mask:
1794 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001795 case X86::BI__builtin_ia32_psllwi512_mask:
1796 case X86::BI__builtin_ia32_psllwi128_mask:
1797 case X86::BI__builtin_ia32_psllwi256_mask:
1798 case X86::BI__builtin_ia32_psrldi128_mask:
1799 case X86::BI__builtin_ia32_psrldi256_mask:
1800 case X86::BI__builtin_ia32_psrldi512_mask:
1801 case X86::BI__builtin_ia32_psrlqi128_mask:
1802 case X86::BI__builtin_ia32_psrlqi256_mask:
1803 case X86::BI__builtin_ia32_psrlqi512_mask:
1804 case X86::BI__builtin_ia32_psrawi512_mask:
1805 case X86::BI__builtin_ia32_psrawi128_mask:
1806 case X86::BI__builtin_ia32_psrawi256_mask:
1807 case X86::BI__builtin_ia32_psrlwi512_mask:
1808 case X86::BI__builtin_ia32_psrlwi128_mask:
1809 case X86::BI__builtin_ia32_psrlwi256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001810 case X86::BI__builtin_ia32_psradi128_mask:
1811 case X86::BI__builtin_ia32_psradi256_mask:
1812 case X86::BI__builtin_ia32_psradi512_mask:
1813 case X86::BI__builtin_ia32_psraqi128_mask:
1814 case X86::BI__builtin_ia32_psraqi256_mask:
1815 case X86::BI__builtin_ia32_psraqi512_mask:
1816 case X86::BI__builtin_ia32_pslldi128_mask:
1817 case X86::BI__builtin_ia32_pslldi256_mask:
1818 case X86::BI__builtin_ia32_pslldi512_mask:
1819 case X86::BI__builtin_ia32_psllqi128_mask:
1820 case X86::BI__builtin_ia32_psllqi256_mask:
1821 case X86::BI__builtin_ia32_psllqi512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001822 case X86::BI__builtin_ia32_fpclasspd128_mask:
1823 case X86::BI__builtin_ia32_fpclasspd256_mask:
1824 case X86::BI__builtin_ia32_fpclassps128_mask:
1825 case X86::BI__builtin_ia32_fpclassps256_mask:
1826 case X86::BI__builtin_ia32_fpclassps512_mask:
1827 case X86::BI__builtin_ia32_fpclasspd512_mask:
1828 case X86::BI__builtin_ia32_fpclasssd_mask:
1829 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001830 i = 1; l = 0; u = 255;
1831 break;
1832 case X86::BI__builtin_ia32_palignr:
1833 case X86::BI__builtin_ia32_insertps128:
1834 case X86::BI__builtin_ia32_dpps:
1835 case X86::BI__builtin_ia32_dppd:
1836 case X86::BI__builtin_ia32_dpps256:
1837 case X86::BI__builtin_ia32_mpsadbw128:
1838 case X86::BI__builtin_ia32_mpsadbw256:
1839 case X86::BI__builtin_ia32_pcmpistrm128:
1840 case X86::BI__builtin_ia32_pcmpistri128:
1841 case X86::BI__builtin_ia32_pcmpistria128:
1842 case X86::BI__builtin_ia32_pcmpistric128:
1843 case X86::BI__builtin_ia32_pcmpistrio128:
1844 case X86::BI__builtin_ia32_pcmpistris128:
1845 case X86::BI__builtin_ia32_pcmpistriz128:
1846 case X86::BI__builtin_ia32_pclmulqdq128:
1847 case X86::BI__builtin_ia32_vperm2f128_pd256:
1848 case X86::BI__builtin_ia32_vperm2f128_ps256:
1849 case X86::BI__builtin_ia32_vperm2f128_si256:
1850 case X86::BI__builtin_ia32_permti256:
1851 i = 2; l = -128; u = 255;
1852 break;
1853 case X86::BI__builtin_ia32_palignr128:
1854 case X86::BI__builtin_ia32_palignr256:
1855 case X86::BI__builtin_ia32_palignr128_mask:
1856 case X86::BI__builtin_ia32_palignr256_mask:
1857 case X86::BI__builtin_ia32_palignr512_mask:
1858 case X86::BI__builtin_ia32_alignq512_mask:
1859 case X86::BI__builtin_ia32_alignd512_mask:
1860 case X86::BI__builtin_ia32_alignd128_mask:
1861 case X86::BI__builtin_ia32_alignd256_mask:
1862 case X86::BI__builtin_ia32_alignq128_mask:
1863 case X86::BI__builtin_ia32_alignq256_mask:
1864 case X86::BI__builtin_ia32_vcomisd:
1865 case X86::BI__builtin_ia32_vcomiss:
1866 case X86::BI__builtin_ia32_shuf_f32x4_mask:
1867 case X86::BI__builtin_ia32_shuf_f64x2_mask:
1868 case X86::BI__builtin_ia32_shuf_i32x4_mask:
1869 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001870 case X86::BI__builtin_ia32_dbpsadbw128_mask:
1871 case X86::BI__builtin_ia32_dbpsadbw256_mask:
1872 case X86::BI__builtin_ia32_dbpsadbw512_mask:
1873 i = 2; l = 0; u = 255;
1874 break;
1875 case X86::BI__builtin_ia32_fixupimmpd512_mask:
1876 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1877 case X86::BI__builtin_ia32_fixupimmps512_mask:
1878 case X86::BI__builtin_ia32_fixupimmps512_maskz:
1879 case X86::BI__builtin_ia32_fixupimmsd_mask:
1880 case X86::BI__builtin_ia32_fixupimmsd_maskz:
1881 case X86::BI__builtin_ia32_fixupimmss_mask:
1882 case X86::BI__builtin_ia32_fixupimmss_maskz:
1883 case X86::BI__builtin_ia32_fixupimmpd128_mask:
1884 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
1885 case X86::BI__builtin_ia32_fixupimmpd256_mask:
1886 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
1887 case X86::BI__builtin_ia32_fixupimmps128_mask:
1888 case X86::BI__builtin_ia32_fixupimmps128_maskz:
1889 case X86::BI__builtin_ia32_fixupimmps256_mask:
1890 case X86::BI__builtin_ia32_fixupimmps256_maskz:
1891 case X86::BI__builtin_ia32_pternlogd512_mask:
1892 case X86::BI__builtin_ia32_pternlogd512_maskz:
1893 case X86::BI__builtin_ia32_pternlogq512_mask:
1894 case X86::BI__builtin_ia32_pternlogq512_maskz:
1895 case X86::BI__builtin_ia32_pternlogd128_mask:
1896 case X86::BI__builtin_ia32_pternlogd128_maskz:
1897 case X86::BI__builtin_ia32_pternlogd256_mask:
1898 case X86::BI__builtin_ia32_pternlogd256_maskz:
1899 case X86::BI__builtin_ia32_pternlogq128_mask:
1900 case X86::BI__builtin_ia32_pternlogq128_maskz:
1901 case X86::BI__builtin_ia32_pternlogq256_mask:
1902 case X86::BI__builtin_ia32_pternlogq256_maskz:
1903 i = 3; l = 0; u = 255;
1904 break;
1905 case X86::BI__builtin_ia32_pcmpestrm128:
1906 case X86::BI__builtin_ia32_pcmpestri128:
1907 case X86::BI__builtin_ia32_pcmpestria128:
1908 case X86::BI__builtin_ia32_pcmpestric128:
1909 case X86::BI__builtin_ia32_pcmpestrio128:
1910 case X86::BI__builtin_ia32_pcmpestris128:
1911 case X86::BI__builtin_ia32_pcmpestriz128:
1912 i = 4; l = -128; u = 255;
1913 break;
1914 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1915 case X86::BI__builtin_ia32_rndscaless_round_mask:
1916 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00001917 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001918 }
Craig Topperdd84ec52014-12-27 07:00:08 +00001919 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001920}
1921
Richard Smith55ce3522012-06-25 20:30:08 +00001922/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1923/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1924/// Returns true when the format fits the function and the FormatStringInfo has
1925/// been populated.
1926bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1927 FormatStringInfo *FSI) {
1928 FSI->HasVAListArg = Format->getFirstArg() == 0;
1929 FSI->FormatIdx = Format->getFormatIdx() - 1;
1930 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001931
Richard Smith55ce3522012-06-25 20:30:08 +00001932 // The way the format attribute works in GCC, the implicit this argument
1933 // of member functions is counted. However, it doesn't appear in our own
1934 // lists, so decrement format_idx in that case.
1935 if (IsCXXMember) {
1936 if(FSI->FormatIdx == 0)
1937 return false;
1938 --FSI->FormatIdx;
1939 if (FSI->FirstDataArg != 0)
1940 --FSI->FirstDataArg;
1941 }
1942 return true;
1943}
Mike Stump11289f42009-09-09 15:08:12 +00001944
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001945/// Checks if a the given expression evaluates to null.
1946///
1947/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00001948static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001949 // If the expression has non-null type, it doesn't evaluate to null.
1950 if (auto nullability
1951 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1952 if (*nullability == NullabilityKind::NonNull)
1953 return false;
1954 }
1955
Ted Kremeneka146db32014-01-17 06:24:47 +00001956 // As a special case, transparent unions initialized with zero are
1957 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001958 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001959 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1960 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001961 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001962 if (const InitListExpr *ILE =
1963 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001964 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001965 }
1966
1967 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001968 return (!Expr->isValueDependent() &&
1969 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1970 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001971}
1972
1973static void CheckNonNullArgument(Sema &S,
1974 const Expr *ArgExpr,
1975 SourceLocation CallSiteLoc) {
1976 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00001977 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
1978 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00001979}
1980
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001981bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1982 FormatStringInfo FSI;
1983 if ((GetFormatStringType(Format) == FST_NSString) &&
1984 getFormatStringInfo(Format, false, &FSI)) {
1985 Idx = FSI.FormatIdx;
1986 return true;
1987 }
1988 return false;
1989}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001990/// \brief Diagnose use of %s directive in an NSString which is being passed
1991/// as formatting string to formatting method.
1992static void
1993DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1994 const NamedDecl *FDecl,
1995 Expr **Args,
1996 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001997 unsigned Idx = 0;
1998 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001999 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2000 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002001 Idx = 2;
2002 Format = true;
2003 }
2004 else
2005 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2006 if (S.GetFormatNSStringIdx(I, Idx)) {
2007 Format = true;
2008 break;
2009 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002010 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002011 if (!Format || NumArgs <= Idx)
2012 return;
2013 const Expr *FormatExpr = Args[Idx];
2014 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2015 FormatExpr = CSCE->getSubExpr();
2016 const StringLiteral *FormatString;
2017 if (const ObjCStringLiteral *OSL =
2018 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2019 FormatString = OSL->getString();
2020 else
2021 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2022 if (!FormatString)
2023 return;
2024 if (S.FormatStringHasSArg(FormatString)) {
2025 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2026 << "%s" << 1 << 1;
2027 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2028 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002029 }
2030}
2031
Douglas Gregorb4866e82015-06-19 18:13:19 +00002032/// Determine whether the given type has a non-null nullability annotation.
2033static bool isNonNullType(ASTContext &ctx, QualType type) {
2034 if (auto nullability = type->getNullability(ctx))
2035 return *nullability == NullabilityKind::NonNull;
2036
2037 return false;
2038}
2039
Ted Kremenek2bc73332014-01-17 06:24:43 +00002040static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002041 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002042 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002043 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002044 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002045 assert((FDecl || Proto) && "Need a function declaration or prototype");
2046
Ted Kremenek9aedc152014-01-17 06:24:56 +00002047 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002048 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002049 if (FDecl) {
2050 // Handle the nonnull attribute on the function/method declaration itself.
2051 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2052 if (!NonNull->args_size()) {
2053 // Easy case: all pointer arguments are nonnull.
2054 for (const auto *Arg : Args)
2055 if (S.isValidPointerAttrType(Arg->getType()))
2056 CheckNonNullArgument(S, Arg, CallSiteLoc);
2057 return;
2058 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002059
Douglas Gregorb4866e82015-06-19 18:13:19 +00002060 for (unsigned Val : NonNull->args()) {
2061 if (Val >= Args.size())
2062 continue;
2063 if (NonNullArgs.empty())
2064 NonNullArgs.resize(Args.size());
2065 NonNullArgs.set(Val);
2066 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002067 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002068 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002069
Douglas Gregorb4866e82015-06-19 18:13:19 +00002070 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2071 // Handle the nonnull attribute on the parameters of the
2072 // function/method.
2073 ArrayRef<ParmVarDecl*> parms;
2074 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2075 parms = FD->parameters();
2076 else
2077 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2078
2079 unsigned ParamIndex = 0;
2080 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2081 I != E; ++I, ++ParamIndex) {
2082 const ParmVarDecl *PVD = *I;
2083 if (PVD->hasAttr<NonNullAttr>() ||
2084 isNonNullType(S.Context, PVD->getType())) {
2085 if (NonNullArgs.empty())
2086 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002087
Douglas Gregorb4866e82015-06-19 18:13:19 +00002088 NonNullArgs.set(ParamIndex);
2089 }
2090 }
2091 } else {
2092 // If we have a non-function, non-method declaration but no
2093 // function prototype, try to dig out the function prototype.
2094 if (!Proto) {
2095 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2096 QualType type = VD->getType().getNonReferenceType();
2097 if (auto pointerType = type->getAs<PointerType>())
2098 type = pointerType->getPointeeType();
2099 else if (auto blockType = type->getAs<BlockPointerType>())
2100 type = blockType->getPointeeType();
2101 // FIXME: data member pointers?
2102
2103 // Dig out the function prototype, if there is one.
2104 Proto = type->getAs<FunctionProtoType>();
2105 }
2106 }
2107
2108 // Fill in non-null argument information from the nullability
2109 // information on the parameter types (if we have them).
2110 if (Proto) {
2111 unsigned Index = 0;
2112 for (auto paramType : Proto->getParamTypes()) {
2113 if (isNonNullType(S.Context, paramType)) {
2114 if (NonNullArgs.empty())
2115 NonNullArgs.resize(Args.size());
2116
2117 NonNullArgs.set(Index);
2118 }
2119
2120 ++Index;
2121 }
2122 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002123 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002124
Douglas Gregorb4866e82015-06-19 18:13:19 +00002125 // Check for non-null arguments.
2126 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2127 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002128 if (NonNullArgs[ArgIndex])
2129 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002130 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002131}
2132
Richard Smith55ce3522012-06-25 20:30:08 +00002133/// Handles the checks for format strings, non-POD arguments to vararg
2134/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002135void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2136 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00002137 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00002138 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002139 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002140 if (CurContext->isDependentContext())
2141 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002142
Ted Kremenekb8176da2010-09-09 04:33:05 +00002143 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002144 llvm::SmallBitVector CheckedVarArgs;
2145 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002146 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002147 // Only create vector if there are format attributes.
2148 CheckedVarArgs.resize(Args.size());
2149
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002150 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002151 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002152 }
Richard Smithd7293d72013-08-05 18:49:43 +00002153 }
Richard Smith55ce3522012-06-25 20:30:08 +00002154
2155 // Refuse POD arguments that weren't caught by the format string
2156 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00002157 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002158 unsigned NumParams = Proto ? Proto->getNumParams()
2159 : FDecl && isa<FunctionDecl>(FDecl)
2160 ? cast<FunctionDecl>(FDecl)->getNumParams()
2161 : FDecl && isa<ObjCMethodDecl>(FDecl)
2162 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2163 : 0;
2164
Alp Toker9cacbab2014-01-20 20:26:09 +00002165 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002166 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002167 if (const Expr *Arg = Args[ArgIdx]) {
2168 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2169 checkVariadicArgument(Arg, CallType);
2170 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002171 }
Richard Smithd7293d72013-08-05 18:49:43 +00002172 }
Mike Stump11289f42009-09-09 15:08:12 +00002173
Douglas Gregorb4866e82015-06-19 18:13:19 +00002174 if (FDecl || Proto) {
2175 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002176
Richard Trieu41bc0992013-06-22 00:20:41 +00002177 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002178 if (FDecl) {
2179 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2180 CheckArgumentWithTypeTag(I, Args.data());
2181 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002182 }
Richard Smith55ce3522012-06-25 20:30:08 +00002183}
2184
2185/// CheckConstructorCall - Check a constructor call for correctness and safety
2186/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002187void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2188 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002189 const FunctionProtoType *Proto,
2190 SourceLocation Loc) {
2191 VariadicCallType CallType =
2192 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002193 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
2194 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002195}
2196
2197/// CheckFunctionCall - Check a direct function call for various correctness
2198/// and safety properties not strictly enforced by the C type system.
2199bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2200 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002201 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2202 isa<CXXMethodDecl>(FDecl);
2203 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2204 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002205 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2206 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002207 Expr** Args = TheCall->getArgs();
2208 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00002209 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002210 // If this is a call to a member operator, hide the first argument
2211 // from checkCall.
2212 // FIXME: Our choice of AST representation here is less than ideal.
2213 ++Args;
2214 --NumArgs;
2215 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00002216 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002217 IsMemberFunction, TheCall->getRParenLoc(),
2218 TheCall->getCallee()->getSourceRange(), CallType);
2219
2220 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2221 // None of the checks below are needed for functions that don't have
2222 // simple names (e.g., C++ conversion functions).
2223 if (!FnInfo)
2224 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002225
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002226 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002227 if (getLangOpts().ObjC1)
2228 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002229
Anna Zaks22122702012-01-17 00:37:07 +00002230 unsigned CMId = FDecl->getMemoryFunctionKind();
2231 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002232 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002233
Anna Zaks201d4892012-01-13 21:52:01 +00002234 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002235 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002236 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002237 else if (CMId == Builtin::BIstrncat)
2238 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002239 else
Anna Zaks22122702012-01-17 00:37:07 +00002240 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002241
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002242 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002243}
2244
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002245bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002246 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002247 VariadicCallType CallType =
2248 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002249
Douglas Gregorb4866e82015-06-19 18:13:19 +00002250 checkCall(Method, nullptr, Args,
2251 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2252 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002253
2254 return false;
2255}
2256
Richard Trieu664c4c62013-06-20 21:03:13 +00002257bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2258 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002259 QualType Ty;
2260 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002261 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002262 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002263 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002264 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002265 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002266
Douglas Gregorb4866e82015-06-19 18:13:19 +00002267 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2268 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002269 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002270
Richard Trieu664c4c62013-06-20 21:03:13 +00002271 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002272 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002273 CallType = VariadicDoesNotApply;
2274 } else if (Ty->isBlockPointerType()) {
2275 CallType = VariadicBlock;
2276 } else { // Ty->isFunctionPointerType()
2277 CallType = VariadicFunction;
2278 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002279
Douglas Gregorb4866e82015-06-19 18:13:19 +00002280 checkCall(NDecl, Proto,
2281 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2282 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002283 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002284
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002285 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002286}
2287
Richard Trieu41bc0992013-06-22 00:20:41 +00002288/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2289/// such as function pointers returned from functions.
2290bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002291 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002292 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00002293 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002294 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002295 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002296 TheCall->getCallee()->getSourceRange(), CallType);
2297
2298 return false;
2299}
2300
Tim Northovere94a34c2014-03-11 10:49:14 +00002301static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002302 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002303 return false;
2304
JF Bastiendda2cb12016-04-18 18:01:49 +00002305 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002306 switch (Op) {
2307 case AtomicExpr::AO__c11_atomic_init:
2308 llvm_unreachable("There is no ordering argument for an init");
2309
2310 case AtomicExpr::AO__c11_atomic_load:
2311 case AtomicExpr::AO__atomic_load_n:
2312 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002313 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2314 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002315
2316 case AtomicExpr::AO__c11_atomic_store:
2317 case AtomicExpr::AO__atomic_store:
2318 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002319 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2320 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2321 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002322
2323 default:
2324 return true;
2325 }
2326}
2327
Richard Smithfeea8832012-04-12 05:08:17 +00002328ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2329 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002330 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2331 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002332
Richard Smithfeea8832012-04-12 05:08:17 +00002333 // All these operations take one of the following forms:
2334 enum {
2335 // C __c11_atomic_init(A *, C)
2336 Init,
2337 // C __c11_atomic_load(A *, int)
2338 Load,
2339 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002340 LoadCopy,
2341 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002342 Copy,
2343 // C __c11_atomic_add(A *, M, int)
2344 Arithmetic,
2345 // C __atomic_exchange_n(A *, CP, int)
2346 Xchg,
2347 // void __atomic_exchange(A *, C *, CP, int)
2348 GNUXchg,
2349 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2350 C11CmpXchg,
2351 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2352 GNUCmpXchg
2353 } Form = Init;
Eric Fiselier8d662442016-03-30 23:39:56 +00002354 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2355 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002356 // where:
2357 // C is an appropriate type,
2358 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2359 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2360 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2361 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002362
Gabor Horvath98bd0982015-03-16 09:59:54 +00002363 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2364 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2365 AtomicExpr::AO__atomic_load,
2366 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00002367 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2368 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2369 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2370 Op == AtomicExpr::AO__atomic_store_n ||
2371 Op == AtomicExpr::AO__atomic_exchange_n ||
2372 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2373 bool IsAddSub = false;
2374
2375 switch (Op) {
2376 case AtomicExpr::AO__c11_atomic_init:
2377 Form = Init;
2378 break;
2379
2380 case AtomicExpr::AO__c11_atomic_load:
2381 case AtomicExpr::AO__atomic_load_n:
2382 Form = Load;
2383 break;
2384
Richard Smithfeea8832012-04-12 05:08:17 +00002385 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002386 Form = LoadCopy;
2387 break;
2388
2389 case AtomicExpr::AO__c11_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002390 case AtomicExpr::AO__atomic_store:
2391 case AtomicExpr::AO__atomic_store_n:
2392 Form = Copy;
2393 break;
2394
2395 case AtomicExpr::AO__c11_atomic_fetch_add:
2396 case AtomicExpr::AO__c11_atomic_fetch_sub:
2397 case AtomicExpr::AO__atomic_fetch_add:
2398 case AtomicExpr::AO__atomic_fetch_sub:
2399 case AtomicExpr::AO__atomic_add_fetch:
2400 case AtomicExpr::AO__atomic_sub_fetch:
2401 IsAddSub = true;
2402 // Fall through.
2403 case AtomicExpr::AO__c11_atomic_fetch_and:
2404 case AtomicExpr::AO__c11_atomic_fetch_or:
2405 case AtomicExpr::AO__c11_atomic_fetch_xor:
2406 case AtomicExpr::AO__atomic_fetch_and:
2407 case AtomicExpr::AO__atomic_fetch_or:
2408 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00002409 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00002410 case AtomicExpr::AO__atomic_and_fetch:
2411 case AtomicExpr::AO__atomic_or_fetch:
2412 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00002413 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00002414 Form = Arithmetic;
2415 break;
2416
2417 case AtomicExpr::AO__c11_atomic_exchange:
2418 case AtomicExpr::AO__atomic_exchange_n:
2419 Form = Xchg;
2420 break;
2421
2422 case AtomicExpr::AO__atomic_exchange:
2423 Form = GNUXchg;
2424 break;
2425
2426 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2427 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2428 Form = C11CmpXchg;
2429 break;
2430
2431 case AtomicExpr::AO__atomic_compare_exchange:
2432 case AtomicExpr::AO__atomic_compare_exchange_n:
2433 Form = GNUCmpXchg;
2434 break;
2435 }
2436
2437 // Check we have the right number of arguments.
2438 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002439 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002440 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002441 << TheCall->getCallee()->getSourceRange();
2442 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00002443 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2444 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002445 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002446 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002447 << TheCall->getCallee()->getSourceRange();
2448 return ExprError();
2449 }
2450
Richard Smithfeea8832012-04-12 05:08:17 +00002451 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002452 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00002453 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2454 if (ConvertedPtr.isInvalid())
2455 return ExprError();
2456
2457 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002458 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2459 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00002460 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002461 << Ptr->getType() << Ptr->getSourceRange();
2462 return ExprError();
2463 }
2464
Richard Smithfeea8832012-04-12 05:08:17 +00002465 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2466 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2467 QualType ValType = AtomTy; // 'C'
2468 if (IsC11) {
2469 if (!AtomTy->isAtomicType()) {
2470 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2471 << Ptr->getType() << Ptr->getSourceRange();
2472 return ExprError();
2473 }
Richard Smithe00921a2012-09-15 06:09:58 +00002474 if (AtomTy.isConstQualified()) {
2475 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2476 << Ptr->getType() << Ptr->getSourceRange();
2477 return ExprError();
2478 }
Richard Smithfeea8832012-04-12 05:08:17 +00002479 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00002480 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002481 if (ValType.isConstQualified()) {
2482 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2483 << Ptr->getType() << Ptr->getSourceRange();
2484 return ExprError();
2485 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002486 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002487
Richard Smithfeea8832012-04-12 05:08:17 +00002488 // For an arithmetic operation, the implied arithmetic must be well-formed.
2489 if (Form == Arithmetic) {
2490 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2491 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2492 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2493 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2494 return ExprError();
2495 }
2496 if (!IsAddSub && !ValType->isIntegerType()) {
2497 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2498 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2499 return ExprError();
2500 }
David Majnemere85cff82015-01-28 05:48:06 +00002501 if (IsC11 && ValType->isPointerType() &&
2502 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2503 diag::err_incomplete_type)) {
2504 return ExprError();
2505 }
Richard Smithfeea8832012-04-12 05:08:17 +00002506 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2507 // For __atomic_*_n operations, the value type must be a scalar integral or
2508 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002509 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00002510 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2511 return ExprError();
2512 }
2513
Eli Friedmanaa769812013-09-11 03:49:34 +00002514 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2515 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00002516 // For GNU atomics, require a trivially-copyable type. This is not part of
2517 // the GNU atomics specification, but we enforce it for sanity.
2518 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002519 << Ptr->getType() << Ptr->getSourceRange();
2520 return ExprError();
2521 }
2522
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002523 switch (ValType.getObjCLifetime()) {
2524 case Qualifiers::OCL_None:
2525 case Qualifiers::OCL_ExplicitNone:
2526 // okay
2527 break;
2528
2529 case Qualifiers::OCL_Weak:
2530 case Qualifiers::OCL_Strong:
2531 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002532 // FIXME: Can this happen? By this point, ValType should be known
2533 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002534 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2535 << ValType << Ptr->getSourceRange();
2536 return ExprError();
2537 }
2538
David Majnemerc6eb6502015-06-03 00:26:35 +00002539 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2540 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00002541 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00002542 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00002543 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002544 QualType ResultType = ValType;
Eric Fiselier8d662442016-03-30 23:39:56 +00002545 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002546 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002547 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002548 ResultType = Context.BoolTy;
2549
Richard Smithfeea8832012-04-12 05:08:17 +00002550 // The type of a parameter passed 'by value'. In the GNU atomics, such
2551 // arguments are actually passed as pointers.
2552 QualType ByValType = ValType; // 'CP'
2553 if (!IsC11 && !IsN)
2554 ByValType = Ptr->getType();
2555
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002556 // The first argument --- the pointer --- has a fixed type; we
2557 // deduce the types of the rest of the arguments accordingly. Walk
2558 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002559 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002560 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002561 if (i < NumVals[Form] + 1) {
2562 switch (i) {
2563 case 1:
2564 // The second argument is the non-atomic operand. For arithmetic, this
2565 // is always passed by value, and for a compare_exchange it is always
2566 // passed by address. For the rest, GNU uses by-address and C11 uses
2567 // by-value.
2568 assert(Form != Load);
2569 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2570 Ty = ValType;
2571 else if (Form == Copy || Form == Xchg)
2572 Ty = ByValType;
2573 else if (Form == Arithmetic)
2574 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002575 else {
2576 Expr *ValArg = TheCall->getArg(i);
2577 unsigned AS = 0;
2578 // Keep address space of non-atomic pointer type.
2579 if (const PointerType *PtrTy =
2580 ValArg->getType()->getAs<PointerType>()) {
2581 AS = PtrTy->getPointeeType().getAddressSpace();
2582 }
2583 Ty = Context.getPointerType(
2584 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2585 }
Richard Smithfeea8832012-04-12 05:08:17 +00002586 break;
2587 case 2:
2588 // The third argument to compare_exchange / GNU exchange is a
2589 // (pointer to a) desired value.
2590 Ty = ByValType;
2591 break;
2592 case 3:
2593 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2594 Ty = Context.BoolTy;
2595 break;
2596 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002597 } else {
2598 // The order(s) are always converted to int.
2599 Ty = Context.IntTy;
2600 }
Richard Smithfeea8832012-04-12 05:08:17 +00002601
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002602 InitializedEntity Entity =
2603 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00002604 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002605 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2606 if (Arg.isInvalid())
2607 return true;
2608 TheCall->setArg(i, Arg.get());
2609 }
2610
Richard Smithfeea8832012-04-12 05:08:17 +00002611 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002612 SmallVector<Expr*, 5> SubExprs;
2613 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00002614 switch (Form) {
2615 case Init:
2616 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00002617 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002618 break;
2619 case Load:
2620 SubExprs.push_back(TheCall->getArg(1)); // Order
2621 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00002622 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00002623 case Copy:
2624 case Arithmetic:
2625 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002626 SubExprs.push_back(TheCall->getArg(2)); // Order
2627 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002628 break;
2629 case GNUXchg:
2630 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2631 SubExprs.push_back(TheCall->getArg(3)); // Order
2632 SubExprs.push_back(TheCall->getArg(1)); // Val1
2633 SubExprs.push_back(TheCall->getArg(2)); // Val2
2634 break;
2635 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002636 SubExprs.push_back(TheCall->getArg(3)); // Order
2637 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002638 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00002639 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00002640 break;
2641 case GNUCmpXchg:
2642 SubExprs.push_back(TheCall->getArg(4)); // Order
2643 SubExprs.push_back(TheCall->getArg(1)); // Val1
2644 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2645 SubExprs.push_back(TheCall->getArg(2)); // Val2
2646 SubExprs.push_back(TheCall->getArg(3)); // Weak
2647 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002648 }
Tim Northovere94a34c2014-03-11 10:49:14 +00002649
2650 if (SubExprs.size() >= 2 && Form != Init) {
2651 llvm::APSInt Result(32);
2652 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2653 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00002654 Diag(SubExprs[1]->getLocStart(),
2655 diag::warn_atomic_op_has_invalid_memory_order)
2656 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00002657 }
2658
Fariborz Jahanian615de762013-05-28 17:37:39 +00002659 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2660 SubExprs, ResultType, Op,
2661 TheCall->getRParenLoc());
2662
2663 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2664 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2665 Context.AtomicUsesUnsupportedLibcall(AE))
2666 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2667 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002668
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002669 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002670}
2671
John McCall29ad95b2011-08-27 01:09:30 +00002672/// checkBuiltinArgument - Given a call to a builtin function, perform
2673/// normal type-checking on the given argument, updating the call in
2674/// place. This is useful when a builtin function requires custom
2675/// type-checking for some of its arguments but not necessarily all of
2676/// them.
2677///
2678/// Returns true on error.
2679static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2680 FunctionDecl *Fn = E->getDirectCallee();
2681 assert(Fn && "builtin call without direct callee!");
2682
2683 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2684 InitializedEntity Entity =
2685 InitializedEntity::InitializeParameter(S.Context, Param);
2686
2687 ExprResult Arg = E->getArg(0);
2688 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2689 if (Arg.isInvalid())
2690 return true;
2691
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002692 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00002693 return false;
2694}
2695
Chris Lattnerdc046542009-05-08 06:58:22 +00002696/// SemaBuiltinAtomicOverloaded - We have a call to a function like
2697/// __sync_fetch_and_add, which is an overloaded function based on the pointer
2698/// type of its first argument. The main ActOnCallExpr routines have already
2699/// promoted the types of arguments because all of these calls are prototyped as
2700/// void(...).
2701///
2702/// This function goes through and does final semantic checking for these
2703/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00002704ExprResult
2705Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002706 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00002707 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2708 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2709
2710 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002711 if (TheCall->getNumArgs() < 1) {
2712 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2713 << 0 << 1 << TheCall->getNumArgs()
2714 << TheCall->getCallee()->getSourceRange();
2715 return ExprError();
2716 }
Mike Stump11289f42009-09-09 15:08:12 +00002717
Chris Lattnerdc046542009-05-08 06:58:22 +00002718 // Inspect the first argument of the atomic builtin. This should always be
2719 // a pointer type, whose element is an integral scalar or pointer type.
2720 // Because it is a pointer type, we don't have to worry about any implicit
2721 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002722 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00002723 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00002724 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
2725 if (FirstArgResult.isInvalid())
2726 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002727 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00002728 TheCall->setArg(0, FirstArg);
2729
John McCall31168b02011-06-15 23:02:42 +00002730 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
2731 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002732 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2733 << FirstArg->getType() << FirstArg->getSourceRange();
2734 return ExprError();
2735 }
Mike Stump11289f42009-09-09 15:08:12 +00002736
John McCall31168b02011-06-15 23:02:42 +00002737 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00002738 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002739 !ValType->isBlockPointerType()) {
2740 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
2741 << FirstArg->getType() << FirstArg->getSourceRange();
2742 return ExprError();
2743 }
Chris Lattnerdc046542009-05-08 06:58:22 +00002744
John McCall31168b02011-06-15 23:02:42 +00002745 switch (ValType.getObjCLifetime()) {
2746 case Qualifiers::OCL_None:
2747 case Qualifiers::OCL_ExplicitNone:
2748 // okay
2749 break;
2750
2751 case Qualifiers::OCL_Weak:
2752 case Qualifiers::OCL_Strong:
2753 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002754 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00002755 << ValType << FirstArg->getSourceRange();
2756 return ExprError();
2757 }
2758
John McCallb50451a2011-10-05 07:41:44 +00002759 // Strip any qualifiers off ValType.
2760 ValType = ValType.getUnqualifiedType();
2761
Chandler Carruth3973af72010-07-18 20:54:12 +00002762 // The majority of builtins return a value, but a few have special return
2763 // types, so allow them to override appropriately below.
2764 QualType ResultType = ValType;
2765
Chris Lattnerdc046542009-05-08 06:58:22 +00002766 // We need to figure out which concrete builtin this maps onto. For example,
2767 // __sync_fetch_and_add with a 2 byte object turns into
2768 // __sync_fetch_and_add_2.
2769#define BUILTIN_ROW(x) \
2770 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
2771 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00002772
Chris Lattnerdc046542009-05-08 06:58:22 +00002773 static const unsigned BuiltinIndices[][5] = {
2774 BUILTIN_ROW(__sync_fetch_and_add),
2775 BUILTIN_ROW(__sync_fetch_and_sub),
2776 BUILTIN_ROW(__sync_fetch_and_or),
2777 BUILTIN_ROW(__sync_fetch_and_and),
2778 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00002779 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00002780
Chris Lattnerdc046542009-05-08 06:58:22 +00002781 BUILTIN_ROW(__sync_add_and_fetch),
2782 BUILTIN_ROW(__sync_sub_and_fetch),
2783 BUILTIN_ROW(__sync_and_and_fetch),
2784 BUILTIN_ROW(__sync_or_and_fetch),
2785 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00002786 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00002787
Chris Lattnerdc046542009-05-08 06:58:22 +00002788 BUILTIN_ROW(__sync_val_compare_and_swap),
2789 BUILTIN_ROW(__sync_bool_compare_and_swap),
2790 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00002791 BUILTIN_ROW(__sync_lock_release),
2792 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00002793 };
Mike Stump11289f42009-09-09 15:08:12 +00002794#undef BUILTIN_ROW
2795
Chris Lattnerdc046542009-05-08 06:58:22 +00002796 // Determine the index of the size.
2797 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00002798 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00002799 case 1: SizeIndex = 0; break;
2800 case 2: SizeIndex = 1; break;
2801 case 4: SizeIndex = 2; break;
2802 case 8: SizeIndex = 3; break;
2803 case 16: SizeIndex = 4; break;
2804 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002805 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2806 << FirstArg->getType() << FirstArg->getSourceRange();
2807 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00002808 }
Mike Stump11289f42009-09-09 15:08:12 +00002809
Chris Lattnerdc046542009-05-08 06:58:22 +00002810 // Each of these builtins has one pointer argument, followed by some number of
2811 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2812 // that we ignore. Find out which row of BuiltinIndices to read from as well
2813 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002814 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00002815 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00002816 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00002817 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00002818 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00002819 case Builtin::BI__sync_fetch_and_add:
2820 case Builtin::BI__sync_fetch_and_add_1:
2821 case Builtin::BI__sync_fetch_and_add_2:
2822 case Builtin::BI__sync_fetch_and_add_4:
2823 case Builtin::BI__sync_fetch_and_add_8:
2824 case Builtin::BI__sync_fetch_and_add_16:
2825 BuiltinIndex = 0;
2826 break;
2827
2828 case Builtin::BI__sync_fetch_and_sub:
2829 case Builtin::BI__sync_fetch_and_sub_1:
2830 case Builtin::BI__sync_fetch_and_sub_2:
2831 case Builtin::BI__sync_fetch_and_sub_4:
2832 case Builtin::BI__sync_fetch_and_sub_8:
2833 case Builtin::BI__sync_fetch_and_sub_16:
2834 BuiltinIndex = 1;
2835 break;
2836
2837 case Builtin::BI__sync_fetch_and_or:
2838 case Builtin::BI__sync_fetch_and_or_1:
2839 case Builtin::BI__sync_fetch_and_or_2:
2840 case Builtin::BI__sync_fetch_and_or_4:
2841 case Builtin::BI__sync_fetch_and_or_8:
2842 case Builtin::BI__sync_fetch_and_or_16:
2843 BuiltinIndex = 2;
2844 break;
2845
2846 case Builtin::BI__sync_fetch_and_and:
2847 case Builtin::BI__sync_fetch_and_and_1:
2848 case Builtin::BI__sync_fetch_and_and_2:
2849 case Builtin::BI__sync_fetch_and_and_4:
2850 case Builtin::BI__sync_fetch_and_and_8:
2851 case Builtin::BI__sync_fetch_and_and_16:
2852 BuiltinIndex = 3;
2853 break;
Mike Stump11289f42009-09-09 15:08:12 +00002854
Douglas Gregor73722482011-11-28 16:30:08 +00002855 case Builtin::BI__sync_fetch_and_xor:
2856 case Builtin::BI__sync_fetch_and_xor_1:
2857 case Builtin::BI__sync_fetch_and_xor_2:
2858 case Builtin::BI__sync_fetch_and_xor_4:
2859 case Builtin::BI__sync_fetch_and_xor_8:
2860 case Builtin::BI__sync_fetch_and_xor_16:
2861 BuiltinIndex = 4;
2862 break;
2863
Hal Finkeld2208b52014-10-02 20:53:50 +00002864 case Builtin::BI__sync_fetch_and_nand:
2865 case Builtin::BI__sync_fetch_and_nand_1:
2866 case Builtin::BI__sync_fetch_and_nand_2:
2867 case Builtin::BI__sync_fetch_and_nand_4:
2868 case Builtin::BI__sync_fetch_and_nand_8:
2869 case Builtin::BI__sync_fetch_and_nand_16:
2870 BuiltinIndex = 5;
2871 WarnAboutSemanticsChange = true;
2872 break;
2873
Douglas Gregor73722482011-11-28 16:30:08 +00002874 case Builtin::BI__sync_add_and_fetch:
2875 case Builtin::BI__sync_add_and_fetch_1:
2876 case Builtin::BI__sync_add_and_fetch_2:
2877 case Builtin::BI__sync_add_and_fetch_4:
2878 case Builtin::BI__sync_add_and_fetch_8:
2879 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002880 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00002881 break;
2882
2883 case Builtin::BI__sync_sub_and_fetch:
2884 case Builtin::BI__sync_sub_and_fetch_1:
2885 case Builtin::BI__sync_sub_and_fetch_2:
2886 case Builtin::BI__sync_sub_and_fetch_4:
2887 case Builtin::BI__sync_sub_and_fetch_8:
2888 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002889 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00002890 break;
2891
2892 case Builtin::BI__sync_and_and_fetch:
2893 case Builtin::BI__sync_and_and_fetch_1:
2894 case Builtin::BI__sync_and_and_fetch_2:
2895 case Builtin::BI__sync_and_and_fetch_4:
2896 case Builtin::BI__sync_and_and_fetch_8:
2897 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002898 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00002899 break;
2900
2901 case Builtin::BI__sync_or_and_fetch:
2902 case Builtin::BI__sync_or_and_fetch_1:
2903 case Builtin::BI__sync_or_and_fetch_2:
2904 case Builtin::BI__sync_or_and_fetch_4:
2905 case Builtin::BI__sync_or_and_fetch_8:
2906 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002907 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00002908 break;
2909
2910 case Builtin::BI__sync_xor_and_fetch:
2911 case Builtin::BI__sync_xor_and_fetch_1:
2912 case Builtin::BI__sync_xor_and_fetch_2:
2913 case Builtin::BI__sync_xor_and_fetch_4:
2914 case Builtin::BI__sync_xor_and_fetch_8:
2915 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002916 BuiltinIndex = 10;
2917 break;
2918
2919 case Builtin::BI__sync_nand_and_fetch:
2920 case Builtin::BI__sync_nand_and_fetch_1:
2921 case Builtin::BI__sync_nand_and_fetch_2:
2922 case Builtin::BI__sync_nand_and_fetch_4:
2923 case Builtin::BI__sync_nand_and_fetch_8:
2924 case Builtin::BI__sync_nand_and_fetch_16:
2925 BuiltinIndex = 11;
2926 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00002927 break;
Mike Stump11289f42009-09-09 15:08:12 +00002928
Chris Lattnerdc046542009-05-08 06:58:22 +00002929 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002930 case Builtin::BI__sync_val_compare_and_swap_1:
2931 case Builtin::BI__sync_val_compare_and_swap_2:
2932 case Builtin::BI__sync_val_compare_and_swap_4:
2933 case Builtin::BI__sync_val_compare_and_swap_8:
2934 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002935 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00002936 NumFixed = 2;
2937 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002938
Chris Lattnerdc046542009-05-08 06:58:22 +00002939 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002940 case Builtin::BI__sync_bool_compare_and_swap_1:
2941 case Builtin::BI__sync_bool_compare_and_swap_2:
2942 case Builtin::BI__sync_bool_compare_and_swap_4:
2943 case Builtin::BI__sync_bool_compare_and_swap_8:
2944 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002945 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00002946 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00002947 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002948 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002949
2950 case Builtin::BI__sync_lock_test_and_set:
2951 case Builtin::BI__sync_lock_test_and_set_1:
2952 case Builtin::BI__sync_lock_test_and_set_2:
2953 case Builtin::BI__sync_lock_test_and_set_4:
2954 case Builtin::BI__sync_lock_test_and_set_8:
2955 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002956 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002957 break;
2958
Chris Lattnerdc046542009-05-08 06:58:22 +00002959 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002960 case Builtin::BI__sync_lock_release_1:
2961 case Builtin::BI__sync_lock_release_2:
2962 case Builtin::BI__sync_lock_release_4:
2963 case Builtin::BI__sync_lock_release_8:
2964 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002965 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002966 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002967 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002968 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002969
2970 case Builtin::BI__sync_swap:
2971 case Builtin::BI__sync_swap_1:
2972 case Builtin::BI__sync_swap_2:
2973 case Builtin::BI__sync_swap_4:
2974 case Builtin::BI__sync_swap_8:
2975 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002976 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002977 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002978 }
Mike Stump11289f42009-09-09 15:08:12 +00002979
Chris Lattnerdc046542009-05-08 06:58:22 +00002980 // Now that we know how many fixed arguments we expect, first check that we
2981 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002982 if (TheCall->getNumArgs() < 1+NumFixed) {
2983 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2984 << 0 << 1+NumFixed << TheCall->getNumArgs()
2985 << TheCall->getCallee()->getSourceRange();
2986 return ExprError();
2987 }
Mike Stump11289f42009-09-09 15:08:12 +00002988
Hal Finkeld2208b52014-10-02 20:53:50 +00002989 if (WarnAboutSemanticsChange) {
2990 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2991 << TheCall->getCallee()->getSourceRange();
2992 }
2993
Chris Lattner5b9241b2009-05-08 15:36:58 +00002994 // Get the decl for the concrete builtin from this, we can tell what the
2995 // concrete integer type we should convert to is.
2996 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Eric Christopher02d5d862015-08-06 01:01:12 +00002997 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002998 FunctionDecl *NewBuiltinDecl;
2999 if (NewBuiltinID == BuiltinID)
3000 NewBuiltinDecl = FDecl;
3001 else {
3002 // Perform builtin lookup to avoid redeclaring it.
3003 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3004 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3005 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3006 assert(Res.getFoundDecl());
3007 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003008 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003009 return ExprError();
3010 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003011
John McCallcf142162010-08-07 06:22:56 +00003012 // The first argument --- the pointer --- has a fixed type; we
3013 // deduce the types of the rest of the arguments accordingly. Walk
3014 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003015 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003016 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003017
Chris Lattnerdc046542009-05-08 06:58:22 +00003018 // GCC does an implicit conversion to the pointer or integer ValType. This
3019 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003020 // Initialize the argument.
3021 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3022 ValType, /*consume*/ false);
3023 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003024 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003025 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003026
Chris Lattnerdc046542009-05-08 06:58:22 +00003027 // Okay, we have something that *can* be converted to the right type. Check
3028 // to see if there is a potentially weird extension going on here. This can
3029 // happen when you do an atomic operation on something like an char* and
3030 // pass in 42. The 42 gets converted to char. This is even more strange
3031 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003032 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003033 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003034 }
Mike Stump11289f42009-09-09 15:08:12 +00003035
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003036 ASTContext& Context = this->getASTContext();
3037
3038 // Create a new DeclRefExpr to refer to the new decl.
3039 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3040 Context,
3041 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003042 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003043 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003044 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003045 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003046 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003047 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003048
Chris Lattnerdc046542009-05-08 06:58:22 +00003049 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003050 // FIXME: This loses syntactic information.
3051 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3052 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3053 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003054 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003055
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003056 // Change the result type of the call to match the original value type. This
3057 // is arbitrary, but the codegen for these builtins ins design to handle it
3058 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003059 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003060
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003061 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003062}
3063
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003064/// SemaBuiltinNontemporalOverloaded - We have a call to
3065/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3066/// overloaded function based on the pointer type of its last argument.
3067///
3068/// This function goes through and does final semantic checking for these
3069/// builtins.
3070ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3071 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3072 DeclRefExpr *DRE =
3073 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3074 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3075 unsigned BuiltinID = FDecl->getBuiltinID();
3076 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3077 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3078 "Unexpected nontemporal load/store builtin!");
3079 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3080 unsigned numArgs = isStore ? 2 : 1;
3081
3082 // Ensure that we have the proper number of arguments.
3083 if (checkArgCount(*this, TheCall, numArgs))
3084 return ExprError();
3085
3086 // Inspect the last argument of the nontemporal builtin. This should always
3087 // be a pointer type, from which we imply the type of the memory access.
3088 // Because it is a pointer type, we don't have to worry about any implicit
3089 // casts here.
3090 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3091 ExprResult PointerArgResult =
3092 DefaultFunctionArrayLvalueConversion(PointerArg);
3093
3094 if (PointerArgResult.isInvalid())
3095 return ExprError();
3096 PointerArg = PointerArgResult.get();
3097 TheCall->setArg(numArgs - 1, PointerArg);
3098
3099 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3100 if (!pointerType) {
3101 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3102 << PointerArg->getType() << PointerArg->getSourceRange();
3103 return ExprError();
3104 }
3105
3106 QualType ValType = pointerType->getPointeeType();
3107
3108 // Strip any qualifiers off ValType.
3109 ValType = ValType.getUnqualifiedType();
3110 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3111 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3112 !ValType->isVectorType()) {
3113 Diag(DRE->getLocStart(),
3114 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3115 << PointerArg->getType() << PointerArg->getSourceRange();
3116 return ExprError();
3117 }
3118
3119 if (!isStore) {
3120 TheCall->setType(ValType);
3121 return TheCallResult;
3122 }
3123
3124 ExprResult ValArg = TheCall->getArg(0);
3125 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3126 Context, ValType, /*consume*/ false);
3127 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3128 if (ValArg.isInvalid())
3129 return ExprError();
3130
3131 TheCall->setArg(0, ValArg.get());
3132 TheCall->setType(Context.VoidTy);
3133 return TheCallResult;
3134}
3135
Chris Lattner6436fb62009-02-18 06:01:06 +00003136/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003137/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003138/// Note: It might also make sense to do the UTF-16 conversion here (would
3139/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003140bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003141 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003142 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3143
Douglas Gregorfb65e592011-07-27 05:40:30 +00003144 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003145 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3146 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003147 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003148 }
Mike Stump11289f42009-09-09 15:08:12 +00003149
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003150 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003151 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003152 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003153 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00003154 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003155 UTF16 *ToPtr = &ToBuf[0];
3156
3157 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
3158 &ToPtr, ToPtr + NumBytes,
3159 strictConversion);
3160 // Check for conversion failure.
3161 if (Result != conversionOK)
3162 Diag(Arg->getLocStart(),
3163 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3164 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003165 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003166}
3167
Charles Davisc7d5c942015-09-17 20:55:33 +00003168/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3169/// for validity. Emit an error and return true on failure; return false
3170/// on success.
3171bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003172 Expr *Fn = TheCall->getCallee();
3173 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003174 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003175 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003176 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3177 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003178 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003179 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003180 return true;
3181 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003182
3183 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003184 return Diag(TheCall->getLocEnd(),
3185 diag::err_typecheck_call_too_few_args_at_least)
3186 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003187 }
3188
John McCall29ad95b2011-08-27 01:09:30 +00003189 // Type-check the first argument normally.
3190 if (checkBuiltinArgument(*this, TheCall, 0))
3191 return true;
3192
Chris Lattnere202e6a2007-12-20 00:05:45 +00003193 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00003194 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00003195 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00003196 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00003197 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00003198 else if (FunctionDecl *FD = getCurFunctionDecl())
3199 isVariadic = FD->isVariadic();
3200 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00003201 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00003202
Chris Lattnere202e6a2007-12-20 00:05:45 +00003203 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003204 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3205 return true;
3206 }
Mike Stump11289f42009-09-09 15:08:12 +00003207
Chris Lattner43be2e62007-12-19 23:59:04 +00003208 // Verify that the second argument to the builtin is the last argument of the
3209 // current function or method.
3210 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003211 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003212
Nico Weber9eea7642013-05-24 23:31:57 +00003213 // These are valid if SecondArgIsLastNamedArgument is false after the next
3214 // block.
3215 QualType Type;
3216 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003217 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003218
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003219 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3220 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003221 // FIXME: This isn't correct for methods (results in bogus warning).
3222 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003223 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00003224 if (CurBlock)
David Majnemera3debed2016-06-24 05:33:44 +00003225 LastArg = CurBlock->TheDecl->parameters().back();
Steve Naroff439a3e42009-04-15 19:33:47 +00003226 else if (FunctionDecl *FD = getCurFunctionDecl())
David Majnemera3debed2016-06-24 05:33:44 +00003227 LastArg = FD->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003228 else
David Majnemera3debed2016-06-24 05:33:44 +00003229 LastArg = getCurMethodDecl()->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003230 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00003231
3232 Type = PV->getType();
3233 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003234 IsCRegister =
3235 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003236 }
3237 }
Mike Stump11289f42009-09-09 15:08:12 +00003238
Chris Lattner43be2e62007-12-19 23:59:04 +00003239 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003240 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003241 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003242 else if (IsCRegister || Type->isReferenceType() ||
3243 Type->isPromotableIntegerType() ||
3244 Type->isSpecificBuiltinType(BuiltinType::Float)) {
3245 unsigned Reason = 0;
3246 if (Type->isReferenceType()) Reason = 1;
3247 else if (IsCRegister) Reason = 2;
3248 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003249 Diag(ParamLoc, diag::note_parameter_type) << Type;
3250 }
3251
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003252 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003253 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003254}
Chris Lattner43be2e62007-12-19 23:59:04 +00003255
Charles Davisc7d5c942015-09-17 20:55:33 +00003256/// Check the arguments to '__builtin_va_start' for validity, and that
3257/// it was called from a function of the native ABI.
3258/// Emit an error and return true on failure; return false on success.
3259bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3260 // On x86-64 Unix, don't allow this in Win64 ABI functions.
3261 // On x64 Windows, don't allow this in System V ABI functions.
3262 // (Yes, that means there's no corresponding way to support variadic
3263 // System V ABI functions on Windows.)
3264 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3265 unsigned OS = Context.getTargetInfo().getTriple().getOS();
3266 clang::CallingConv CC = CC_C;
3267 if (const FunctionDecl *FD = getCurFunctionDecl())
3268 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3269 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3270 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3271 return Diag(TheCall->getCallee()->getLocStart(),
3272 diag::err_va_start_used_in_wrong_abi_function)
3273 << (OS != llvm::Triple::Win32);
3274 }
3275 return SemaBuiltinVAStartImpl(TheCall);
3276}
3277
3278/// Check the arguments to '__builtin_ms_va_start' for validity, and that
3279/// it was called from a Win64 ABI function.
3280/// Emit an error and return true on failure; return false on success.
3281bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3282 // This only makes sense for x86-64.
3283 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3284 Expr *Callee = TheCall->getCallee();
3285 if (TT.getArch() != llvm::Triple::x86_64)
3286 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3287 // Don't allow this in System V ABI functions.
3288 clang::CallingConv CC = CC_C;
3289 if (const FunctionDecl *FD = getCurFunctionDecl())
3290 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3291 if (CC == CC_X86_64SysV ||
3292 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3293 return Diag(Callee->getLocStart(),
3294 diag::err_ms_va_start_used_in_sysv_function);
3295 return SemaBuiltinVAStartImpl(TheCall);
3296}
3297
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003298bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3299 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3300 // const char *named_addr);
3301
3302 Expr *Func = Call->getCallee();
3303
3304 if (Call->getNumArgs() < 3)
3305 return Diag(Call->getLocEnd(),
3306 diag::err_typecheck_call_too_few_args_at_least)
3307 << 0 /*function call*/ << 3 << Call->getNumArgs();
3308
3309 // Determine whether the current function is variadic or not.
3310 bool IsVariadic;
3311 if (BlockScopeInfo *CurBlock = getCurBlock())
3312 IsVariadic = CurBlock->TheDecl->isVariadic();
3313 else if (FunctionDecl *FD = getCurFunctionDecl())
3314 IsVariadic = FD->isVariadic();
3315 else if (ObjCMethodDecl *MD = getCurMethodDecl())
3316 IsVariadic = MD->isVariadic();
3317 else
3318 llvm_unreachable("unexpected statement type");
3319
3320 if (!IsVariadic) {
3321 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3322 return true;
3323 }
3324
3325 // Type-check the first argument normally.
3326 if (checkBuiltinArgument(*this, Call, 0))
3327 return true;
3328
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003329 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003330 unsigned ArgNo;
3331 QualType Type;
3332 } ArgumentTypes[] = {
3333 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3334 { 2, Context.getSizeType() },
3335 };
3336
3337 for (const auto &AT : ArgumentTypes) {
3338 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3339 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3340 continue;
3341 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3342 << Arg->getType() << AT.Type << 1 /* different class */
3343 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3344 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3345 }
3346
3347 return false;
3348}
3349
Chris Lattner2da14fb2007-12-20 00:26:33 +00003350/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3351/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003352bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3353 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003354 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003355 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003356 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003357 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003358 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003359 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003360 << SourceRange(TheCall->getArg(2)->getLocStart(),
3361 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003362
John Wiegley01296292011-04-08 18:41:53 +00003363 ExprResult OrigArg0 = TheCall->getArg(0);
3364 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003365
Chris Lattner2da14fb2007-12-20 00:26:33 +00003366 // Do standard promotions between the two arguments, returning their common
3367 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003368 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003369 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3370 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003371
3372 // Make sure any conversions are pushed back into the call; this is
3373 // type safe since unordered compare builtins are declared as "_Bool
3374 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003375 TheCall->setArg(0, OrigArg0.get());
3376 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003377
John Wiegley01296292011-04-08 18:41:53 +00003378 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003379 return false;
3380
Chris Lattner2da14fb2007-12-20 00:26:33 +00003381 // If the common type isn't a real floating type, then the arguments were
3382 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003383 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00003384 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003385 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00003386 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3387 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003388
Chris Lattner2da14fb2007-12-20 00:26:33 +00003389 return false;
3390}
3391
Benjamin Kramer634fc102010-02-15 22:42:31 +00003392/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3393/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00003394/// to check everything. We expect the last argument to be a floating point
3395/// value.
3396bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3397 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00003398 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003399 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00003400 if (TheCall->getNumArgs() > NumArgs)
3401 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003402 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003403 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00003404 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003405 (*(TheCall->arg_end()-1))->getLocEnd());
3406
Benjamin Kramer64aae502010-02-16 10:07:31 +00003407 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00003408
Eli Friedman7e4faac2009-08-31 20:06:00 +00003409 if (OrigArg->isTypeDependent())
3410 return false;
3411
Chris Lattner68784ef2010-05-06 05:50:07 +00003412 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00003413 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00003414 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003415 diag::err_typecheck_call_invalid_unary_fp)
3416 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003417
Chris Lattner68784ef2010-05-06 05:50:07 +00003418 // If this is an implicit conversion from float -> double, remove it.
3419 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3420 Expr *CastArg = Cast->getSubExpr();
3421 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3422 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
3423 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00003424 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00003425 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00003426 }
3427 }
3428
Eli Friedman7e4faac2009-08-31 20:06:00 +00003429 return false;
3430}
3431
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003432/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3433// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00003434ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00003435 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003436 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00003437 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00003438 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3439 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003440
Nate Begemana0110022010-06-08 00:16:34 +00003441 // Determine which of the following types of shufflevector we're checking:
3442 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00003443 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00003444 QualType resType = TheCall->getArg(0)->getType();
3445 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00003446
Douglas Gregorc25f7662009-05-19 22:10:17 +00003447 if (!TheCall->getArg(0)->isTypeDependent() &&
3448 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00003449 QualType LHSType = TheCall->getArg(0)->getType();
3450 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00003451
Craig Topperbaca3892013-07-29 06:47:04 +00003452 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3453 return ExprError(Diag(TheCall->getLocStart(),
3454 diag::err_shufflevector_non_vector)
3455 << SourceRange(TheCall->getArg(0)->getLocStart(),
3456 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003457
Nate Begemana0110022010-06-08 00:16:34 +00003458 numElements = LHSType->getAs<VectorType>()->getNumElements();
3459 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00003460
Nate Begemana0110022010-06-08 00:16:34 +00003461 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3462 // with mask. If so, verify that RHS is an integer vector type with the
3463 // same number of elts as lhs.
3464 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00003465 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00003466 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00003467 return ExprError(Diag(TheCall->getLocStart(),
3468 diag::err_shufflevector_incompatible_vector)
3469 << SourceRange(TheCall->getArg(1)->getLocStart(),
3470 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003471 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00003472 return ExprError(Diag(TheCall->getLocStart(),
3473 diag::err_shufflevector_incompatible_vector)
3474 << SourceRange(TheCall->getArg(0)->getLocStart(),
3475 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00003476 } else if (numElements != numResElements) {
3477 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00003478 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003479 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003480 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003481 }
3482
3483 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00003484 if (TheCall->getArg(i)->isTypeDependent() ||
3485 TheCall->getArg(i)->isValueDependent())
3486 continue;
3487
Nate Begemana0110022010-06-08 00:16:34 +00003488 llvm::APSInt Result(32);
3489 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3490 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003491 diag::err_shufflevector_nonconstant_argument)
3492 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003493
Craig Topper50ad5b72013-08-03 17:40:38 +00003494 // Allow -1 which will be translated to undef in the IR.
3495 if (Result.isSigned() && Result.isAllOnesValue())
3496 continue;
3497
Chris Lattner7ab824e2008-08-10 02:05:13 +00003498 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003499 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003500 diag::err_shufflevector_argument_too_large)
3501 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003502 }
3503
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003504 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003505
Chris Lattner7ab824e2008-08-10 02:05:13 +00003506 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003507 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00003508 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003509 }
3510
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003511 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3512 TheCall->getCallee()->getLocStart(),
3513 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003514}
Chris Lattner43be2e62007-12-19 23:59:04 +00003515
Hal Finkelc4d7c822013-09-18 03:29:45 +00003516/// SemaConvertVectorExpr - Handle __builtin_convertvector
3517ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3518 SourceLocation BuiltinLoc,
3519 SourceLocation RParenLoc) {
3520 ExprValueKind VK = VK_RValue;
3521 ExprObjectKind OK = OK_Ordinary;
3522 QualType DstTy = TInfo->getType();
3523 QualType SrcTy = E->getType();
3524
3525 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3526 return ExprError(Diag(BuiltinLoc,
3527 diag::err_convertvector_non_vector)
3528 << E->getSourceRange());
3529 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3530 return ExprError(Diag(BuiltinLoc,
3531 diag::err_convertvector_non_vector_type));
3532
3533 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3534 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3535 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3536 if (SrcElts != DstElts)
3537 return ExprError(Diag(BuiltinLoc,
3538 diag::err_convertvector_incompatible_vector)
3539 << E->getSourceRange());
3540 }
3541
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003542 return new (Context)
3543 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003544}
3545
Daniel Dunbarb7257262008-07-21 22:59:13 +00003546/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3547// This is declared to take (const void*, ...) and can take two
3548// optional constant int args.
3549bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003550 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003551
Chris Lattner3b054132008-11-19 05:08:23 +00003552 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003553 return Diag(TheCall->getLocEnd(),
3554 diag::err_typecheck_call_too_many_args_at_most)
3555 << 0 /*function call*/ << 3 << NumArgs
3556 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003557
3558 // Argument 0 is checked for us and the remaining arguments must be
3559 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003560 for (unsigned i = 1; i != NumArgs; ++i)
3561 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003562 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003563
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003564 return false;
3565}
3566
Hal Finkelf0417332014-07-17 14:25:55 +00003567/// SemaBuiltinAssume - Handle __assume (MS Extension).
3568// __assume does not evaluate its arguments, and should warn if its argument
3569// has side effects.
3570bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3571 Expr *Arg = TheCall->getArg(0);
3572 if (Arg->isInstantiationDependent()) return false;
3573
3574 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003575 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003576 << Arg->getSourceRange()
3577 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3578
3579 return false;
3580}
3581
3582/// Handle __builtin_assume_aligned. This is declared
3583/// as (const void*, size_t, ...) and can take one optional constant int arg.
3584bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3585 unsigned NumArgs = TheCall->getNumArgs();
3586
3587 if (NumArgs > 3)
3588 return Diag(TheCall->getLocEnd(),
3589 diag::err_typecheck_call_too_many_args_at_most)
3590 << 0 /*function call*/ << 3 << NumArgs
3591 << TheCall->getSourceRange();
3592
3593 // The alignment must be a constant integer.
3594 Expr *Arg = TheCall->getArg(1);
3595
3596 // We can't check the value of a dependent argument.
3597 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3598 llvm::APSInt Result;
3599 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3600 return true;
3601
3602 if (!Result.isPowerOf2())
3603 return Diag(TheCall->getLocStart(),
3604 diag::err_alignment_not_power_of_two)
3605 << Arg->getSourceRange();
3606 }
3607
3608 if (NumArgs > 2) {
3609 ExprResult Arg(TheCall->getArg(2));
3610 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3611 Context.getSizeType(), false);
3612 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3613 if (Arg.isInvalid()) return true;
3614 TheCall->setArg(2, Arg.get());
3615 }
Hal Finkelf0417332014-07-17 14:25:55 +00003616
3617 return false;
3618}
3619
Eric Christopher8d0c6212010-04-17 02:26:23 +00003620/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3621/// TheCall is a constant expression.
3622bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3623 llvm::APSInt &Result) {
3624 Expr *Arg = TheCall->getArg(ArgNum);
3625 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3626 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3627
3628 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3629
3630 if (!Arg->isIntegerConstantExpr(Result, Context))
3631 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00003632 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00003633
Chris Lattnerd545ad12009-09-23 06:06:36 +00003634 return false;
3635}
3636
Richard Sandiford28940af2014-04-16 08:47:51 +00003637/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3638/// TheCall is a constant expression in the range [Low, High].
3639bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3640 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00003641 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003642
3643 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00003644 Expr *Arg = TheCall->getArg(ArgNum);
3645 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003646 return false;
3647
Eric Christopher8d0c6212010-04-17 02:26:23 +00003648 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00003649 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003650 return true;
3651
Richard Sandiford28940af2014-04-16 08:47:51 +00003652 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00003653 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00003654 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00003655
3656 return false;
3657}
3658
Luke Cheeseman59b2d832015-06-15 17:51:01 +00003659/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
3660/// TheCall is an ARM/AArch64 special register string literal.
3661bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
3662 int ArgNum, unsigned ExpectedFieldNum,
3663 bool AllowName) {
3664 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3665 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
3666 BuiltinID == ARM::BI__builtin_arm_rsr ||
3667 BuiltinID == ARM::BI__builtin_arm_rsrp ||
3668 BuiltinID == ARM::BI__builtin_arm_wsr ||
3669 BuiltinID == ARM::BI__builtin_arm_wsrp;
3670 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3671 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3672 BuiltinID == AArch64::BI__builtin_arm_rsr ||
3673 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3674 BuiltinID == AArch64::BI__builtin_arm_wsr ||
3675 BuiltinID == AArch64::BI__builtin_arm_wsrp;
3676 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
3677
3678 // We can't check the value of a dependent argument.
3679 Expr *Arg = TheCall->getArg(ArgNum);
3680 if (Arg->isTypeDependent() || Arg->isValueDependent())
3681 return false;
3682
3683 // Check if the argument is a string literal.
3684 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3685 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3686 << Arg->getSourceRange();
3687
3688 // Check the type of special register given.
3689 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3690 SmallVector<StringRef, 6> Fields;
3691 Reg.split(Fields, ":");
3692
3693 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
3694 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3695 << Arg->getSourceRange();
3696
3697 // If the string is the name of a register then we cannot check that it is
3698 // valid here but if the string is of one the forms described in ACLE then we
3699 // can check that the supplied fields are integers and within the valid
3700 // ranges.
3701 if (Fields.size() > 1) {
3702 bool FiveFields = Fields.size() == 5;
3703
3704 bool ValidString = true;
3705 if (IsARMBuiltin) {
3706 ValidString &= Fields[0].startswith_lower("cp") ||
3707 Fields[0].startswith_lower("p");
3708 if (ValidString)
3709 Fields[0] =
3710 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
3711
3712 ValidString &= Fields[2].startswith_lower("c");
3713 if (ValidString)
3714 Fields[2] = Fields[2].drop_front(1);
3715
3716 if (FiveFields) {
3717 ValidString &= Fields[3].startswith_lower("c");
3718 if (ValidString)
3719 Fields[3] = Fields[3].drop_front(1);
3720 }
3721 }
3722
3723 SmallVector<int, 5> Ranges;
3724 if (FiveFields)
3725 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
3726 else
3727 Ranges.append({15, 7, 15});
3728
3729 for (unsigned i=0; i<Fields.size(); ++i) {
3730 int IntField;
3731 ValidString &= !Fields[i].getAsInteger(10, IntField);
3732 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
3733 }
3734
3735 if (!ValidString)
3736 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3737 << Arg->getSourceRange();
3738
3739 } else if (IsAArch64Builtin && Fields.size() == 1) {
3740 // If the register name is one of those that appear in the condition below
3741 // and the special register builtin being used is one of the write builtins,
3742 // then we require that the argument provided for writing to the register
3743 // is an integer constant expression. This is because it will be lowered to
3744 // an MSR (immediate) instruction, so we need to know the immediate at
3745 // compile time.
3746 if (TheCall->getNumArgs() != 2)
3747 return false;
3748
3749 std::string RegLower = Reg.lower();
3750 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
3751 RegLower != "pan" && RegLower != "uao")
3752 return false;
3753
3754 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3755 }
3756
3757 return false;
3758}
3759
Eli Friedmanc97d0142009-05-03 06:04:26 +00003760/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003761/// This checks that the target supports __builtin_longjmp and
3762/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003763bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003764 if (!Context.getTargetInfo().hasSjLjLowering())
3765 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
3766 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3767
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003768 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00003769 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00003770
Eric Christopher8d0c6212010-04-17 02:26:23 +00003771 // TODO: This is less than ideal. Overload this to take a value.
3772 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3773 return true;
3774
3775 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003776 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3777 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3778
3779 return false;
3780}
3781
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003782/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3783/// This checks that the target supports __builtin_setjmp.
3784bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3785 if (!Context.getTargetInfo().hasSjLjLowering())
3786 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3787 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3788 return false;
3789}
3790
Richard Smithd7293d72013-08-05 18:49:43 +00003791namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003792class UncoveredArgHandler {
3793 enum { Unknown = -1, AllCovered = -2 };
3794 signed FirstUncoveredArg;
3795 SmallVector<const Expr *, 4> DiagnosticExprs;
3796
3797public:
3798 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
3799
3800 bool hasUncoveredArg() const {
3801 return (FirstUncoveredArg >= 0);
3802 }
3803
3804 unsigned getUncoveredArg() const {
3805 assert(hasUncoveredArg() && "no uncovered argument");
3806 return FirstUncoveredArg;
3807 }
3808
3809 void setAllCovered() {
3810 // A string has been found with all arguments covered, so clear out
3811 // the diagnostics.
3812 DiagnosticExprs.clear();
3813 FirstUncoveredArg = AllCovered;
3814 }
3815
3816 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
3817 assert(NewFirstUncoveredArg >= 0 && "Outside range");
3818
3819 // Don't update if a previous string covers all arguments.
3820 if (FirstUncoveredArg == AllCovered)
3821 return;
3822
3823 // UncoveredArgHandler tracks the highest uncovered argument index
3824 // and with it all the strings that match this index.
3825 if (NewFirstUncoveredArg == FirstUncoveredArg)
3826 DiagnosticExprs.push_back(StrExpr);
3827 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
3828 DiagnosticExprs.clear();
3829 DiagnosticExprs.push_back(StrExpr);
3830 FirstUncoveredArg = NewFirstUncoveredArg;
3831 }
3832 }
3833
3834 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
3835};
3836
Richard Smithd7293d72013-08-05 18:49:43 +00003837enum StringLiteralCheckType {
3838 SLCT_NotALiteral,
3839 SLCT_UncheckedLiteral,
3840 SLCT_CheckedLiteral
3841};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003842} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00003843
Stephen Hines0535fec2016-09-14 20:05:20 +00003844static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
3845 BinaryOperatorKind BinOpKind,
3846 bool AddendIsRight) {
3847 unsigned BitWidth = Offset.getBitWidth();
3848 unsigned AddendBitWidth = Addend.getBitWidth();
3849 // There might be negative interim results.
3850 if (Addend.isUnsigned()) {
3851 Addend = Addend.zext(++AddendBitWidth);
3852 Addend.setIsSigned(true);
3853 }
3854 // Adjust the bit width of the APSInts.
3855 if (AddendBitWidth > BitWidth) {
3856 Offset = Offset.sext(AddendBitWidth);
3857 BitWidth = AddendBitWidth;
3858 } else if (BitWidth > AddendBitWidth) {
3859 Addend = Addend.sext(BitWidth);
3860 }
3861
3862 bool Ov = false;
3863 llvm::APSInt ResOffset = Offset;
3864 if (BinOpKind == BO_Add)
3865 ResOffset = Offset.sadd_ov(Addend, Ov);
3866 else {
3867 assert(AddendIsRight && BinOpKind == BO_Sub &&
3868 "operator must be add or sub with addend on the right");
3869 ResOffset = Offset.ssub_ov(Addend, Ov);
3870 }
3871
3872 // We add an offset to a pointer here so we should support an offset as big as
3873 // possible.
3874 if (Ov) {
3875 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
3876 Offset.sext(2 * BitWidth);
3877 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
3878 return;
3879 }
3880
3881 Offset = ResOffset;
3882}
3883
3884namespace {
3885// This is a wrapper class around StringLiteral to support offsetted string
3886// literals as format strings. It takes the offset into account when returning
3887// the string and its length or the source locations to display notes correctly.
3888class FormatStringLiteral {
3889 const StringLiteral *FExpr;
3890 int64_t Offset;
3891
3892 public:
3893 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
3894 : FExpr(fexpr), Offset(Offset) {}
3895
3896 StringRef getString() const {
3897 return FExpr->getString().drop_front(Offset);
3898 }
3899
3900 unsigned getByteLength() const {
3901 return FExpr->getByteLength() - getCharByteWidth() * Offset;
3902 }
3903 unsigned getLength() const { return FExpr->getLength() - Offset; }
3904 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
3905
3906 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
3907
3908 QualType getType() const { return FExpr->getType(); }
3909
3910 bool isAscii() const { return FExpr->isAscii(); }
3911 bool isWide() const { return FExpr->isWide(); }
3912 bool isUTF8() const { return FExpr->isUTF8(); }
3913 bool isUTF16() const { return FExpr->isUTF16(); }
3914 bool isUTF32() const { return FExpr->isUTF32(); }
3915 bool isPascal() const { return FExpr->isPascal(); }
3916
3917 SourceLocation getLocationOfByte(
3918 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
3919 const TargetInfo &Target, unsigned *StartToken = nullptr,
3920 unsigned *StartTokenByteOffset = nullptr) const {
3921 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
3922 StartToken, StartTokenByteOffset);
3923 }
3924
3925 SourceLocation getLocStart() const LLVM_READONLY {
3926 return FExpr->getLocStart().getLocWithOffset(Offset);
3927 }
3928 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
3929};
3930} // end anonymous namespace
3931
3932static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003933 const Expr *OrigFormatExpr,
3934 ArrayRef<const Expr *> Args,
3935 bool HasVAListArg, unsigned format_idx,
3936 unsigned firstDataArg,
3937 Sema::FormatStringType Type,
3938 bool inFunctionCall,
3939 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003940 llvm::SmallBitVector &CheckedVarArgs,
3941 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003942
Richard Smith55ce3522012-06-25 20:30:08 +00003943// Determine if an expression is a string literal or constant string.
3944// If this function returns false on the arguments to a function expecting a
3945// format string, we will usually need to emit a warning.
3946// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00003947static StringLiteralCheckType
3948checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
3949 bool HasVAListArg, unsigned format_idx,
3950 unsigned firstDataArg, Sema::FormatStringType Type,
3951 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003952 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines0535fec2016-09-14 20:05:20 +00003953 UncoveredArgHandler &UncoveredArg,
3954 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00003955 tryAgain:
Stephen Hines0535fec2016-09-14 20:05:20 +00003956 assert(Offset.isSigned() && "invalid offset");
3957
Douglas Gregorc25f7662009-05-19 22:10:17 +00003958 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00003959 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003960
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003961 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00003962
Richard Smithd7293d72013-08-05 18:49:43 +00003963 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00003964 // Technically -Wformat-nonliteral does not warn about this case.
3965 // The behavior of printf and friends in this case is implementation
3966 // dependent. Ideally if the format string cannot be null then
3967 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00003968 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00003969
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003970 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00003971 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003972 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00003973 // The expression is a literal if both sub-expressions were, and it was
3974 // completely checked only if both sub-expressions were checked.
3975 const AbstractConditionalOperator *C =
3976 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003977
3978 // Determine whether it is necessary to check both sub-expressions, for
3979 // example, because the condition expression is a constant that can be
3980 // evaluated at compile time.
3981 bool CheckLeft = true, CheckRight = true;
3982
3983 bool Cond;
3984 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
3985 if (Cond)
3986 CheckRight = false;
3987 else
3988 CheckLeft = false;
3989 }
3990
Stephen Hines0535fec2016-09-14 20:05:20 +00003991 // We need to maintain the offsets for the right and the left hand side
3992 // separately to check if every possible indexed expression is a valid
3993 // string literal. They might have different offsets for different string
3994 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003995 StringLiteralCheckType Left;
3996 if (!CheckLeft)
3997 Left = SLCT_UncheckedLiteral;
3998 else {
3999 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4000 HasVAListArg, format_idx, firstDataArg,
4001 Type, CallType, InFunctionCall,
Stephen Hines0535fec2016-09-14 20:05:20 +00004002 CheckedVarArgs, UncoveredArg, Offset);
4003 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004004 return Left;
Stephen Hines0535fec2016-09-14 20:05:20 +00004005 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004006 }
4007
Richard Smith55ce3522012-06-25 20:30:08 +00004008 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004009 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004010 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004011 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines0535fec2016-09-14 20:05:20 +00004012 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004013
4014 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004015 }
4016
4017 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00004018 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4019 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004020 }
4021
John McCallc07a0c72011-02-17 10:25:35 +00004022 case Stmt::OpaqueValueExprClass:
4023 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4024 E = src;
4025 goto tryAgain;
4026 }
Richard Smith55ce3522012-06-25 20:30:08 +00004027 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004028
Ted Kremeneka8890832011-02-24 23:03:04 +00004029 case Stmt::PredefinedExprClass:
4030 // While __func__, etc., are technically not string literals, they
4031 // cannot contain format specifiers and thus are not a security
4032 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004033 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004034
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004035 case Stmt::DeclRefExprClass: {
4036 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004037
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004038 // As an exception, do not flag errors for variables binding to
4039 // const string literals.
4040 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4041 bool isConstant = false;
4042 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004043
Richard Smithd7293d72013-08-05 18:49:43 +00004044 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4045 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004046 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004047 isConstant = T.isConstant(S.Context) &&
4048 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004049 } else if (T->isObjCObjectPointerType()) {
4050 // In ObjC, there is usually no "const ObjectPointer" type,
4051 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004052 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004053 }
Mike Stump11289f42009-09-09 15:08:12 +00004054
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004055 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004056 if (const Expr *Init = VD->getAnyInitializer()) {
4057 // Look through initializers like const char c[] = { "foo" }
4058 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4059 if (InitList->isStringLiteralInit())
4060 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4061 }
Richard Smithd7293d72013-08-05 18:49:43 +00004062 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004063 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004064 firstDataArg, Type, CallType,
Stephen Hines0535fec2016-09-14 20:05:20 +00004065 /*InFunctionCall*/ false, CheckedVarArgs,
4066 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004067 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004068 }
Mike Stump11289f42009-09-09 15:08:12 +00004069
Anders Carlssonb012ca92009-06-28 19:55:58 +00004070 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4071 // special check to see if the format string is a function parameter
4072 // of the function calling the printf function. If the function
4073 // has an attribute indicating it is a printf-like function, then we
4074 // should suppress warnings concerning non-literals being used in a call
4075 // to a vprintf function. For example:
4076 //
4077 // void
4078 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4079 // va_list ap;
4080 // va_start(ap, fmt);
4081 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4082 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00004083 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004084 if (HasVAListArg) {
4085 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4086 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4087 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004088 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004089 // adjust for implicit parameter
4090 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4091 if (MD->isInstance())
4092 ++PVIndex;
4093 // We also check if the formats are compatible.
4094 // We can't pass a 'scanf' string to a 'printf' function.
4095 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00004096 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00004097 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004098 }
4099 }
4100 }
4101 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004102 }
Mike Stump11289f42009-09-09 15:08:12 +00004103
Richard Smith55ce3522012-06-25 20:30:08 +00004104 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004105 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004106
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004107 case Stmt::CallExprClass:
4108 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004109 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004110 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4111 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4112 unsigned ArgIndex = FA->getFormatIdx();
4113 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4114 if (MD->isInstance())
4115 --ArgIndex;
4116 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00004117
Richard Smithd7293d72013-08-05 18:49:43 +00004118 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004119 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00004120 Type, CallType, InFunctionCall,
Stephen Hines0535fec2016-09-14 20:05:20 +00004121 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004122 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4123 unsigned BuiltinID = FD->getBuiltinID();
4124 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4125 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4126 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00004127 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004128 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004129 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004130 InFunctionCall, CheckedVarArgs,
Stephen Hines0535fec2016-09-14 20:05:20 +00004131 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004132 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004133 }
4134 }
Mike Stump11289f42009-09-09 15:08:12 +00004135
Richard Smith55ce3522012-06-25 20:30:08 +00004136 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004137 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004138 case Stmt::ObjCStringLiteralClass:
4139 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00004140 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004141
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004142 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004143 StrE = ObjCFExpr->getString();
4144 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004145 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004146
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004147 if (StrE) {
Stephen Hines0535fec2016-09-14 20:05:20 +00004148 if (Offset.isNegative() || Offset > StrE->getLength()) {
4149 // TODO: It would be better to have an explicit warning for out of
4150 // bounds literals.
4151 return SLCT_NotALiteral;
4152 }
4153 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4154 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004155 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004156 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00004157 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004158 }
Mike Stump11289f42009-09-09 15:08:12 +00004159
Richard Smith55ce3522012-06-25 20:30:08 +00004160 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004161 }
Stephen Hines0535fec2016-09-14 20:05:20 +00004162 case Stmt::BinaryOperatorClass: {
4163 llvm::APSInt LResult;
4164 llvm::APSInt RResult;
4165
4166 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4167
4168 // A string literal + an int offset is still a string literal.
4169 if (BinOp->isAdditiveOp()) {
4170 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4171 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4172
4173 if (LIsInt != RIsInt) {
4174 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4175
4176 if (LIsInt) {
4177 if (BinOpKind == BO_Add) {
4178 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4179 E = BinOp->getRHS();
4180 goto tryAgain;
4181 }
4182 } else {
4183 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4184 E = BinOp->getLHS();
4185 goto tryAgain;
4186 }
4187 }
4188
4189 return SLCT_NotALiteral;
4190 }
4191 }
4192 case Stmt::UnaryOperatorClass: {
4193 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4194 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4195 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4196 llvm::APSInt IndexResult;
4197 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4198 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4199 E = ASE->getBase();
4200 goto tryAgain;
4201 }
4202 }
4203
4204 return SLCT_NotALiteral;
4205 }
Mike Stump11289f42009-09-09 15:08:12 +00004206
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004207 default:
Richard Smith55ce3522012-06-25 20:30:08 +00004208 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004209 }
4210}
4211
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004212Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00004213 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004214 .Case("scanf", FST_Scanf)
4215 .Cases("printf", "printf0", FST_Printf)
4216 .Cases("NSString", "CFString", FST_NSString)
4217 .Case("strftime", FST_Strftime)
4218 .Case("strfmon", FST_Strfmon)
4219 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004220 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004221 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004222 .Default(FST_Unknown);
4223}
4224
Jordan Rose3e0ec582012-07-19 18:10:23 +00004225/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00004226/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00004227/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004228bool Sema::CheckFormatArguments(const FormatAttr *Format,
4229 ArrayRef<const Expr *> Args,
4230 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004231 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004232 SourceLocation Loc, SourceRange Range,
4233 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00004234 FormatStringInfo FSI;
4235 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004236 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00004237 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00004238 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00004239 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004240}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00004241
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004242bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004243 bool HasVAListArg, unsigned format_idx,
4244 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004245 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004246 SourceLocation Loc, SourceRange Range,
4247 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004248 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004249 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004250 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00004251 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004252 }
Mike Stump11289f42009-09-09 15:08:12 +00004253
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004254 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004255
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004256 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00004257 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004258 // Dynamically generated format strings are difficult to
4259 // automatically vet at compile time. Requiring that format strings
4260 // are string literals: (1) permits the checking of format strings by
4261 // the compiler and thereby (2) can practically remove the source of
4262 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00004263
Mike Stump11289f42009-09-09 15:08:12 +00004264 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00004265 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00004266 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00004267 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004268 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00004269 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00004270 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4271 format_idx, firstDataArg, Type, CallType,
Stephen Hines0535fec2016-09-14 20:05:20 +00004272 /*IsFunctionCall*/ true, CheckedVarArgs,
4273 UncoveredArg,
4274 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004275
4276 // Generate a diagnostic where an uncovered argument is detected.
4277 if (UncoveredArg.hasUncoveredArg()) {
4278 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4279 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4280 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4281 }
4282
Richard Smith55ce3522012-06-25 20:30:08 +00004283 if (CT != SLCT_NotALiteral)
4284 // Literal format string found, check done!
4285 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00004286
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004287 // Strftime is particular as it always uses a single 'time' argument,
4288 // so it is safe to pass a non-literal string.
4289 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00004290 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004291
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004292 // Do not emit diag when the string param is a macro expansion and the
4293 // format is either NSString or CFString. This is a hack to prevent
4294 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4295 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004296 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4297 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00004298 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004299
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004300 // If there are no arguments specified, warn with -Wformat-security, otherwise
4301 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004302 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00004303 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4304 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004305 switch (Type) {
4306 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004307 break;
4308 case FST_Kprintf:
4309 case FST_FreeBSDKPrintf:
4310 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00004311 Diag(FormatLoc, diag::note_format_security_fixit)
4312 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004313 break;
4314 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00004315 Diag(FormatLoc, diag::note_format_security_fixit)
4316 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004317 break;
4318 }
4319 } else {
4320 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004321 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004322 }
Richard Smith55ce3522012-06-25 20:30:08 +00004323 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004324}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004325
Ted Kremenekab278de2010-01-28 23:39:18 +00004326namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00004327class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4328protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00004329 Sema &S;
Stephen Hines0535fec2016-09-14 20:05:20 +00004330 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00004331 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00004332 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00004333 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00004334 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00004335 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004336 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00004337 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00004338 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00004339 bool usesPositionalArgs;
4340 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004341 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00004342 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00004343 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004344 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004345
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004346public:
Stephen Hines0535fec2016-09-14 20:05:20 +00004347 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00004348 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004349 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004350 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004351 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004352 Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004353 llvm::SmallBitVector &CheckedVarArgs,
4354 UncoveredArgHandler &UncoveredArg)
Ted Kremenekab278de2010-01-28 23:39:18 +00004355 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004356 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
4357 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004358 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00004359 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00004360 inFunctionCall(inFunctionCall), CallType(callType),
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004361 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00004362 CoveredArgs.resize(numDataArgs);
4363 CoveredArgs.reset();
4364 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004365
Ted Kremenek019d2242010-01-29 01:50:07 +00004366 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004367
Ted Kremenek02087932010-07-16 02:11:22 +00004368 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004369 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004370
Jordan Rose92303592012-09-08 04:00:03 +00004371 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004372 const analyze_format_string::FormatSpecifier &FS,
4373 const analyze_format_string::ConversionSpecifier &CS,
4374 const char *startSpecifier, unsigned specifierLen,
4375 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00004376
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004377 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004378 const analyze_format_string::FormatSpecifier &FS,
4379 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004380
4381 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004382 const analyze_format_string::ConversionSpecifier &CS,
4383 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004384
Craig Toppere14c0f82014-03-12 04:55:44 +00004385 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004386
Craig Toppere14c0f82014-03-12 04:55:44 +00004387 void HandleInvalidPosition(const char *startSpecifier,
4388 unsigned specifierLen,
4389 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004390
Craig Toppere14c0f82014-03-12 04:55:44 +00004391 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004392
Craig Toppere14c0f82014-03-12 04:55:44 +00004393 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004394
Richard Trieu03cf7b72011-10-28 00:41:25 +00004395 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00004396 static void
4397 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4398 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4399 bool IsStringLocation, Range StringRange,
4400 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004401
Ted Kremenek02087932010-07-16 02:11:22 +00004402protected:
Ted Kremenekce815422010-07-19 21:25:57 +00004403 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4404 const char *startSpec,
4405 unsigned specifierLen,
4406 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004407
4408 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4409 const char *startSpec,
4410 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00004411
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004412 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00004413 CharSourceRange getSpecifierRange(const char *startSpecifier,
4414 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00004415 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004416
Ted Kremenek5739de72010-01-29 01:06:55 +00004417 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004418
4419 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4420 const analyze_format_string::ConversionSpecifier &CS,
4421 const char *startSpecifier, unsigned specifierLen,
4422 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004423
4424 template <typename Range>
4425 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4426 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004427 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00004428};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004429} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004430
Ted Kremenek02087932010-07-16 02:11:22 +00004431SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00004432 return OrigFormatExpr->getSourceRange();
4433}
4434
Ted Kremenek02087932010-07-16 02:11:22 +00004435CharSourceRange CheckFormatHandler::
4436getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00004437 SourceLocation Start = getLocationOfByte(startSpecifier);
4438 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
4439
4440 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004441 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00004442
4443 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004444}
4445
Ted Kremenek02087932010-07-16 02:11:22 +00004446SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines0535fec2016-09-14 20:05:20 +00004447 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
4448 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00004449}
4450
Ted Kremenek02087932010-07-16 02:11:22 +00004451void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4452 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00004453 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4454 getLocationOfByte(startSpecifier),
4455 /*IsStringLocation*/true,
4456 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00004457}
4458
Jordan Rose92303592012-09-08 04:00:03 +00004459void CheckFormatHandler::HandleInvalidLengthModifier(
4460 const analyze_format_string::FormatSpecifier &FS,
4461 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00004462 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00004463 using namespace analyze_format_string;
4464
4465 const LengthModifier &LM = FS.getLengthModifier();
4466 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4467
4468 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004469 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00004470 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004471 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004472 getLocationOfByte(LM.getStart()),
4473 /*IsStringLocation*/true,
4474 getSpecifierRange(startSpecifier, specifierLen));
4475
4476 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4477 << FixedLM->toString()
4478 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4479
4480 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004481 FixItHint Hint;
4482 if (DiagID == diag::warn_format_nonsensical_length)
4483 Hint = FixItHint::CreateRemoval(LMRange);
4484
4485 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004486 getLocationOfByte(LM.getStart()),
4487 /*IsStringLocation*/true,
4488 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00004489 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00004490 }
4491}
4492
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004493void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00004494 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004495 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004496 using namespace analyze_format_string;
4497
4498 const LengthModifier &LM = FS.getLengthModifier();
4499 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4500
4501 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004502 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00004503 if (FixedLM) {
4504 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4505 << LM.toString() << 0,
4506 getLocationOfByte(LM.getStart()),
4507 /*IsStringLocation*/true,
4508 getSpecifierRange(startSpecifier, specifierLen));
4509
4510 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4511 << FixedLM->toString()
4512 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4513
4514 } else {
4515 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4516 << LM.toString() << 0,
4517 getLocationOfByte(LM.getStart()),
4518 /*IsStringLocation*/true,
4519 getSpecifierRange(startSpecifier, specifierLen));
4520 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004521}
4522
4523void CheckFormatHandler::HandleNonStandardConversionSpecifier(
4524 const analyze_format_string::ConversionSpecifier &CS,
4525 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00004526 using namespace analyze_format_string;
4527
4528 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00004529 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00004530 if (FixedCS) {
4531 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4532 << CS.toString() << /*conversion specifier*/1,
4533 getLocationOfByte(CS.getStart()),
4534 /*IsStringLocation*/true,
4535 getSpecifierRange(startSpecifier, specifierLen));
4536
4537 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
4538 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
4539 << FixedCS->toString()
4540 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
4541 } else {
4542 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4543 << CS.toString() << /*conversion specifier*/1,
4544 getLocationOfByte(CS.getStart()),
4545 /*IsStringLocation*/true,
4546 getSpecifierRange(startSpecifier, specifierLen));
4547 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004548}
4549
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004550void CheckFormatHandler::HandlePosition(const char *startPos,
4551 unsigned posLen) {
4552 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
4553 getLocationOfByte(startPos),
4554 /*IsStringLocation*/true,
4555 getSpecifierRange(startPos, posLen));
4556}
4557
Ted Kremenekd1668192010-02-27 01:41:03 +00004558void
Ted Kremenek02087932010-07-16 02:11:22 +00004559CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
4560 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004561 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
4562 << (unsigned) p,
4563 getLocationOfByte(startPos), /*IsStringLocation*/true,
4564 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00004565}
4566
Ted Kremenek02087932010-07-16 02:11:22 +00004567void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00004568 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004569 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
4570 getLocationOfByte(startPos),
4571 /*IsStringLocation*/true,
4572 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00004573}
4574
Ted Kremenek02087932010-07-16 02:11:22 +00004575void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004576 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00004577 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004578 EmitFormatDiagnostic(
4579 S.PDiag(diag::warn_printf_format_string_contains_null_char),
4580 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
4581 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00004582 }
Ted Kremenek02087932010-07-16 02:11:22 +00004583}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004584
Jordan Rose58bbe422012-07-19 18:10:08 +00004585// Note that this may return NULL if there was an error parsing or building
4586// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00004587const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004588 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00004589}
4590
4591void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004592 // Does the number of data arguments exceed the number of
4593 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00004594 if (!HasVAListArg) {
4595 // Find any arguments that weren't covered.
4596 CoveredArgs.flip();
4597 signed notCoveredArg = CoveredArgs.find_first();
4598 if (notCoveredArg >= 0) {
4599 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004600 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
4601 } else {
4602 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00004603 }
4604 }
4605}
4606
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004607void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
4608 const Expr *ArgExpr) {
4609 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
4610 "Invalid state");
4611
4612 if (!ArgExpr)
4613 return;
4614
4615 SourceLocation Loc = ArgExpr->getLocStart();
4616
4617 if (S.getSourceManager().isInSystemMacro(Loc))
4618 return;
4619
4620 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
4621 for (auto E : DiagnosticExprs)
4622 PDiag << E->getSourceRange();
4623
4624 CheckFormatHandler::EmitFormatDiagnostic(
4625 S, IsFunctionCall, DiagnosticExprs[0],
4626 PDiag, Loc, /*IsStringLocation*/false,
4627 DiagnosticExprs[0]->getSourceRange());
4628}
4629
Ted Kremenekce815422010-07-19 21:25:57 +00004630bool
4631CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
4632 SourceLocation Loc,
4633 const char *startSpec,
4634 unsigned specifierLen,
4635 const char *csStart,
4636 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00004637 bool keepGoing = true;
4638 if (argIndex < NumDataArgs) {
4639 // Consider the argument coverered, even though the specifier doesn't
4640 // make sense.
4641 CoveredArgs.set(argIndex);
4642 }
4643 else {
4644 // If argIndex exceeds the number of data arguments we
4645 // don't issue a warning because that is just a cascade of warnings (and
4646 // they may have intended '%%' anyway). We don't want to continue processing
4647 // the format string after this point, however, as we will like just get
4648 // gibberish when trying to match arguments.
4649 keepGoing = false;
4650 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00004651
4652 StringRef Specifier(csStart, csLen);
4653
4654 // If the specifier in non-printable, it could be the first byte of a UTF-8
4655 // sequence. In that case, print the UTF-8 code point. If not, print the byte
4656 // hex value.
4657 std::string CodePointStr;
4658 if (!llvm::sys::locale::isPrint(*csStart)) {
4659 UTF32 CodePoint;
4660 const UTF8 **B = reinterpret_cast<const UTF8 **>(&csStart);
4661 const UTF8 *E =
4662 reinterpret_cast<const UTF8 *>(csStart + csLen);
4663 ConversionResult Result =
4664 llvm::convertUTF8Sequence(B, E, &CodePoint, strictConversion);
4665
4666 if (Result != conversionOK) {
4667 unsigned char FirstChar = *csStart;
4668 CodePoint = (UTF32)FirstChar;
4669 }
4670
4671 llvm::raw_string_ostream OS(CodePointStr);
4672 if (CodePoint < 256)
4673 OS << "\\x" << llvm::format("%02x", CodePoint);
4674 else if (CodePoint <= 0xFFFF)
4675 OS << "\\u" << llvm::format("%04x", CodePoint);
4676 else
4677 OS << "\\U" << llvm::format("%08x", CodePoint);
4678 OS.flush();
4679 Specifier = CodePointStr;
4680 }
4681
4682 EmitFormatDiagnostic(
4683 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
4684 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
4685
Ted Kremenekce815422010-07-19 21:25:57 +00004686 return keepGoing;
4687}
4688
Richard Trieu03cf7b72011-10-28 00:41:25 +00004689void
4690CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
4691 const char *startSpec,
4692 unsigned specifierLen) {
4693 EmitFormatDiagnostic(
4694 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
4695 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
4696}
4697
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004698bool
4699CheckFormatHandler::CheckNumArgs(
4700 const analyze_format_string::FormatSpecifier &FS,
4701 const analyze_format_string::ConversionSpecifier &CS,
4702 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
4703
4704 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004705 PartialDiagnostic PDiag = FS.usesPositionalArg()
4706 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
4707 << (argIndex+1) << NumDataArgs)
4708 : S.PDiag(diag::warn_printf_insufficient_data_args);
4709 EmitFormatDiagnostic(
4710 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
4711 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004712
4713 // Since more arguments than conversion tokens are given, by extension
4714 // all arguments are covered, so mark this as so.
4715 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004716 return false;
4717 }
4718 return true;
4719}
4720
Richard Trieu03cf7b72011-10-28 00:41:25 +00004721template<typename Range>
4722void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
4723 SourceLocation Loc,
4724 bool IsStringLocation,
4725 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00004726 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004727 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00004728 Loc, IsStringLocation, StringRange, FixIt);
4729}
4730
4731/// \brief If the format string is not within the funcion call, emit a note
4732/// so that the function call and string are in diagnostic messages.
4733///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004734/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00004735/// call and only one diagnostic message will be produced. Otherwise, an
4736/// extra note will be emitted pointing to location of the format string.
4737///
4738/// \param ArgumentExpr the expression that is passed as the format string
4739/// argument in the function call. Used for getting locations when two
4740/// diagnostics are emitted.
4741///
4742/// \param PDiag the callee should already have provided any strings for the
4743/// diagnostic message. This function only adds locations and fixits
4744/// to diagnostics.
4745///
4746/// \param Loc primary location for diagnostic. If two diagnostics are
4747/// required, one will be at Loc and a new SourceLocation will be created for
4748/// the other one.
4749///
4750/// \param IsStringLocation if true, Loc points to the format string should be
4751/// used for the note. Otherwise, Loc points to the argument list and will
4752/// be used with PDiag.
4753///
4754/// \param StringRange some or all of the string to highlight. This is
4755/// templated so it can accept either a CharSourceRange or a SourceRange.
4756///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004757/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00004758template <typename Range>
4759void CheckFormatHandler::EmitFormatDiagnostic(
4760 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
4761 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
4762 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00004763 if (InFunctionCall) {
4764 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
4765 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004766 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00004767 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004768 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
4769 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00004770
4771 const Sema::SemaDiagnosticBuilder &Note =
4772 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
4773 diag::note_format_string_defined);
4774
4775 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004776 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004777 }
4778}
4779
Ted Kremenek02087932010-07-16 02:11:22 +00004780//===--- CHECK: Printf format string checking ------------------------------===//
4781
4782namespace {
4783class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004784 bool ObjCContext;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004785
Ted Kremenek02087932010-07-16 02:11:22 +00004786public:
Stephen Hines0535fec2016-09-14 20:05:20 +00004787 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Ted Kremenek02087932010-07-16 02:11:22 +00004788 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004789 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00004790 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004791 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004792 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004793 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004794 llvm::SmallBitVector &CheckedVarArgs,
4795 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00004796 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4797 numDataArgs, beg, hasVAListArg, Args,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004798 formatIdx, inFunctionCall, CallType, CheckedVarArgs,
4799 UncoveredArg),
Richard Smithd7293d72013-08-05 18:49:43 +00004800 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004801 {}
4802
Ted Kremenek02087932010-07-16 02:11:22 +00004803 bool HandleInvalidPrintfConversionSpecifier(
4804 const analyze_printf::PrintfSpecifier &FS,
4805 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004806 unsigned specifierLen) override;
4807
Ted Kremenek02087932010-07-16 02:11:22 +00004808 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
4809 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004810 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004811 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4812 const char *StartSpecifier,
4813 unsigned SpecifierLen,
4814 const Expr *E);
4815
Ted Kremenek02087932010-07-16 02:11:22 +00004816 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
4817 const char *startSpecifier, unsigned specifierLen);
4818 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
4819 const analyze_printf::OptionalAmount &Amt,
4820 unsigned type,
4821 const char *startSpecifier, unsigned specifierLen);
4822 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
4823 const analyze_printf::OptionalFlag &flag,
4824 const char *startSpecifier, unsigned specifierLen);
4825 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
4826 const analyze_printf::OptionalFlag &ignoredFlag,
4827 const analyze_printf::OptionalFlag &flag,
4828 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004829 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00004830 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00004831
4832 void HandleEmptyObjCModifierFlag(const char *startFlag,
4833 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004834
Ted Kremenek2b417712015-07-02 05:39:16 +00004835 void HandleInvalidObjCModifierFlag(const char *startFlag,
4836 unsigned flagLen) override;
4837
4838 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
4839 const char *flagsEnd,
4840 const char *conversionPosition)
4841 override;
4842};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004843} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00004844
4845bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
4846 const analyze_printf::PrintfSpecifier &FS,
4847 const char *startSpecifier,
4848 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004849 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004850 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004851
Ted Kremenekce815422010-07-19 21:25:57 +00004852 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4853 getLocationOfByte(CS.getStart()),
4854 startSpecifier, specifierLen,
4855 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00004856}
4857
Ted Kremenek02087932010-07-16 02:11:22 +00004858bool CheckPrintfHandler::HandleAmount(
4859 const analyze_format_string::OptionalAmount &Amt,
4860 unsigned k, const char *startSpecifier,
4861 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004862 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004863 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00004864 unsigned argIndex = Amt.getArgIndex();
4865 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004866 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
4867 << k,
4868 getLocationOfByte(Amt.getStart()),
4869 /*IsStringLocation*/true,
4870 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004871 // Don't do any more checking. We will just emit
4872 // spurious errors.
4873 return false;
4874 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004875
Ted Kremenek5739de72010-01-29 01:06:55 +00004876 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00004877 // Although not in conformance with C99, we also allow the argument to be
4878 // an 'unsigned int' as that is a reasonably safe case. GCC also
4879 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00004880 CoveredArgs.set(argIndex);
4881 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004882 if (!Arg)
4883 return false;
4884
Ted Kremenek5739de72010-01-29 01:06:55 +00004885 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004886
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004887 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
4888 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004889
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004890 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004891 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004892 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00004893 << T << Arg->getSourceRange(),
4894 getLocationOfByte(Amt.getStart()),
4895 /*IsStringLocation*/true,
4896 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004897 // Don't do any more checking. We will just emit
4898 // spurious errors.
4899 return false;
4900 }
4901 }
4902 }
4903 return true;
4904}
Ted Kremenek5739de72010-01-29 01:06:55 +00004905
Tom Careb49ec692010-06-17 19:00:27 +00004906void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00004907 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004908 const analyze_printf::OptionalAmount &Amt,
4909 unsigned type,
4910 const char *startSpecifier,
4911 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004912 const analyze_printf::PrintfConversionSpecifier &CS =
4913 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00004914
Richard Trieu03cf7b72011-10-28 00:41:25 +00004915 FixItHint fixit =
4916 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
4917 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
4918 Amt.getConstantLength()))
4919 : FixItHint();
4920
4921 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
4922 << type << CS.toString(),
4923 getLocationOfByte(Amt.getStart()),
4924 /*IsStringLocation*/true,
4925 getSpecifierRange(startSpecifier, specifierLen),
4926 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00004927}
4928
Ted Kremenek02087932010-07-16 02:11:22 +00004929void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004930 const analyze_printf::OptionalFlag &flag,
4931 const char *startSpecifier,
4932 unsigned specifierLen) {
4933 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004934 const analyze_printf::PrintfConversionSpecifier &CS =
4935 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00004936 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
4937 << flag.toString() << CS.toString(),
4938 getLocationOfByte(flag.getPosition()),
4939 /*IsStringLocation*/true,
4940 getSpecifierRange(startSpecifier, specifierLen),
4941 FixItHint::CreateRemoval(
4942 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004943}
4944
4945void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00004946 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004947 const analyze_printf::OptionalFlag &ignoredFlag,
4948 const analyze_printf::OptionalFlag &flag,
4949 const char *startSpecifier,
4950 unsigned specifierLen) {
4951 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004952 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
4953 << ignoredFlag.toString() << flag.toString(),
4954 getLocationOfByte(ignoredFlag.getPosition()),
4955 /*IsStringLocation*/true,
4956 getSpecifierRange(startSpecifier, specifierLen),
4957 FixItHint::CreateRemoval(
4958 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004959}
4960
Ted Kremenek2b417712015-07-02 05:39:16 +00004961// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4962// bool IsStringLocation, Range StringRange,
4963// ArrayRef<FixItHint> Fixit = None);
4964
4965void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
4966 unsigned flagLen) {
4967 // Warn about an empty flag.
4968 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
4969 getLocationOfByte(startFlag),
4970 /*IsStringLocation*/true,
4971 getSpecifierRange(startFlag, flagLen));
4972}
4973
4974void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
4975 unsigned flagLen) {
4976 // Warn about an invalid flag.
4977 auto Range = getSpecifierRange(startFlag, flagLen);
4978 StringRef flag(startFlag, flagLen);
4979 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
4980 getLocationOfByte(startFlag),
4981 /*IsStringLocation*/true,
4982 Range, FixItHint::CreateRemoval(Range));
4983}
4984
4985void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
4986 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
4987 // Warn about using '[...]' without a '@' conversion.
4988 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
4989 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
4990 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
4991 getLocationOfByte(conversionPosition),
4992 /*IsStringLocation*/true,
4993 Range, FixItHint::CreateRemoval(Range));
4994}
4995
Richard Smith55ce3522012-06-25 20:30:08 +00004996// Determines if the specified is a C++ class or struct containing
4997// a member with the specified name and kind (e.g. a CXXMethodDecl named
4998// "c_str()").
4999template<typename MemberKind>
5000static llvm::SmallPtrSet<MemberKind*, 1>
5001CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5002 const RecordType *RT = Ty->getAs<RecordType>();
5003 llvm::SmallPtrSet<MemberKind*, 1> Results;
5004
5005 if (!RT)
5006 return Results;
5007 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005008 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005009 return Results;
5010
Alp Tokerb6cc5922014-05-03 03:45:55 +00005011 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005012 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005013 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005014
5015 // We just need to include all members of the right kind turned up by the
5016 // filter, at this point.
5017 if (S.LookupQualifiedName(R, RT->getDecl()))
5018 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5019 NamedDecl *decl = (*I)->getUnderlyingDecl();
5020 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5021 Results.insert(FK);
5022 }
5023 return Results;
5024}
5025
Richard Smith2868a732014-02-28 01:36:39 +00005026/// Check if we could call '.c_str()' on an object.
5027///
5028/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5029/// allow the call, or if it would be ambiguous).
5030bool Sema::hasCStrMethod(const Expr *E) {
5031 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5032 MethodSet Results =
5033 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5034 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5035 MI != ME; ++MI)
5036 if ((*MI)->getMinRequiredArguments() == 0)
5037 return true;
5038 return false;
5039}
5040
Richard Smith55ce3522012-06-25 20:30:08 +00005041// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005042// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00005043// Returns true when a c_str() conversion method is found.
5044bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00005045 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00005046 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5047
5048 MethodSet Results =
5049 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5050
5051 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5052 MI != ME; ++MI) {
5053 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00005054 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00005055 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00005056 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00005057 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00005058 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5059 << "c_str()"
5060 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5061 return true;
5062 }
5063 }
5064
5065 return false;
5066}
5067
Ted Kremenekab278de2010-01-28 23:39:18 +00005068bool
Ted Kremenek02087932010-07-16 02:11:22 +00005069CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00005070 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00005071 const char *startSpecifier,
5072 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005073 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00005074 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005075 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00005076
Ted Kremenek6cd69422010-07-19 22:01:06 +00005077 if (FS.consumesDataArgument()) {
5078 if (atFirstArg) {
5079 atFirstArg = false;
5080 usesPositionalArgs = FS.usesPositionalArg();
5081 }
5082 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005083 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5084 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005085 return false;
5086 }
Ted Kremenek5739de72010-01-29 01:06:55 +00005087 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005088
Ted Kremenekd1668192010-02-27 01:41:03 +00005089 // First check if the field width, precision, and conversion specifier
5090 // have matching data arguments.
5091 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5092 startSpecifier, specifierLen)) {
5093 return false;
5094 }
5095
5096 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5097 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005098 return false;
5099 }
5100
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005101 if (!CS.consumesDataArgument()) {
5102 // FIXME: Technically specifying a precision or field width here
5103 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00005104 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005105 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005106
Ted Kremenek4a49d982010-02-26 19:18:41 +00005107 // Consume the argument.
5108 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00005109 if (argIndex < NumDataArgs) {
5110 // The check to see if the argIndex is valid will come later.
5111 // We set the bit here because we may exit early from this
5112 // function if we encounter some other error.
5113 CoveredArgs.set(argIndex);
5114 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00005115
Dimitry Andric6b5ed342015-02-19 22:32:33 +00005116 // FreeBSD kernel extensions.
5117 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5118 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5119 // We need at least two arguments.
5120 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5121 return false;
5122
5123 // Claim the second argument.
5124 CoveredArgs.set(argIndex + 1);
5125
5126 // Type check the first argument (int for %b, pointer for %D)
5127 const Expr *Ex = getDataArg(argIndex);
5128 const analyze_printf::ArgType &AT =
5129 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5130 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5131 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5132 EmitFormatDiagnostic(
5133 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5134 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5135 << false << Ex->getSourceRange(),
5136 Ex->getLocStart(), /*IsStringLocation*/false,
5137 getSpecifierRange(startSpecifier, specifierLen));
5138
5139 // Type check the second argument (char * for both %b and %D)
5140 Ex = getDataArg(argIndex + 1);
5141 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5142 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5143 EmitFormatDiagnostic(
5144 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5145 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5146 << false << Ex->getSourceRange(),
5147 Ex->getLocStart(), /*IsStringLocation*/false,
5148 getSpecifierRange(startSpecifier, specifierLen));
5149
5150 return true;
5151 }
5152
Ted Kremenek4a49d982010-02-26 19:18:41 +00005153 // Check for using an Objective-C specific conversion specifier
5154 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005155 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00005156 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5157 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00005158 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005159
Tom Careb49ec692010-06-17 19:00:27 +00005160 // Check for invalid use of field width
5161 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00005162 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00005163 startSpecifier, specifierLen);
5164 }
5165
5166 // Check for invalid use of precision
5167 if (!FS.hasValidPrecision()) {
5168 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5169 startSpecifier, specifierLen);
5170 }
5171
5172 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00005173 if (!FS.hasValidThousandsGroupingPrefix())
5174 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005175 if (!FS.hasValidLeadingZeros())
5176 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5177 if (!FS.hasValidPlusPrefix())
5178 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00005179 if (!FS.hasValidSpacePrefix())
5180 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005181 if (!FS.hasValidAlternativeForm())
5182 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5183 if (!FS.hasValidLeftJustified())
5184 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5185
5186 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00005187 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5188 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5189 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005190 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5191 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5192 startSpecifier, specifierLen);
5193
5194 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005195 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005196 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5197 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005198 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005199 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005200 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005201 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5202 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00005203
Jordan Rose92303592012-09-08 04:00:03 +00005204 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5205 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5206
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005207 // The remaining checks depend on the data arguments.
5208 if (HasVAListArg)
5209 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005210
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005211 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005212 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005213
Jordan Rose58bbe422012-07-19 18:10:08 +00005214 const Expr *Arg = getDataArg(argIndex);
5215 if (!Arg)
5216 return true;
5217
5218 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00005219}
5220
Jordan Roseaee34382012-09-05 22:56:26 +00005221static bool requiresParensToAddCast(const Expr *E) {
5222 // FIXME: We should have a general way to reason about operator
5223 // precedence and whether parens are actually needed here.
5224 // Take care of a few common cases where they aren't.
5225 const Expr *Inside = E->IgnoreImpCasts();
5226 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5227 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5228
5229 switch (Inside->getStmtClass()) {
5230 case Stmt::ArraySubscriptExprClass:
5231 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005232 case Stmt::CharacterLiteralClass:
5233 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005234 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005235 case Stmt::FloatingLiteralClass:
5236 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005237 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005238 case Stmt::ObjCArrayLiteralClass:
5239 case Stmt::ObjCBoolLiteralExprClass:
5240 case Stmt::ObjCBoxedExprClass:
5241 case Stmt::ObjCDictionaryLiteralClass:
5242 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005243 case Stmt::ObjCIvarRefExprClass:
5244 case Stmt::ObjCMessageExprClass:
5245 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005246 case Stmt::ObjCStringLiteralClass:
5247 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005248 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005249 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005250 case Stmt::UnaryOperatorClass:
5251 return false;
5252 default:
5253 return true;
5254 }
5255}
5256
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005257static std::pair<QualType, StringRef>
5258shouldNotPrintDirectly(const ASTContext &Context,
5259 QualType IntendedTy,
5260 const Expr *E) {
5261 // Use a 'while' to peel off layers of typedefs.
5262 QualType TyTy = IntendedTy;
5263 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5264 StringRef Name = UserTy->getDecl()->getName();
5265 QualType CastTy = llvm::StringSwitch<QualType>(Name)
5266 .Case("NSInteger", Context.LongTy)
5267 .Case("NSUInteger", Context.UnsignedLongTy)
5268 .Case("SInt32", Context.IntTy)
5269 .Case("UInt32", Context.UnsignedIntTy)
5270 .Default(QualType());
5271
5272 if (!CastTy.isNull())
5273 return std::make_pair(CastTy, Name);
5274
5275 TyTy = UserTy->desugar();
5276 }
5277
5278 // Strip parens if necessary.
5279 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5280 return shouldNotPrintDirectly(Context,
5281 PE->getSubExpr()->getType(),
5282 PE->getSubExpr());
5283
5284 // If this is a conditional expression, then its result type is constructed
5285 // via usual arithmetic conversions and thus there might be no necessary
5286 // typedef sugar there. Recurse to operands to check for NSInteger &
5287 // Co. usage condition.
5288 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5289 QualType TrueTy, FalseTy;
5290 StringRef TrueName, FalseName;
5291
5292 std::tie(TrueTy, TrueName) =
5293 shouldNotPrintDirectly(Context,
5294 CO->getTrueExpr()->getType(),
5295 CO->getTrueExpr());
5296 std::tie(FalseTy, FalseName) =
5297 shouldNotPrintDirectly(Context,
5298 CO->getFalseExpr()->getType(),
5299 CO->getFalseExpr());
5300
5301 if (TrueTy == FalseTy)
5302 return std::make_pair(TrueTy, TrueName);
5303 else if (TrueTy.isNull())
5304 return std::make_pair(FalseTy, FalseName);
5305 else if (FalseTy.isNull())
5306 return std::make_pair(TrueTy, TrueName);
5307 }
5308
5309 return std::make_pair(QualType(), StringRef());
5310}
5311
Richard Smith55ce3522012-06-25 20:30:08 +00005312bool
5313CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5314 const char *StartSpecifier,
5315 unsigned SpecifierLen,
5316 const Expr *E) {
5317 using namespace analyze_format_string;
5318 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005319 // Now type check the data expression that matches the
5320 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005321 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
5322 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00005323 if (!AT.isValid())
5324 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00005325
Jordan Rose598ec092012-12-05 18:44:40 +00005326 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00005327 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5328 ExprTy = TET->getUnderlyingExpr()->getType();
5329 }
5330
Seth Cantrellb4802962015-03-04 03:12:10 +00005331 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5332
5333 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00005334 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005335 }
Jordan Rose98709982012-06-04 22:48:57 +00005336
Jordan Rose22b74712012-09-05 22:56:19 +00005337 // Look through argument promotions for our error message's reported type.
5338 // This includes the integral and floating promotions, but excludes array
5339 // and function pointer decay; seeing that an argument intended to be a
5340 // string has type 'char [6]' is probably more confusing than 'char *'.
5341 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5342 if (ICE->getCastKind() == CK_IntegralCast ||
5343 ICE->getCastKind() == CK_FloatingCast) {
5344 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00005345 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00005346
5347 // Check if we didn't match because of an implicit cast from a 'char'
5348 // or 'short' to an 'int'. This is done because printf is a varargs
5349 // function.
5350 if (ICE->getType() == S.Context.IntTy ||
5351 ICE->getType() == S.Context.UnsignedIntTy) {
5352 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00005353 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00005354 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00005355 }
Jordan Rose98709982012-06-04 22:48:57 +00005356 }
Jordan Rose598ec092012-12-05 18:44:40 +00005357 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5358 // Special case for 'a', which has type 'int' in C.
5359 // Note, however, that we do /not/ want to treat multibyte constants like
5360 // 'MooV' as characters! This form is deprecated but still exists.
5361 if (ExprTy == S.Context.IntTy)
5362 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5363 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00005364 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005365
Jordan Rosebc53ed12014-05-31 04:12:14 +00005366 // Look through enums to their underlying type.
5367 bool IsEnum = false;
5368 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5369 ExprTy = EnumTy->getDecl()->getIntegerType();
5370 IsEnum = true;
5371 }
5372
Jordan Rose0e5badd2012-12-05 18:44:49 +00005373 // %C in an Objective-C context prints a unichar, not a wchar_t.
5374 // If the argument is an integer of some kind, believe the %C and suggest
5375 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00005376 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00005377 if (ObjCContext &&
5378 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5379 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5380 !ExprTy->isCharType()) {
5381 // 'unichar' is defined as a typedef of unsigned short, but we should
5382 // prefer using the typedef if it is visible.
5383 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00005384
5385 // While we are here, check if the value is an IntegerLiteral that happens
5386 // to be within the valid range.
5387 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5388 const llvm::APInt &V = IL->getValue();
5389 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5390 return true;
5391 }
5392
Jordan Rose0e5badd2012-12-05 18:44:49 +00005393 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5394 Sema::LookupOrdinaryName);
5395 if (S.LookupName(Result, S.getCurScope())) {
5396 NamedDecl *ND = Result.getFoundDecl();
5397 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5398 if (TD->getUnderlyingType() == IntendedTy)
5399 IntendedTy = S.Context.getTypedefType(TD);
5400 }
5401 }
5402 }
5403
5404 // Special-case some of Darwin's platform-independence types by suggesting
5405 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005406 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00005407 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005408 QualType CastTy;
5409 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5410 if (!CastTy.isNull()) {
5411 IntendedTy = CastTy;
5412 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00005413 }
5414 }
5415
Jordan Rose22b74712012-09-05 22:56:19 +00005416 // We may be able to offer a FixItHint if it is a supported type.
5417 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00005418 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00005419 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005420
Jordan Rose22b74712012-09-05 22:56:19 +00005421 if (success) {
5422 // Get the fix string from the fixed format specifier
5423 SmallString<16> buf;
5424 llvm::raw_svector_ostream os(buf);
5425 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005426
Jordan Roseaee34382012-09-05 22:56:26 +00005427 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5428
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005429 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00005430 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5431 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5432 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5433 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00005434 // In this case, the specifier is wrong and should be changed to match
5435 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00005436 EmitFormatDiagnostic(S.PDiag(diag)
5437 << AT.getRepresentativeTypeName(S.Context)
5438 << IntendedTy << IsEnum << E->getSourceRange(),
5439 E->getLocStart(),
5440 /*IsStringLocation*/ false, SpecRange,
5441 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00005442 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00005443 // The canonical type for formatting this value is different from the
5444 // actual type of the expression. (This occurs, for example, with Darwin's
5445 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
5446 // should be printed as 'long' for 64-bit compatibility.)
5447 // Rather than emitting a normal format/argument mismatch, we want to
5448 // add a cast to the recommended type (and correct the format string
5449 // if necessary).
5450 SmallString<16> CastBuf;
5451 llvm::raw_svector_ostream CastFix(CastBuf);
5452 CastFix << "(";
5453 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
5454 CastFix << ")";
5455
5456 SmallVector<FixItHint,4> Hints;
5457 if (!AT.matchesType(S.Context, IntendedTy))
5458 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
5459
5460 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
5461 // If there's already a cast present, just replace it.
5462 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
5463 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
5464
5465 } else if (!requiresParensToAddCast(E)) {
5466 // If the expression has high enough precedence,
5467 // just write the C-style cast.
5468 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5469 CastFix.str()));
5470 } else {
5471 // Otherwise, add parens around the expression as well as the cast.
5472 CastFix << "(";
5473 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5474 CastFix.str()));
5475
Alp Tokerb6cc5922014-05-03 03:45:55 +00005476 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00005477 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
5478 }
5479
Jordan Rose0e5badd2012-12-05 18:44:49 +00005480 if (ShouldNotPrintDirectly) {
5481 // The expression has a type that should not be printed directly.
5482 // We extract the name from the typedef because we don't want to show
5483 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005484 StringRef Name;
5485 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
5486 Name = TypedefTy->getDecl()->getName();
5487 else
5488 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00005489 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00005490 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00005491 << E->getSourceRange(),
5492 E->getLocStart(), /*IsStringLocation=*/false,
5493 SpecRange, Hints);
5494 } else {
5495 // In this case, the expression could be printed using a different
5496 // specifier, but we've decided that the specifier is probably correct
5497 // and we should cast instead. Just use the normal warning message.
5498 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00005499 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5500 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00005501 << E->getSourceRange(),
5502 E->getLocStart(), /*IsStringLocation*/false,
5503 SpecRange, Hints);
5504 }
Jordan Roseaee34382012-09-05 22:56:26 +00005505 }
Jordan Rose22b74712012-09-05 22:56:19 +00005506 } else {
5507 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
5508 SpecifierLen);
5509 // Since the warning for passing non-POD types to variadic functions
5510 // was deferred until now, we emit a warning for non-POD
5511 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00005512 switch (S.isValidVarArgType(ExprTy)) {
5513 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00005514 case Sema::VAK_ValidInCXX11: {
5515 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5516 if (match == analyze_printf::ArgType::NoMatchPedantic) {
5517 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5518 }
Richard Smithd7293d72013-08-05 18:49:43 +00005519
Seth Cantrellb4802962015-03-04 03:12:10 +00005520 EmitFormatDiagnostic(
5521 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
5522 << IsEnum << CSR << E->getSourceRange(),
5523 E->getLocStart(), /*IsStringLocation*/ false, CSR);
5524 break;
5525 }
Richard Smithd7293d72013-08-05 18:49:43 +00005526 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00005527 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00005528 EmitFormatDiagnostic(
5529 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005530 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00005531 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00005532 << CallType
5533 << AT.getRepresentativeTypeName(S.Context)
5534 << CSR
5535 << E->getSourceRange(),
5536 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00005537 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00005538 break;
5539
5540 case Sema::VAK_Invalid:
5541 if (ExprTy->isObjCObjectType())
5542 EmitFormatDiagnostic(
5543 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
5544 << S.getLangOpts().CPlusPlus11
5545 << ExprTy
5546 << CallType
5547 << AT.getRepresentativeTypeName(S.Context)
5548 << CSR
5549 << E->getSourceRange(),
5550 E->getLocStart(), /*IsStringLocation*/false, CSR);
5551 else
5552 // FIXME: If this is an initializer list, suggest removing the braces
5553 // or inserting a cast to the target type.
5554 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
5555 << isa<InitListExpr>(E) << ExprTy << CallType
5556 << AT.getRepresentativeTypeName(S.Context)
5557 << E->getSourceRange();
5558 break;
5559 }
5560
5561 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
5562 "format string specifier index out of range");
5563 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005564 }
5565
Ted Kremenekab278de2010-01-28 23:39:18 +00005566 return true;
5567}
5568
Ted Kremenek02087932010-07-16 02:11:22 +00005569//===--- CHECK: Scanf format string checking ------------------------------===//
5570
5571namespace {
5572class CheckScanfHandler : public CheckFormatHandler {
5573public:
Stephen Hines0535fec2016-09-14 20:05:20 +00005574 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Ted Kremenek02087932010-07-16 02:11:22 +00005575 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005576 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005577 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005578 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005579 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005580 llvm::SmallBitVector &CheckedVarArgs,
5581 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00005582 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
5583 numDataArgs, beg, hasVAListArg,
5584 Args, formatIdx, inFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005585 CheckedVarArgs, UncoveredArg)
Jordan Rose3e0ec582012-07-19 18:10:23 +00005586 {}
Ted Kremenek02087932010-07-16 02:11:22 +00005587
5588 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
5589 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005590 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00005591
5592 bool HandleInvalidScanfConversionSpecifier(
5593 const analyze_scanf::ScanfSpecifier &FS,
5594 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005595 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005596
Craig Toppere14c0f82014-03-12 04:55:44 +00005597 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00005598};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005599} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005600
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005601void CheckScanfHandler::HandleIncompleteScanList(const char *start,
5602 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005603 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
5604 getLocationOfByte(end), /*IsStringLocation*/true,
5605 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005606}
5607
Ted Kremenekce815422010-07-19 21:25:57 +00005608bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
5609 const analyze_scanf::ScanfSpecifier &FS,
5610 const char *startSpecifier,
5611 unsigned specifierLen) {
5612
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005613 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005614 FS.getConversionSpecifier();
5615
5616 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5617 getLocationOfByte(CS.getStart()),
5618 startSpecifier, specifierLen,
5619 CS.getStart(), CS.getLength());
5620}
5621
Ted Kremenek02087932010-07-16 02:11:22 +00005622bool CheckScanfHandler::HandleScanfSpecifier(
5623 const analyze_scanf::ScanfSpecifier &FS,
5624 const char *startSpecifier,
5625 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00005626 using namespace analyze_scanf;
5627 using namespace analyze_format_string;
5628
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005629 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005630
Ted Kremenek6cd69422010-07-19 22:01:06 +00005631 // Handle case where '%' and '*' don't consume an argument. These shouldn't
5632 // be used to decide if we are using positional arguments consistently.
5633 if (FS.consumesDataArgument()) {
5634 if (atFirstArg) {
5635 atFirstArg = false;
5636 usesPositionalArgs = FS.usesPositionalArg();
5637 }
5638 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005639 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5640 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005641 return false;
5642 }
Ted Kremenek02087932010-07-16 02:11:22 +00005643 }
5644
5645 // Check if the field with is non-zero.
5646 const OptionalAmount &Amt = FS.getFieldWidth();
5647 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
5648 if (Amt.getConstantAmount() == 0) {
5649 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
5650 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00005651 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
5652 getLocationOfByte(Amt.getStart()),
5653 /*IsStringLocation*/true, R,
5654 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00005655 }
5656 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005657
Ted Kremenek02087932010-07-16 02:11:22 +00005658 if (!FS.consumesDataArgument()) {
5659 // FIXME: Technically specifying a precision or field width here
5660 // makes no sense. Worth issuing a warning at some point.
5661 return true;
5662 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005663
Ted Kremenek02087932010-07-16 02:11:22 +00005664 // Consume the argument.
5665 unsigned argIndex = FS.getArgIndex();
5666 if (argIndex < NumDataArgs) {
5667 // The check to see if the argIndex is valid will come later.
5668 // We set the bit here because we may exit early from this
5669 // function if we encounter some other error.
5670 CoveredArgs.set(argIndex);
5671 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005672
Ted Kremenek4407ea42010-07-20 20:04:47 +00005673 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005674 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005675 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5676 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005677 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005678 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005679 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005680 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5681 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005682
Jordan Rose92303592012-09-08 04:00:03 +00005683 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5684 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5685
Ted Kremenek02087932010-07-16 02:11:22 +00005686 // The remaining checks depend on the data arguments.
5687 if (HasVAListArg)
5688 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005689
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005690 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00005691 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00005692
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005693 // Check that the argument type matches the format specifier.
5694 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005695 if (!Ex)
5696 return true;
5697
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00005698 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00005699
5700 if (!AT.isValid()) {
5701 return true;
5702 }
5703
Seth Cantrellb4802962015-03-04 03:12:10 +00005704 analyze_format_string::ArgType::MatchKind match =
5705 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00005706 if (match == analyze_format_string::ArgType::Match) {
5707 return true;
5708 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005709
Seth Cantrell79340072015-03-04 05:58:08 +00005710 ScanfSpecifier fixedFS = FS;
5711 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
5712 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005713
Seth Cantrell79340072015-03-04 05:58:08 +00005714 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5715 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5716 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5717 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005718
Seth Cantrell79340072015-03-04 05:58:08 +00005719 if (success) {
5720 // Get the fix string from the fixed format specifier.
5721 SmallString<128> buf;
5722 llvm::raw_svector_ostream os(buf);
5723 fixedFS.toString(os);
5724
5725 EmitFormatDiagnostic(
5726 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
5727 << Ex->getType() << false << Ex->getSourceRange(),
5728 Ex->getLocStart(),
5729 /*IsStringLocation*/ false,
5730 getSpecifierRange(startSpecifier, specifierLen),
5731 FixItHint::CreateReplacement(
5732 getSpecifierRange(startSpecifier, specifierLen), os.str()));
5733 } else {
5734 EmitFormatDiagnostic(S.PDiag(diag)
5735 << AT.getRepresentativeTypeName(S.Context)
5736 << Ex->getType() << false << Ex->getSourceRange(),
5737 Ex->getLocStart(),
5738 /*IsStringLocation*/ false,
5739 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005740 }
5741
Ted Kremenek02087932010-07-16 02:11:22 +00005742 return true;
5743}
5744
Stephen Hines0535fec2016-09-14 20:05:20 +00005745static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005746 const Expr *OrigFormatExpr,
5747 ArrayRef<const Expr *> Args,
5748 bool HasVAListArg, unsigned format_idx,
5749 unsigned firstDataArg,
5750 Sema::FormatStringType Type,
5751 bool inFunctionCall,
5752 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005753 llvm::SmallBitVector &CheckedVarArgs,
5754 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00005755 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00005756 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005757 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005758 S, inFunctionCall, Args[format_idx],
5759 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005760 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005761 return;
5762 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005763
Ted Kremenekab278de2010-01-28 23:39:18 +00005764 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005765 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00005766 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005767 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005768 const ConstantArrayType *T =
5769 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005770 assert(T && "String literal not of constant array type!");
5771 size_t TypeSize = T->getSize().getZExtValue();
5772 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005773 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005774
5775 // Emit a warning if the string literal is truncated and does not contain an
5776 // embedded null character.
5777 if (TypeSize <= StrRef.size() &&
5778 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
5779 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005780 S, inFunctionCall, Args[format_idx],
5781 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005782 FExpr->getLocStart(),
5783 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
5784 return;
5785 }
5786
Ted Kremenekab278de2010-01-28 23:39:18 +00005787 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00005788 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005789 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005790 S, inFunctionCall, Args[format_idx],
5791 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005792 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005793 return;
5794 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005795
5796 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
5797 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) {
5798 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
5799 numDataArgs, (Type == Sema::FST_NSString ||
5800 Type == Sema::FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005801 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005802 inFunctionCall, CallType, CheckedVarArgs,
5803 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005804
Hans Wennborg23926bd2011-12-15 10:25:47 +00005805 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005806 S.getLangOpts(),
5807 S.Context.getTargetInfo(),
5808 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00005809 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005810 } else if (Type == Sema::FST_Scanf) {
5811 CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005812 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005813 inFunctionCall, CallType, CheckedVarArgs,
5814 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005815
Hans Wennborg23926bd2011-12-15 10:25:47 +00005816 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005817 S.getLangOpts(),
5818 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00005819 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005820 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00005821}
5822
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00005823bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
5824 // Str - The format string. NOTE: this is NOT null-terminated!
5825 StringRef StrRef = FExpr->getString();
5826 const char *Str = StrRef.data();
5827 // Account for cases where the string literal is truncated in a declaration.
5828 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
5829 assert(T && "String literal not of constant array type!");
5830 size_t TypeSize = T->getSize().getZExtValue();
5831 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5832 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
5833 getLangOpts(),
5834 Context.getTargetInfo());
5835}
5836
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005837//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
5838
5839// Returns the related absolute value function that is larger, of 0 if one
5840// does not exist.
5841static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
5842 switch (AbsFunction) {
5843 default:
5844 return 0;
5845
5846 case Builtin::BI__builtin_abs:
5847 return Builtin::BI__builtin_labs;
5848 case Builtin::BI__builtin_labs:
5849 return Builtin::BI__builtin_llabs;
5850 case Builtin::BI__builtin_llabs:
5851 return 0;
5852
5853 case Builtin::BI__builtin_fabsf:
5854 return Builtin::BI__builtin_fabs;
5855 case Builtin::BI__builtin_fabs:
5856 return Builtin::BI__builtin_fabsl;
5857 case Builtin::BI__builtin_fabsl:
5858 return 0;
5859
5860 case Builtin::BI__builtin_cabsf:
5861 return Builtin::BI__builtin_cabs;
5862 case Builtin::BI__builtin_cabs:
5863 return Builtin::BI__builtin_cabsl;
5864 case Builtin::BI__builtin_cabsl:
5865 return 0;
5866
5867 case Builtin::BIabs:
5868 return Builtin::BIlabs;
5869 case Builtin::BIlabs:
5870 return Builtin::BIllabs;
5871 case Builtin::BIllabs:
5872 return 0;
5873
5874 case Builtin::BIfabsf:
5875 return Builtin::BIfabs;
5876 case Builtin::BIfabs:
5877 return Builtin::BIfabsl;
5878 case Builtin::BIfabsl:
5879 return 0;
5880
5881 case Builtin::BIcabsf:
5882 return Builtin::BIcabs;
5883 case Builtin::BIcabs:
5884 return Builtin::BIcabsl;
5885 case Builtin::BIcabsl:
5886 return 0;
5887 }
5888}
5889
5890// Returns the argument type of the absolute value function.
5891static QualType getAbsoluteValueArgumentType(ASTContext &Context,
5892 unsigned AbsType) {
5893 if (AbsType == 0)
5894 return QualType();
5895
5896 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
5897 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
5898 if (Error != ASTContext::GE_None)
5899 return QualType();
5900
5901 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
5902 if (!FT)
5903 return QualType();
5904
5905 if (FT->getNumParams() != 1)
5906 return QualType();
5907
5908 return FT->getParamType(0);
5909}
5910
5911// Returns the best absolute value function, or zero, based on type and
5912// current absolute value function.
5913static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
5914 unsigned AbsFunctionKind) {
5915 unsigned BestKind = 0;
5916 uint64_t ArgSize = Context.getTypeSize(ArgType);
5917 for (unsigned Kind = AbsFunctionKind; Kind != 0;
5918 Kind = getLargerAbsoluteValueFunction(Kind)) {
5919 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
5920 if (Context.getTypeSize(ParamType) >= ArgSize) {
5921 if (BestKind == 0)
5922 BestKind = Kind;
5923 else if (Context.hasSameType(ParamType, ArgType)) {
5924 BestKind = Kind;
5925 break;
5926 }
5927 }
5928 }
5929 return BestKind;
5930}
5931
5932enum AbsoluteValueKind {
5933 AVK_Integer,
5934 AVK_Floating,
5935 AVK_Complex
5936};
5937
5938static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
5939 if (T->isIntegralOrEnumerationType())
5940 return AVK_Integer;
5941 if (T->isRealFloatingType())
5942 return AVK_Floating;
5943 if (T->isAnyComplexType())
5944 return AVK_Complex;
5945
5946 llvm_unreachable("Type not integer, floating, or complex");
5947}
5948
5949// Changes the absolute value function to a different type. Preserves whether
5950// the function is a builtin.
5951static unsigned changeAbsFunction(unsigned AbsKind,
5952 AbsoluteValueKind ValueKind) {
5953 switch (ValueKind) {
5954 case AVK_Integer:
5955 switch (AbsKind) {
5956 default:
5957 return 0;
5958 case Builtin::BI__builtin_fabsf:
5959 case Builtin::BI__builtin_fabs:
5960 case Builtin::BI__builtin_fabsl:
5961 case Builtin::BI__builtin_cabsf:
5962 case Builtin::BI__builtin_cabs:
5963 case Builtin::BI__builtin_cabsl:
5964 return Builtin::BI__builtin_abs;
5965 case Builtin::BIfabsf:
5966 case Builtin::BIfabs:
5967 case Builtin::BIfabsl:
5968 case Builtin::BIcabsf:
5969 case Builtin::BIcabs:
5970 case Builtin::BIcabsl:
5971 return Builtin::BIabs;
5972 }
5973 case AVK_Floating:
5974 switch (AbsKind) {
5975 default:
5976 return 0;
5977 case Builtin::BI__builtin_abs:
5978 case Builtin::BI__builtin_labs:
5979 case Builtin::BI__builtin_llabs:
5980 case Builtin::BI__builtin_cabsf:
5981 case Builtin::BI__builtin_cabs:
5982 case Builtin::BI__builtin_cabsl:
5983 return Builtin::BI__builtin_fabsf;
5984 case Builtin::BIabs:
5985 case Builtin::BIlabs:
5986 case Builtin::BIllabs:
5987 case Builtin::BIcabsf:
5988 case Builtin::BIcabs:
5989 case Builtin::BIcabsl:
5990 return Builtin::BIfabsf;
5991 }
5992 case AVK_Complex:
5993 switch (AbsKind) {
5994 default:
5995 return 0;
5996 case Builtin::BI__builtin_abs:
5997 case Builtin::BI__builtin_labs:
5998 case Builtin::BI__builtin_llabs:
5999 case Builtin::BI__builtin_fabsf:
6000 case Builtin::BI__builtin_fabs:
6001 case Builtin::BI__builtin_fabsl:
6002 return Builtin::BI__builtin_cabsf;
6003 case Builtin::BIabs:
6004 case Builtin::BIlabs:
6005 case Builtin::BIllabs:
6006 case Builtin::BIfabsf:
6007 case Builtin::BIfabs:
6008 case Builtin::BIfabsl:
6009 return Builtin::BIcabsf;
6010 }
6011 }
6012 llvm_unreachable("Unable to convert function");
6013}
6014
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006015static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006016 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6017 if (!FnInfo)
6018 return 0;
6019
6020 switch (FDecl->getBuiltinID()) {
6021 default:
6022 return 0;
6023 case Builtin::BI__builtin_abs:
6024 case Builtin::BI__builtin_fabs:
6025 case Builtin::BI__builtin_fabsf:
6026 case Builtin::BI__builtin_fabsl:
6027 case Builtin::BI__builtin_labs:
6028 case Builtin::BI__builtin_llabs:
6029 case Builtin::BI__builtin_cabs:
6030 case Builtin::BI__builtin_cabsf:
6031 case Builtin::BI__builtin_cabsl:
6032 case Builtin::BIabs:
6033 case Builtin::BIlabs:
6034 case Builtin::BIllabs:
6035 case Builtin::BIfabs:
6036 case Builtin::BIfabsf:
6037 case Builtin::BIfabsl:
6038 case Builtin::BIcabs:
6039 case Builtin::BIcabsf:
6040 case Builtin::BIcabsl:
6041 return FDecl->getBuiltinID();
6042 }
6043 llvm_unreachable("Unknown Builtin type");
6044}
6045
6046// If the replacement is valid, emit a note with replacement function.
6047// Additionally, suggest including the proper header if not already included.
6048static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00006049 unsigned AbsKind, QualType ArgType) {
6050 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006051 const char *HeaderName = nullptr;
6052 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006053 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6054 FunctionName = "std::abs";
6055 if (ArgType->isIntegralOrEnumerationType()) {
6056 HeaderName = "cstdlib";
6057 } else if (ArgType->isRealFloatingType()) {
6058 HeaderName = "cmath";
6059 } else {
6060 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006061 }
Richard Trieubeffb832014-04-15 23:47:53 +00006062
6063 // Lookup all std::abs
6064 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00006065 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00006066 R.suppressDiagnostics();
6067 S.LookupQualifiedName(R, Std);
6068
6069 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006070 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006071 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6072 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6073 } else {
6074 FDecl = dyn_cast<FunctionDecl>(I);
6075 }
6076 if (!FDecl)
6077 continue;
6078
6079 // Found std::abs(), check that they are the right ones.
6080 if (FDecl->getNumParams() != 1)
6081 continue;
6082
6083 // Check that the parameter type can handle the argument.
6084 QualType ParamType = FDecl->getParamDecl(0)->getType();
6085 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6086 S.Context.getTypeSize(ArgType) <=
6087 S.Context.getTypeSize(ParamType)) {
6088 // Found a function, don't need the header hint.
6089 EmitHeaderHint = false;
6090 break;
6091 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006092 }
Richard Trieubeffb832014-04-15 23:47:53 +00006093 }
6094 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00006095 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00006096 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6097
6098 if (HeaderName) {
6099 DeclarationName DN(&S.Context.Idents.get(FunctionName));
6100 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6101 R.suppressDiagnostics();
6102 S.LookupName(R, S.getCurScope());
6103
6104 if (R.isSingleResult()) {
6105 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6106 if (FD && FD->getBuiltinID() == AbsKind) {
6107 EmitHeaderHint = false;
6108 } else {
6109 return;
6110 }
6111 } else if (!R.empty()) {
6112 return;
6113 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006114 }
6115 }
6116
6117 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00006118 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006119
Richard Trieubeffb832014-04-15 23:47:53 +00006120 if (!HeaderName)
6121 return;
6122
6123 if (!EmitHeaderHint)
6124 return;
6125
Alp Toker5d96e0a2014-07-11 20:53:51 +00006126 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6127 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00006128}
6129
6130static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
6131 if (!FDecl)
6132 return false;
6133
6134 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
6135 return false;
6136
6137 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
6138
6139 while (ND && ND->isInlineNamespace()) {
6140 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006141 }
Richard Trieubeffb832014-04-15 23:47:53 +00006142
6143 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
6144 return false;
6145
6146 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
6147 return false;
6148
6149 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006150}
6151
6152// Warn when using the wrong abs() function.
6153void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
6154 const FunctionDecl *FDecl,
6155 IdentifierInfo *FnInfo) {
6156 if (Call->getNumArgs() != 1)
6157 return;
6158
6159 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00006160 bool IsStdAbs = IsFunctionStdAbs(FDecl);
6161 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006162 return;
6163
6164 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6165 QualType ParamType = Call->getArg(0)->getType();
6166
Alp Toker5d96e0a2014-07-11 20:53:51 +00006167 // Unsigned types cannot be negative. Suggest removing the absolute value
6168 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006169 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00006170 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00006171 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006172 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6173 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00006174 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006175 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6176 return;
6177 }
6178
David Majnemer7f77eb92015-11-15 03:04:34 +00006179 // Taking the absolute value of a pointer is very suspicious, they probably
6180 // wanted to index into an array, dereference a pointer, call a function, etc.
6181 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6182 unsigned DiagType = 0;
6183 if (ArgType->isFunctionType())
6184 DiagType = 1;
6185 else if (ArgType->isArrayType())
6186 DiagType = 2;
6187
6188 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6189 return;
6190 }
6191
Richard Trieubeffb832014-04-15 23:47:53 +00006192 // std::abs has overloads which prevent most of the absolute value problems
6193 // from occurring.
6194 if (IsStdAbs)
6195 return;
6196
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006197 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6198 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6199
6200 // The argument and parameter are the same kind. Check if they are the right
6201 // size.
6202 if (ArgValueKind == ParamValueKind) {
6203 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6204 return;
6205
6206 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6207 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6208 << FDecl << ArgType << ParamType;
6209
6210 if (NewAbsKind == 0)
6211 return;
6212
6213 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006214 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006215 return;
6216 }
6217
6218 // ArgValueKind != ParamValueKind
6219 // The wrong type of absolute value function was used. Attempt to find the
6220 // proper one.
6221 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6222 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6223 if (NewAbsKind == 0)
6224 return;
6225
6226 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6227 << FDecl << ParamValueKind << ArgValueKind;
6228
6229 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006230 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006231}
6232
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006233//===--- CHECK: Standard memory functions ---------------------------------===//
6234
Nico Weber0e6daef2013-12-26 23:38:39 +00006235/// \brief Takes the expression passed to the size_t parameter of functions
6236/// such as memcmp, strncat, etc and warns if it's a comparison.
6237///
6238/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6239static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6240 IdentifierInfo *FnName,
6241 SourceLocation FnLoc,
6242 SourceLocation RParenLoc) {
6243 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6244 if (!Size)
6245 return false;
6246
6247 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6248 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6249 return false;
6250
Nico Weber0e6daef2013-12-26 23:38:39 +00006251 SourceRange SizeRange = Size->getSourceRange();
6252 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6253 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00006254 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006255 << FnName << FixItHint::CreateInsertion(
6256 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00006257 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00006258 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00006259 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00006260 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6261 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00006262
6263 return true;
6264}
6265
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006266/// \brief Determine whether the given type is or contains a dynamic class type
6267/// (e.g., whether it has a vtable).
6268static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6269 bool &IsContained) {
6270 // Look through array types while ignoring qualifiers.
6271 const Type *Ty = T->getBaseElementTypeUnsafe();
6272 IsContained = false;
6273
6274 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6275 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00006276 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006277 return nullptr;
6278
6279 if (RD->isDynamicClass())
6280 return RD;
6281
6282 // Check all the fields. If any bases were dynamic, the class is dynamic.
6283 // It's impossible for a class to transitively contain itself by value, so
6284 // infinite recursion is impossible.
6285 for (auto *FD : RD->fields()) {
6286 bool SubContained;
6287 if (const CXXRecordDecl *ContainedRD =
6288 getContainedDynamicClass(FD->getType(), SubContained)) {
6289 IsContained = true;
6290 return ContainedRD;
6291 }
6292 }
6293
6294 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00006295}
6296
Chandler Carruth889ed862011-06-21 23:04:20 +00006297/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006298/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00006299static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00006300 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006301 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6302 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6303 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006304
Craig Topperc3ec1492014-05-26 06:22:03 +00006305 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006306}
6307
Chandler Carruth889ed862011-06-21 23:04:20 +00006308/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00006309static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006310 if (const UnaryExprOrTypeTraitExpr *SizeOf =
6311 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6312 if (SizeOf->getKind() == clang::UETT_SizeOf)
6313 return SizeOf->getTypeOfArgument();
6314
6315 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00006316}
6317
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006318/// \brief Check for dangerous or invalid arguments to memset().
6319///
Chandler Carruthac687262011-06-03 06:23:57 +00006320/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006321/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6322/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006323///
6324/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006325void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00006326 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006327 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00006328 assert(BId != 0);
6329
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006330 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00006331 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006332 unsigned ExpectedNumArgs =
6333 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00006334 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006335 return;
6336
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006337 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00006338 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006339 unsigned LenArg =
6340 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00006341 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006342
Nico Weber0e6daef2013-12-26 23:38:39 +00006343 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6344 Call->getLocStart(), Call->getRParenLoc()))
6345 return;
6346
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006347 // We have special checking when the length is a sizeof expression.
6348 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6349 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6350 llvm::FoldingSetNodeID SizeOfArgID;
6351
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00006352 // Although widely used, 'bzero' is not a standard function. Be more strict
6353 // with the argument types before allowing diagnostics and only allow the
6354 // form bzero(ptr, sizeof(...)).
6355 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6356 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
6357 return;
6358
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006359 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6360 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006361 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006362
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006363 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00006364 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006365 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00006366 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00006367
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006368 // Never warn about void type pointers. This can be used to suppress
6369 // false positives.
6370 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006371 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006372
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006373 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6374 // actually comparing the expressions for equality. Because computing the
6375 // expression IDs can be expensive, we only do this if the diagnostic is
6376 // enabled.
6377 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006378 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6379 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006380 // We only compute IDs for expressions if the warning is enabled, and
6381 // cache the sizeof arg's ID.
6382 if (SizeOfArgID == llvm::FoldingSetNodeID())
6383 SizeOfArg->Profile(SizeOfArgID, Context, true);
6384 llvm::FoldingSetNodeID DestID;
6385 Dest->Profile(DestID, Context, true);
6386 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00006387 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6388 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006389 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00006390 StringRef ReadableName = FnName->getName();
6391
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006392 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00006393 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006394 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00006395 if (!PointeeTy->isIncompleteType() &&
6396 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006397 ActionIdx = 2; // If the pointee's size is sizeof(char),
6398 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00006399
6400 // If the function is defined as a builtin macro, do not show macro
6401 // expansion.
6402 SourceLocation SL = SizeOfArg->getExprLoc();
6403 SourceRange DSR = Dest->getSourceRange();
6404 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006405 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00006406
6407 if (SM.isMacroArgExpansion(SL)) {
6408 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
6409 SL = SM.getSpellingLoc(SL);
6410 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
6411 SM.getSpellingLoc(DSR.getEnd()));
6412 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
6413 SM.getSpellingLoc(SSR.getEnd()));
6414 }
6415
Anna Zaksd08d9152012-05-30 23:14:52 +00006416 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006417 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00006418 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00006419 << PointeeTy
6420 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00006421 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00006422 << SSR);
6423 DiagRuntimeBehavior(SL, SizeOfArg,
6424 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
6425 << ActionIdx
6426 << SSR);
6427
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006428 break;
6429 }
6430 }
6431
6432 // Also check for cases where the sizeof argument is the exact same
6433 // type as the memory argument, and where it points to a user-defined
6434 // record type.
6435 if (SizeOfArgTy != QualType()) {
6436 if (PointeeTy->isRecordType() &&
6437 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
6438 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
6439 PDiag(diag::warn_sizeof_pointer_type_memaccess)
6440 << FnName << SizeOfArgTy << ArgIdx
6441 << PointeeTy << Dest->getSourceRange()
6442 << LenExpr->getSourceRange());
6443 break;
6444 }
Nico Weberc5e73862011-06-14 16:14:58 +00006445 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00006446 } else if (DestTy->isArrayType()) {
6447 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00006448 }
Nico Weberc5e73862011-06-14 16:14:58 +00006449
Nico Weberc44b35e2015-03-21 17:37:46 +00006450 if (PointeeTy == QualType())
6451 continue;
Anna Zaks22122702012-01-17 00:37:07 +00006452
Nico Weberc44b35e2015-03-21 17:37:46 +00006453 // Always complain about dynamic classes.
6454 bool IsContained;
6455 if (const CXXRecordDecl *ContainedRD =
6456 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00006457
Nico Weberc44b35e2015-03-21 17:37:46 +00006458 unsigned OperationType = 0;
6459 // "overwritten" if we're warning about the destination for any call
6460 // but memcmp; otherwise a verb appropriate to the call.
6461 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
6462 if (BId == Builtin::BImemcpy)
6463 OperationType = 1;
6464 else if(BId == Builtin::BImemmove)
6465 OperationType = 2;
6466 else if (BId == Builtin::BImemcmp)
6467 OperationType = 3;
6468 }
6469
John McCall31168b02011-06-15 23:02:42 +00006470 DiagRuntimeBehavior(
6471 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00006472 PDiag(diag::warn_dyn_class_memaccess)
6473 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
6474 << FnName << IsContained << ContainedRD << OperationType
6475 << Call->getCallee()->getSourceRange());
6476 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
6477 BId != Builtin::BImemset)
6478 DiagRuntimeBehavior(
6479 Dest->getExprLoc(), Dest,
6480 PDiag(diag::warn_arc_object_memaccess)
6481 << ArgIdx << FnName << PointeeTy
6482 << Call->getCallee()->getSourceRange());
6483 else
6484 continue;
6485
6486 DiagRuntimeBehavior(
6487 Dest->getExprLoc(), Dest,
6488 PDiag(diag::note_bad_memaccess_silence)
6489 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
6490 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006491 }
6492}
6493
Ted Kremenek6865f772011-08-18 20:55:45 +00006494// A little helper routine: ignore addition and subtraction of integer literals.
6495// This intentionally does not ignore all integer constant expressions because
6496// we don't want to remove sizeof().
6497static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
6498 Ex = Ex->IgnoreParenCasts();
6499
6500 for (;;) {
6501 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
6502 if (!BO || !BO->isAdditiveOp())
6503 break;
6504
6505 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
6506 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
6507
6508 if (isa<IntegerLiteral>(RHS))
6509 Ex = LHS;
6510 else if (isa<IntegerLiteral>(LHS))
6511 Ex = RHS;
6512 else
6513 break;
6514 }
6515
6516 return Ex;
6517}
6518
Anna Zaks13b08572012-08-08 21:42:23 +00006519static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
6520 ASTContext &Context) {
6521 // Only handle constant-sized or VLAs, but not flexible members.
6522 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
6523 // Only issue the FIXIT for arrays of size > 1.
6524 if (CAT->getSize().getSExtValue() <= 1)
6525 return false;
6526 } else if (!Ty->isVariableArrayType()) {
6527 return false;
6528 }
6529 return true;
6530}
6531
Ted Kremenek6865f772011-08-18 20:55:45 +00006532// Warn if the user has made the 'size' argument to strlcpy or strlcat
6533// be the size of the source, instead of the destination.
6534void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
6535 IdentifierInfo *FnName) {
6536
6537 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00006538 unsigned NumArgs = Call->getNumArgs();
6539 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00006540 return;
6541
6542 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
6543 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00006544 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00006545
6546 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
6547 Call->getLocStart(), Call->getRParenLoc()))
6548 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00006549
6550 // Look for 'strlcpy(dst, x, sizeof(x))'
6551 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
6552 CompareWithSrc = Ex;
6553 else {
6554 // Look for 'strlcpy(dst, x, strlen(x))'
6555 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00006556 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
6557 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00006558 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
6559 }
6560 }
6561
6562 if (!CompareWithSrc)
6563 return;
6564
6565 // Determine if the argument to sizeof/strlen is equal to the source
6566 // argument. In principle there's all kinds of things you could do
6567 // here, for instance creating an == expression and evaluating it with
6568 // EvaluateAsBooleanCondition, but this uses a more direct technique:
6569 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
6570 if (!SrcArgDRE)
6571 return;
6572
6573 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
6574 if (!CompareWithSrcDRE ||
6575 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
6576 return;
6577
6578 const Expr *OriginalSizeArg = Call->getArg(2);
6579 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
6580 << OriginalSizeArg->getSourceRange() << FnName;
6581
6582 // Output a FIXIT hint if the destination is an array (rather than a
6583 // pointer to an array). This could be enhanced to handle some
6584 // pointers if we know the actual size, like if DstArg is 'array+2'
6585 // we could say 'sizeof(array)-2'.
6586 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00006587 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00006588 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00006589
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006590 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00006591 llvm::raw_svector_ostream OS(sizeString);
6592 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006593 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00006594 OS << ")";
6595
6596 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
6597 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
6598 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00006599}
6600
Anna Zaks314cd092012-02-01 19:08:57 +00006601/// Check if two expressions refer to the same declaration.
6602static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
6603 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
6604 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
6605 return D1->getDecl() == D2->getDecl();
6606 return false;
6607}
6608
6609static const Expr *getStrlenExprArg(const Expr *E) {
6610 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6611 const FunctionDecl *FD = CE->getDirectCallee();
6612 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00006613 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00006614 return CE->getArg(0)->IgnoreParenCasts();
6615 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006616 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00006617}
6618
6619// Warn on anti-patterns as the 'size' argument to strncat.
6620// The correct size argument should look like following:
6621// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
6622void Sema::CheckStrncatArguments(const CallExpr *CE,
6623 IdentifierInfo *FnName) {
6624 // Don't crash if the user has the wrong number of arguments.
6625 if (CE->getNumArgs() < 3)
6626 return;
6627 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
6628 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
6629 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
6630
Nico Weber0e6daef2013-12-26 23:38:39 +00006631 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
6632 CE->getRParenLoc()))
6633 return;
6634
Anna Zaks314cd092012-02-01 19:08:57 +00006635 // Identify common expressions, which are wrongly used as the size argument
6636 // to strncat and may lead to buffer overflows.
6637 unsigned PatternType = 0;
6638 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
6639 // - sizeof(dst)
6640 if (referToTheSameDecl(SizeOfArg, DstArg))
6641 PatternType = 1;
6642 // - sizeof(src)
6643 else if (referToTheSameDecl(SizeOfArg, SrcArg))
6644 PatternType = 2;
6645 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
6646 if (BE->getOpcode() == BO_Sub) {
6647 const Expr *L = BE->getLHS()->IgnoreParenCasts();
6648 const Expr *R = BE->getRHS()->IgnoreParenCasts();
6649 // - sizeof(dst) - strlen(dst)
6650 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
6651 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
6652 PatternType = 1;
6653 // - sizeof(src) - (anything)
6654 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
6655 PatternType = 2;
6656 }
6657 }
6658
6659 if (PatternType == 0)
6660 return;
6661
Anna Zaks5069aa32012-02-03 01:27:37 +00006662 // Generate the diagnostic.
6663 SourceLocation SL = LenArg->getLocStart();
6664 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006665 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00006666
6667 // If the function is defined as a builtin macro, do not show macro expansion.
6668 if (SM.isMacroArgExpansion(SL)) {
6669 SL = SM.getSpellingLoc(SL);
6670 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
6671 SM.getSpellingLoc(SR.getEnd()));
6672 }
6673
Anna Zaks13b08572012-08-08 21:42:23 +00006674 // Check if the destination is an array (rather than a pointer to an array).
6675 QualType DstTy = DstArg->getType();
6676 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
6677 Context);
6678 if (!isKnownSizeArray) {
6679 if (PatternType == 1)
6680 Diag(SL, diag::warn_strncat_wrong_size) << SR;
6681 else
6682 Diag(SL, diag::warn_strncat_src_size) << SR;
6683 return;
6684 }
6685
Anna Zaks314cd092012-02-01 19:08:57 +00006686 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00006687 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006688 else
Anna Zaks5069aa32012-02-03 01:27:37 +00006689 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006690
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006691 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00006692 llvm::raw_svector_ostream OS(sizeString);
6693 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006694 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006695 OS << ") - ";
6696 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006697 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006698 OS << ") - 1";
6699
Anna Zaks5069aa32012-02-03 01:27:37 +00006700 Diag(SL, diag::note_strncat_wrong_size)
6701 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00006702}
6703
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006704//===--- CHECK: Return Address of Stack Variable --------------------------===//
6705
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006706static const Expr *EvalVal(const Expr *E,
6707 SmallVectorImpl<const DeclRefExpr *> &refVars,
6708 const Decl *ParentDecl);
6709static const Expr *EvalAddr(const Expr *E,
6710 SmallVectorImpl<const DeclRefExpr *> &refVars,
6711 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006712
6713/// CheckReturnStackAddr - Check if a return statement returns the address
6714/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006715static void
6716CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
6717 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00006718
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006719 const Expr *stackE = nullptr;
6720 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006721
6722 // Perform checking for returned stack addresses, local blocks,
6723 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00006724 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006725 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006726 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00006727 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006728 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006729 }
6730
Craig Topperc3ec1492014-05-26 06:22:03 +00006731 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006732 return; // Nothing suspicious was found.
6733
Richard Trieu81b6c562016-08-05 23:24:47 +00006734 // Parameters are initalized in the calling scope, so taking the address
6735 // of a parameter reference doesn't need a warning.
6736 for (auto *DRE : refVars)
6737 if (isa<ParmVarDecl>(DRE->getDecl()))
6738 return;
6739
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006740 SourceLocation diagLoc;
6741 SourceRange diagRange;
6742 if (refVars.empty()) {
6743 diagLoc = stackE->getLocStart();
6744 diagRange = stackE->getSourceRange();
6745 } else {
6746 // We followed through a reference variable. 'stackE' contains the
6747 // problematic expression but we will warn at the return statement pointing
6748 // at the reference variable. We will later display the "trail" of
6749 // reference variables using notes.
6750 diagLoc = refVars[0]->getLocStart();
6751 diagRange = refVars[0]->getSourceRange();
6752 }
6753
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006754 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
6755 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00006756 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006757 << DR->getDecl()->getDeclName() << diagRange;
6758 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006759 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006760 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006761 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006762 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00006763 // If there is an LValue->RValue conversion, then the value of the
6764 // reference type is used, not the reference.
6765 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
6766 if (ICE->getCastKind() == CK_LValueToRValue) {
6767 return;
6768 }
6769 }
Craig Topperda7b27f2015-11-17 05:40:09 +00006770 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
6771 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006772 }
6773
6774 // Display the "trail" of reference variables that we followed until we
6775 // found the problematic expression using notes.
6776 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006777 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006778 // If this var binds to another reference var, show the range of the next
6779 // var, otherwise the var binds to the problematic expression, in which case
6780 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006781 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
6782 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006783 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
6784 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006785 }
6786}
6787
6788/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
6789/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006790/// to a location on the stack, a local block, an address of a label, or a
6791/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006792/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006793/// encounter a subexpression that (1) clearly does not lead to one of the
6794/// above problematic expressions (2) is something we cannot determine leads to
6795/// a problematic expression based on such local checking.
6796///
6797/// Both EvalAddr and EvalVal follow through reference variables to evaluate
6798/// the expression that they point to. Such variables are added to the
6799/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006800///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00006801/// EvalAddr processes expressions that are pointers that are used as
6802/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006803/// At the base case of the recursion is a check for the above problematic
6804/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006805///
6806/// This implementation handles:
6807///
6808/// * pointer-to-pointer casts
6809/// * implicit conversions from array references to pointers
6810/// * taking the address of fields
6811/// * arbitrary interplay between "&" and "*" operators
6812/// * pointer arithmetic from an address of a stack variable
6813/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006814static const Expr *EvalAddr(const Expr *E,
6815 SmallVectorImpl<const DeclRefExpr *> &refVars,
6816 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006817 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00006818 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006819
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006820 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00006821 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00006822 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006823 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00006824 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00006825
Peter Collingbourne91147592011-04-15 00:35:48 +00006826 E = E->IgnoreParens();
6827
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006828 // Our "symbolic interpreter" is just a dispatch off the currently
6829 // viewed AST node. We then recursively traverse the AST by calling
6830 // EvalAddr and EvalVal appropriately.
6831 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006832 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006833 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006834
Richard Smith40f08eb2014-01-30 22:05:38 +00006835 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00006836 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00006837 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00006838
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006839 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006840 // If this is a reference variable, follow through to the expression that
6841 // it points to.
6842 if (V->hasLocalStorage() &&
6843 V->getType()->isReferenceType() && V->hasInit()) {
6844 // Add the reference variable to the "trail".
6845 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006846 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006847 }
6848
Craig Topperc3ec1492014-05-26 06:22:03 +00006849 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006850 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006851
Chris Lattner934edb22007-12-28 05:31:15 +00006852 case Stmt::UnaryOperatorClass: {
6853 // The only unary operator that make sense to handle here
6854 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006855 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006856
John McCalle3027922010-08-25 11:45:40 +00006857 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006858 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006859 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006860 }
Mike Stump11289f42009-09-09 15:08:12 +00006861
Chris Lattner934edb22007-12-28 05:31:15 +00006862 case Stmt::BinaryOperatorClass: {
6863 // Handle pointer arithmetic. All other binary operators are not valid
6864 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006865 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00006866 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00006867
John McCalle3027922010-08-25 11:45:40 +00006868 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00006869 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006870
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006871 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00006872
6873 // Determine which argument is the real pointer base. It could be
6874 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006875 if (!Base->getType()->isPointerType())
6876 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00006877
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006878 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006879 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006880 }
Steve Naroff2752a172008-09-10 19:17:48 +00006881
Chris Lattner934edb22007-12-28 05:31:15 +00006882 // For conditional operators we need to see if either the LHS or RHS are
6883 // valid DeclRefExpr*s. If one of them is valid, we return it.
6884 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006885 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006886
Chris Lattner934edb22007-12-28 05:31:15 +00006887 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006888 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006889 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006890 // In C++, we can have a throw-expression, which has 'void' type.
6891 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006892 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006893 return LHS;
6894 }
Chris Lattner934edb22007-12-28 05:31:15 +00006895
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006896 // In C++, we can have a throw-expression, which has 'void' type.
6897 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00006898 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006899
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006900 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006901 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006902
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006903 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00006904 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006905 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00006906 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006907
6908 case Stmt::AddrLabelExprClass:
6909 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00006910
John McCall28fc7092011-11-10 05:35:25 +00006911 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006912 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6913 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00006914
Ted Kremenekc3b4c522008-08-07 00:49:01 +00006915 // For casts, we need to handle conversions from arrays to
6916 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00006917 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00006918 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00006919 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00006920 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00006921 case Stmt::CXXStaticCastExprClass:
6922 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00006923 case Stmt::CXXConstCastExprClass:
6924 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006925 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00006926 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00006927 case CK_LValueToRValue:
6928 case CK_NoOp:
6929 case CK_BaseToDerived:
6930 case CK_DerivedToBase:
6931 case CK_UncheckedDerivedToBase:
6932 case CK_Dynamic:
6933 case CK_CPointerToObjCPointerCast:
6934 case CK_BlockPointerToObjCPointerCast:
6935 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006936 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006937
6938 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006939 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006940
Richard Trieudadefde2014-07-02 04:39:38 +00006941 case CK_BitCast:
6942 if (SubExpr->getType()->isAnyPointerType() ||
6943 SubExpr->getType()->isBlockPointerType() ||
6944 SubExpr->getType()->isObjCQualifiedIdType())
6945 return EvalAddr(SubExpr, refVars, ParentDecl);
6946 else
6947 return nullptr;
6948
Eli Friedman8195ad72012-02-23 23:04:32 +00006949 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006950 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00006951 }
Chris Lattner934edb22007-12-28 05:31:15 +00006952 }
Mike Stump11289f42009-09-09 15:08:12 +00006953
Douglas Gregorfe314812011-06-21 17:03:29 +00006954 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006955 if (const Expr *Result =
6956 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6957 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00006958 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00006959 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006960
Chris Lattner934edb22007-12-28 05:31:15 +00006961 // Everything else: we simply don't reason about them.
6962 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006963 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00006964 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006965}
Mike Stump11289f42009-09-09 15:08:12 +00006966
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006967/// EvalVal - This function is complements EvalAddr in the mutual recursion.
6968/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006969static const Expr *EvalVal(const Expr *E,
6970 SmallVectorImpl<const DeclRefExpr *> &refVars,
6971 const Decl *ParentDecl) {
6972 do {
6973 // We should only be called for evaluating non-pointer expressions, or
6974 // expressions with a pointer type that are not used as references but
6975 // instead
6976 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00006977
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006978 // Our "symbolic interpreter" is just a dispatch off the currently
6979 // viewed AST node. We then recursively traverse the AST by calling
6980 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00006981
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006982 E = E->IgnoreParens();
6983 switch (E->getStmtClass()) {
6984 case Stmt::ImplicitCastExprClass: {
6985 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
6986 if (IE->getValueKind() == VK_LValue) {
6987 E = IE->getSubExpr();
6988 continue;
6989 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006990 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006991 }
Richard Smith40f08eb2014-01-30 22:05:38 +00006992
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006993 case Stmt::ExprWithCleanupsClass:
6994 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6995 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006996
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006997 case Stmt::DeclRefExprClass: {
6998 // When we hit a DeclRefExpr we are looking at code that refers to a
6999 // variable's name. If it's not a reference variable we check if it has
7000 // local storage within the function, and if so, return the expression.
7001 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7002
7003 // If we leave the immediate function, the lifetime isn't about to end.
7004 if (DR->refersToEnclosingVariableOrCapture())
7005 return nullptr;
7006
7007 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7008 // Check if it refers to itself, e.g. "int& i = i;".
7009 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007010 return DR;
7011
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007012 if (V->hasLocalStorage()) {
7013 if (!V->getType()->isReferenceType())
7014 return DR;
7015
7016 // Reference variable, follow through to the expression that
7017 // it points to.
7018 if (V->hasInit()) {
7019 // Add the reference variable to the "trail".
7020 refVars.push_back(DR);
7021 return EvalVal(V->getInit(), refVars, V);
7022 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007023 }
7024 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007025
7026 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007027 }
Mike Stump11289f42009-09-09 15:08:12 +00007028
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007029 case Stmt::UnaryOperatorClass: {
7030 // The only unary operator that make sense to handle here
7031 // is Deref. All others don't resolve to a "name." This includes
7032 // handling all sorts of rvalues passed to a unary operator.
7033 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007034
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007035 if (U->getOpcode() == UO_Deref)
7036 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007037
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007038 return nullptr;
7039 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007040
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007041 case Stmt::ArraySubscriptExprClass: {
7042 // Array subscripts are potential references to data on the stack. We
7043 // retrieve the DeclRefExpr* for the array variable if it indeed
7044 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00007045 const auto *ASE = cast<ArraySubscriptExpr>(E);
7046 if (ASE->isTypeDependent())
7047 return nullptr;
7048 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007049 }
Mike Stump11289f42009-09-09 15:08:12 +00007050
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007051 case Stmt::OMPArraySectionExprClass: {
7052 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7053 ParentDecl);
7054 }
Mike Stump11289f42009-09-09 15:08:12 +00007055
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007056 case Stmt::ConditionalOperatorClass: {
7057 // For conditional operators we need to see if either the LHS or RHS are
7058 // non-NULL Expr's. If one is non-NULL, we return it.
7059 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007060
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007061 // Handle the GNU extension for missing LHS.
7062 if (const Expr *LHSExpr = C->getLHS()) {
7063 // In C++, we can have a throw-expression, which has 'void' type.
7064 if (!LHSExpr->getType()->isVoidType())
7065 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7066 return LHS;
7067 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007068
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007069 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007070 if (C->getRHS()->getType()->isVoidType())
7071 return nullptr;
7072
7073 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007074 }
7075
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007076 // Accesses to members are potential references to data on the stack.
7077 case Stmt::MemberExprClass: {
7078 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00007079
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007080 // Check for indirect access. We only want direct field accesses.
7081 if (M->isArrow())
7082 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007083
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007084 // Check whether the member type is itself a reference, in which case
7085 // we're not going to refer to the member, but to what the member refers
7086 // to.
7087 if (M->getMemberDecl()->getType()->isReferenceType())
7088 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007089
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007090 return EvalVal(M->getBase(), refVars, ParentDecl);
7091 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00007092
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007093 case Stmt::MaterializeTemporaryExprClass:
7094 if (const Expr *Result =
7095 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7096 refVars, ParentDecl))
7097 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007098 return E;
7099
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007100 default:
7101 // Check that we don't return or take the address of a reference to a
7102 // temporary. This is only useful in C++.
7103 if (!E->isTypeDependent() && E->isRValue())
7104 return E;
7105
7106 // Everything else: we simply don't reason about them.
7107 return nullptr;
7108 }
7109 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007110}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007111
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007112void
7113Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7114 SourceLocation ReturnLoc,
7115 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00007116 const AttrVec *Attrs,
7117 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007118 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7119
7120 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00007121 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7122 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00007123 CheckNonNullExpr(*this, RetValExp))
7124 Diag(ReturnLoc, diag::warn_null_ret)
7125 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00007126
7127 // C++11 [basic.stc.dynamic.allocation]p4:
7128 // If an allocation function declared with a non-throwing
7129 // exception-specification fails to allocate storage, it shall return
7130 // a null pointer. Any other allocation function that fails to allocate
7131 // storage shall indicate failure only by throwing an exception [...]
7132 if (FD) {
7133 OverloadedOperatorKind Op = FD->getOverloadedOperator();
7134 if (Op == OO_New || Op == OO_Array_New) {
7135 const FunctionProtoType *Proto
7136 = FD->getType()->castAs<FunctionProtoType>();
7137 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7138 CheckNonNullExpr(*this, RetValExp))
7139 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7140 << FD << getLangOpts().CPlusPlus11;
7141 }
7142 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007143}
7144
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007145//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7146
7147/// Check for comparisons of floating point operands using != and ==.
7148/// Issue a warning if these are no self-comparisons, as they are not likely
7149/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00007150void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00007151 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7152 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007153
7154 // Special case: check for x == x (which is OK).
7155 // Do not emit warnings for such cases.
7156 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7157 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7158 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00007159 return;
Mike Stump11289f42009-09-09 15:08:12 +00007160
Ted Kremenekeda40e22007-11-29 00:59:04 +00007161 // Special case: check for comparisons against literals that can be exactly
7162 // represented by APFloat. In such cases, do not emit a warning. This
7163 // is a heuristic: often comparison against such literals are used to
7164 // detect if a value in a variable has not changed. This clearly can
7165 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00007166 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7167 if (FLL->isExact())
7168 return;
7169 } else
7170 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7171 if (FLR->isExact())
7172 return;
Mike Stump11289f42009-09-09 15:08:12 +00007173
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007174 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00007175 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007176 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007177 return;
Mike Stump11289f42009-09-09 15:08:12 +00007178
David Blaikie1f4ff152012-07-16 20:47:22 +00007179 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007180 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007181 return;
Mike Stump11289f42009-09-09 15:08:12 +00007182
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007183 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00007184 Diag(Loc, diag::warn_floatingpoint_eq)
7185 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007186}
John McCallca01b222010-01-04 23:21:16 +00007187
John McCall70aa5392010-01-06 05:24:50 +00007188//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7189//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00007190
John McCall70aa5392010-01-06 05:24:50 +00007191namespace {
John McCallca01b222010-01-04 23:21:16 +00007192
John McCall70aa5392010-01-06 05:24:50 +00007193/// Structure recording the 'active' range of an integer-valued
7194/// expression.
7195struct IntRange {
7196 /// The number of bits active in the int.
7197 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00007198
John McCall70aa5392010-01-06 05:24:50 +00007199 /// True if the int is known not to have negative values.
7200 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00007201
John McCall70aa5392010-01-06 05:24:50 +00007202 IntRange(unsigned Width, bool NonNegative)
7203 : Width(Width), NonNegative(NonNegative)
7204 {}
John McCallca01b222010-01-04 23:21:16 +00007205
John McCall817d4af2010-11-10 23:38:19 +00007206 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00007207 static IntRange forBoolType() {
7208 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00007209 }
7210
John McCall817d4af2010-11-10 23:38:19 +00007211 /// Returns the range of an opaque value of the given integral type.
7212 static IntRange forValueOfType(ASTContext &C, QualType T) {
7213 return forValueOfCanonicalType(C,
7214 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00007215 }
7216
John McCall817d4af2010-11-10 23:38:19 +00007217 /// Returns the range of an opaque value of a canonical integral type.
7218 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00007219 assert(T->isCanonicalUnqualified());
7220
7221 if (const VectorType *VT = dyn_cast<VectorType>(T))
7222 T = VT->getElementType().getTypePtr();
7223 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7224 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007225 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7226 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00007227
David Majnemer6a426652013-06-07 22:07:20 +00007228 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00007229 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00007230 EnumDecl *Enum = ET->getDecl();
7231 if (!Enum->isCompleteDefinition())
7232 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00007233
David Majnemer6a426652013-06-07 22:07:20 +00007234 unsigned NumPositive = Enum->getNumPositiveBits();
7235 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00007236
David Majnemer6a426652013-06-07 22:07:20 +00007237 if (NumNegative == 0)
7238 return IntRange(NumPositive, true/*NonNegative*/);
7239 else
7240 return IntRange(std::max(NumPositive + 1, NumNegative),
7241 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00007242 }
John McCall70aa5392010-01-06 05:24:50 +00007243
7244 const BuiltinType *BT = cast<BuiltinType>(T);
7245 assert(BT->isInteger());
7246
7247 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7248 }
7249
John McCall817d4af2010-11-10 23:38:19 +00007250 /// Returns the "target" range of a canonical integral type, i.e.
7251 /// the range of values expressible in the type.
7252 ///
7253 /// This matches forValueOfCanonicalType except that enums have the
7254 /// full range of their type, not the range of their enumerators.
7255 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7256 assert(T->isCanonicalUnqualified());
7257
7258 if (const VectorType *VT = dyn_cast<VectorType>(T))
7259 T = VT->getElementType().getTypePtr();
7260 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7261 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007262 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7263 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007264 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00007265 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007266
7267 const BuiltinType *BT = cast<BuiltinType>(T);
7268 assert(BT->isInteger());
7269
7270 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7271 }
7272
7273 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00007274 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00007275 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00007276 L.NonNegative && R.NonNegative);
7277 }
7278
John McCall817d4af2010-11-10 23:38:19 +00007279 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00007280 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00007281 return IntRange(std::min(L.Width, R.Width),
7282 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00007283 }
7284};
7285
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007286IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007287 if (value.isSigned() && value.isNegative())
7288 return IntRange(value.getMinSignedBits(), false);
7289
7290 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00007291 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007292
7293 // isNonNegative() just checks the sign bit without considering
7294 // signedness.
7295 return IntRange(value.getActiveBits(), true);
7296}
7297
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007298IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7299 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007300 if (result.isInt())
7301 return GetValueRange(C, result.getInt(), MaxWidth);
7302
7303 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00007304 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7305 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7306 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7307 R = IntRange::join(R, El);
7308 }
John McCall70aa5392010-01-06 05:24:50 +00007309 return R;
7310 }
7311
7312 if (result.isComplexInt()) {
7313 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7314 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7315 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00007316 }
7317
7318 // This can happen with lossless casts to intptr_t of "based" lvalues.
7319 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00007320 // FIXME: The only reason we need to pass the type in here is to get
7321 // the sign right on this one case. It would be nice if APValue
7322 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007323 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00007324 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00007325}
John McCall70aa5392010-01-06 05:24:50 +00007326
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007327QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007328 QualType Ty = E->getType();
7329 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7330 Ty = AtomicRHS->getValueType();
7331 return Ty;
7332}
7333
John McCall70aa5392010-01-06 05:24:50 +00007334/// Pseudo-evaluate the given integer expression, estimating the
7335/// range of values it might take.
7336///
7337/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007338IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007339 E = E->IgnoreParens();
7340
7341 // Try a full evaluation first.
7342 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007343 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00007344 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007345
7346 // I think we only want to look through implicit casts here; if the
7347 // user has an explicit widening cast, we should treat the value as
7348 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007349 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00007350 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00007351 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7352
Eli Friedmane6d33952013-07-08 20:20:06 +00007353 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00007354
George Burgess IVdf1ed002016-01-13 01:52:39 +00007355 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7356 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00007357
John McCall70aa5392010-01-06 05:24:50 +00007358 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00007359 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00007360 return OutputTypeRange;
7361
7362 IntRange SubRange
7363 = GetExprRange(C, CE->getSubExpr(),
7364 std::min(MaxWidth, OutputTypeRange.Width));
7365
7366 // Bail out if the subexpr's range is as wide as the cast type.
7367 if (SubRange.Width >= OutputTypeRange.Width)
7368 return OutputTypeRange;
7369
7370 // Otherwise, we take the smaller width, and we're non-negative if
7371 // either the output type or the subexpr is.
7372 return IntRange(SubRange.Width,
7373 SubRange.NonNegative || OutputTypeRange.NonNegative);
7374 }
7375
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007376 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007377 // If we can fold the condition, just take that operand.
7378 bool CondResult;
7379 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7380 return GetExprRange(C, CondResult ? CO->getTrueExpr()
7381 : CO->getFalseExpr(),
7382 MaxWidth);
7383
7384 // Otherwise, conservatively merge.
7385 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7386 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7387 return IntRange::join(L, R);
7388 }
7389
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007390 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007391 switch (BO->getOpcode()) {
7392
7393 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00007394 case BO_LAnd:
7395 case BO_LOr:
7396 case BO_LT:
7397 case BO_GT:
7398 case BO_LE:
7399 case BO_GE:
7400 case BO_EQ:
7401 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00007402 return IntRange::forBoolType();
7403
John McCallc3688382011-07-13 06:35:24 +00007404 // The type of the assignments is the type of the LHS, so the RHS
7405 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00007406 case BO_MulAssign:
7407 case BO_DivAssign:
7408 case BO_RemAssign:
7409 case BO_AddAssign:
7410 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00007411 case BO_XorAssign:
7412 case BO_OrAssign:
7413 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00007414 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00007415
John McCallc3688382011-07-13 06:35:24 +00007416 // Simple assignments just pass through the RHS, which will have
7417 // been coerced to the LHS type.
7418 case BO_Assign:
7419 // TODO: bitfields?
7420 return GetExprRange(C, BO->getRHS(), MaxWidth);
7421
John McCall70aa5392010-01-06 05:24:50 +00007422 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00007423 case BO_PtrMemD:
7424 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00007425 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007426
John McCall2ce81ad2010-01-06 22:07:33 +00007427 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00007428 case BO_And:
7429 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00007430 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
7431 GetExprRange(C, BO->getRHS(), MaxWidth));
7432
John McCall70aa5392010-01-06 05:24:50 +00007433 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00007434 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00007435 // ...except that we want to treat '1 << (blah)' as logically
7436 // positive. It's an important idiom.
7437 if (IntegerLiteral *I
7438 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
7439 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007440 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00007441 return IntRange(R.Width, /*NonNegative*/ true);
7442 }
7443 }
7444 // fallthrough
7445
John McCalle3027922010-08-25 11:45:40 +00007446 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00007447 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007448
John McCall2ce81ad2010-01-06 22:07:33 +00007449 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00007450 case BO_Shr:
7451 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00007452 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7453
7454 // If the shift amount is a positive constant, drop the width by
7455 // that much.
7456 llvm::APSInt shift;
7457 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
7458 shift.isNonNegative()) {
7459 unsigned zext = shift.getZExtValue();
7460 if (zext >= L.Width)
7461 L.Width = (L.NonNegative ? 0 : 1);
7462 else
7463 L.Width -= zext;
7464 }
7465
7466 return L;
7467 }
7468
7469 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00007470 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00007471 return GetExprRange(C, BO->getRHS(), MaxWidth);
7472
John McCall2ce81ad2010-01-06 22:07:33 +00007473 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00007474 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00007475 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00007476 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007477 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007478
John McCall51431812011-07-14 22:39:48 +00007479 // The width of a division result is mostly determined by the size
7480 // of the LHS.
7481 case BO_Div: {
7482 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00007483 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007484 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7485
7486 // If the divisor is constant, use that.
7487 llvm::APSInt divisor;
7488 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
7489 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
7490 if (log2 >= L.Width)
7491 L.Width = (L.NonNegative ? 0 : 1);
7492 else
7493 L.Width = std::min(L.Width - log2, MaxWidth);
7494 return L;
7495 }
7496
7497 // Otherwise, just use the LHS's width.
7498 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7499 return IntRange(L.Width, L.NonNegative && R.NonNegative);
7500 }
7501
7502 // The result of a remainder can't be larger than the result of
7503 // either side.
7504 case BO_Rem: {
7505 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00007506 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007507 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7508 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7509
7510 IntRange meet = IntRange::meet(L, R);
7511 meet.Width = std::min(meet.Width, MaxWidth);
7512 return meet;
7513 }
7514
7515 // The default behavior is okay for these.
7516 case BO_Mul:
7517 case BO_Add:
7518 case BO_Xor:
7519 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00007520 break;
7521 }
7522
John McCall51431812011-07-14 22:39:48 +00007523 // The default case is to treat the operation as if it were closed
7524 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00007525 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7526 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
7527 return IntRange::join(L, R);
7528 }
7529
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007530 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007531 switch (UO->getOpcode()) {
7532 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00007533 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00007534 return IntRange::forBoolType();
7535
7536 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00007537 case UO_Deref:
7538 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00007539 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007540
7541 default:
7542 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
7543 }
7544 }
7545
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007546 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00007547 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
7548
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007549 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00007550 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00007551 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00007552
Eli Friedmane6d33952013-07-08 20:20:06 +00007553 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007554}
John McCall263a48b2010-01-04 23:31:57 +00007555
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007556IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007557 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00007558}
7559
John McCall263a48b2010-01-04 23:31:57 +00007560/// Checks whether the given value, which currently has the given
7561/// source semantics, has the same value when coerced through the
7562/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007563bool IsSameFloatAfterCast(const llvm::APFloat &value,
7564 const llvm::fltSemantics &Src,
7565 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00007566 llvm::APFloat truncated = value;
7567
7568 bool ignored;
7569 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
7570 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
7571
7572 return truncated.bitwiseIsEqual(value);
7573}
7574
7575/// Checks whether the given value, which currently has the given
7576/// source semantics, has the same value when coerced through the
7577/// target semantics.
7578///
7579/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007580bool IsSameFloatAfterCast(const APValue &value,
7581 const llvm::fltSemantics &Src,
7582 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00007583 if (value.isFloat())
7584 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
7585
7586 if (value.isVector()) {
7587 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
7588 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
7589 return false;
7590 return true;
7591 }
7592
7593 assert(value.isComplexFloat());
7594 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
7595 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
7596}
7597
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007598void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007599
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007600bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00007601 // Suppress cases where we are comparing against an enum constant.
7602 if (const DeclRefExpr *DR =
7603 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
7604 if (isa<EnumConstantDecl>(DR->getDecl()))
7605 return false;
7606
7607 // Suppress cases where the '0' value is expanded from a macro.
7608 if (E->getLocStart().isMacroID())
7609 return false;
7610
John McCallcc7e5bf2010-05-06 08:58:33 +00007611 llvm::APSInt Value;
7612 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
7613}
7614
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007615bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00007616 // Strip off implicit integral promotions.
7617 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00007618 if (ICE->getCastKind() != CK_IntegralCast &&
7619 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00007620 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00007621 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00007622 }
7623
7624 return E->getType()->isEnumeralType();
7625}
7626
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007627void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00007628 // Disable warning in template instantiations.
7629 if (!S.ActiveTemplateInstantiations.empty())
7630 return;
7631
John McCalle3027922010-08-25 11:45:40 +00007632 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00007633 if (E->isValueDependent())
7634 return;
7635
John McCalle3027922010-08-25 11:45:40 +00007636 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007637 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007638 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007639 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007640 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007641 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007642 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007643 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007644 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007645 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007646 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007647 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007648 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007649 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007650 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007651 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7652 }
7653}
7654
Benjamin Kramer7320b992016-06-15 14:20:56 +00007655void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
7656 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007657 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00007658 // Disable warning in template instantiations.
7659 if (!S.ActiveTemplateInstantiations.empty())
7660 return;
7661
Richard Trieu0f097742014-04-04 04:13:47 +00007662 // TODO: Investigate using GetExprRange() to get tighter bounds
7663 // on the bit ranges.
7664 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00007665 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00007666 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00007667 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
7668 unsigned OtherWidth = OtherRange.Width;
7669
7670 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
7671
Richard Trieu560910c2012-11-14 22:50:24 +00007672 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00007673 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00007674 return;
7675
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007676 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00007677 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007678
Richard Trieu0f097742014-04-04 04:13:47 +00007679 // Used for diagnostic printout.
7680 enum {
7681 LiteralConstant = 0,
7682 CXXBoolLiteralTrue,
7683 CXXBoolLiteralFalse
7684 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007685
Richard Trieu0f097742014-04-04 04:13:47 +00007686 if (!OtherIsBooleanType) {
7687 QualType ConstantT = Constant->getType();
7688 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00007689
Richard Trieu0f097742014-04-04 04:13:47 +00007690 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
7691 return;
7692 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
7693 "comparison with non-integer type");
7694
7695 bool ConstantSigned = ConstantT->isSignedIntegerType();
7696 bool CommonSigned = CommonT->isSignedIntegerType();
7697
7698 bool EqualityOnly = false;
7699
7700 if (CommonSigned) {
7701 // The common type is signed, therefore no signed to unsigned conversion.
7702 if (!OtherRange.NonNegative) {
7703 // Check that the constant is representable in type OtherT.
7704 if (ConstantSigned) {
7705 if (OtherWidth >= Value.getMinSignedBits())
7706 return;
7707 } else { // !ConstantSigned
7708 if (OtherWidth >= Value.getActiveBits() + 1)
7709 return;
7710 }
7711 } else { // !OtherSigned
7712 // Check that the constant is representable in type OtherT.
7713 // Negative values are out of range.
7714 if (ConstantSigned) {
7715 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
7716 return;
7717 } else { // !ConstantSigned
7718 if (OtherWidth >= Value.getActiveBits())
7719 return;
7720 }
Richard Trieu560910c2012-11-14 22:50:24 +00007721 }
Richard Trieu0f097742014-04-04 04:13:47 +00007722 } else { // !CommonSigned
7723 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00007724 if (OtherWidth >= Value.getActiveBits())
7725 return;
Craig Toppercf360162014-06-18 05:13:11 +00007726 } else { // OtherSigned
7727 assert(!ConstantSigned &&
7728 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00007729 // Check to see if the constant is representable in OtherT.
7730 if (OtherWidth > Value.getActiveBits())
7731 return;
7732 // Check to see if the constant is equivalent to a negative value
7733 // cast to CommonT.
7734 if (S.Context.getIntWidth(ConstantT) ==
7735 S.Context.getIntWidth(CommonT) &&
7736 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
7737 return;
7738 // The constant value rests between values that OtherT can represent
7739 // after conversion. Relational comparison still works, but equality
7740 // comparisons will be tautological.
7741 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007742 }
7743 }
Richard Trieu0f097742014-04-04 04:13:47 +00007744
7745 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
7746
7747 if (op == BO_EQ || op == BO_NE) {
7748 IsTrue = op == BO_NE;
7749 } else if (EqualityOnly) {
7750 return;
7751 } else if (RhsConstant) {
7752 if (op == BO_GT || op == BO_GE)
7753 IsTrue = !PositiveConstant;
7754 else // op == BO_LT || op == BO_LE
7755 IsTrue = PositiveConstant;
7756 } else {
7757 if (op == BO_LT || op == BO_LE)
7758 IsTrue = !PositiveConstant;
7759 else // op == BO_GT || op == BO_GE
7760 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007761 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007762 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00007763 // Other isKnownToHaveBooleanValue
7764 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
7765 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
7766 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
7767
7768 static const struct LinkedConditions {
7769 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
7770 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
7771 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
7772 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
7773 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
7774 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
7775
7776 } TruthTable = {
7777 // Constant on LHS. | Constant on RHS. |
7778 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
7779 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
7780 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
7781 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
7782 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
7783 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
7784 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
7785 };
7786
7787 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
7788
7789 enum ConstantValue ConstVal = Zero;
7790 if (Value.isUnsigned() || Value.isNonNegative()) {
7791 if (Value == 0) {
7792 LiteralOrBoolConstant =
7793 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
7794 ConstVal = Zero;
7795 } else if (Value == 1) {
7796 LiteralOrBoolConstant =
7797 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
7798 ConstVal = One;
7799 } else {
7800 LiteralOrBoolConstant = LiteralConstant;
7801 ConstVal = GT_One;
7802 }
7803 } else {
7804 ConstVal = LT_Zero;
7805 }
7806
7807 CompareBoolWithConstantResult CmpRes;
7808
7809 switch (op) {
7810 case BO_LT:
7811 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
7812 break;
7813 case BO_GT:
7814 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
7815 break;
7816 case BO_LE:
7817 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
7818 break;
7819 case BO_GE:
7820 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
7821 break;
7822 case BO_EQ:
7823 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
7824 break;
7825 case BO_NE:
7826 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
7827 break;
7828 default:
7829 CmpRes = Unkwn;
7830 break;
7831 }
7832
7833 if (CmpRes == AFals) {
7834 IsTrue = false;
7835 } else if (CmpRes == ATrue) {
7836 IsTrue = true;
7837 } else {
7838 return;
7839 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007840 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007841
7842 // If this is a comparison to an enum constant, include that
7843 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00007844 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007845 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
7846 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
7847
7848 SmallString<64> PrettySourceValue;
7849 llvm::raw_svector_ostream OS(PrettySourceValue);
7850 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00007851 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007852 else
7853 OS << Value;
7854
Richard Trieu0f097742014-04-04 04:13:47 +00007855 S.DiagRuntimeBehavior(
7856 E->getOperatorLoc(), E,
7857 S.PDiag(diag::warn_out_of_range_compare)
7858 << OS.str() << LiteralOrBoolConstant
7859 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
7860 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007861}
7862
John McCallcc7e5bf2010-05-06 08:58:33 +00007863/// Analyze the operands of the given comparison. Implements the
7864/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007865void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00007866 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7867 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007868}
John McCall263a48b2010-01-04 23:31:57 +00007869
John McCallca01b222010-01-04 23:21:16 +00007870/// \brief Implements -Wsign-compare.
7871///
Richard Trieu82402a02011-09-15 21:56:47 +00007872/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007873void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007874 // The type the comparison is being performed in.
7875 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00007876
7877 // Only analyze comparison operators where both sides have been converted to
7878 // the same type.
7879 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
7880 return AnalyzeImpConvsInComparison(S, E);
7881
7882 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00007883 if (E->isValueDependent())
7884 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007885
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007886 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
7887 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007888
7889 bool IsComparisonConstant = false;
7890
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007891 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007892 // of 'true' or 'false'.
7893 if (T->isIntegralType(S.Context)) {
7894 llvm::APSInt RHSValue;
7895 bool IsRHSIntegralLiteral =
7896 RHS->isIntegerConstantExpr(RHSValue, S.Context);
7897 llvm::APSInt LHSValue;
7898 bool IsLHSIntegralLiteral =
7899 LHS->isIntegerConstantExpr(LHSValue, S.Context);
7900 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
7901 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
7902 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
7903 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
7904 else
7905 IsComparisonConstant =
7906 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007907 } else if (!T->hasUnsignedIntegerRepresentation())
7908 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007909
John McCallcc7e5bf2010-05-06 08:58:33 +00007910 // We don't do anything special if this isn't an unsigned integral
7911 // comparison: we're only interested in integral comparisons, and
7912 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00007913 //
7914 // We also don't care about value-dependent expressions or expressions
7915 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007916 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00007917 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007918
John McCallcc7e5bf2010-05-06 08:58:33 +00007919 // Check to see if one of the (unmodified) operands is of different
7920 // signedness.
7921 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00007922 if (LHS->getType()->hasSignedIntegerRepresentation()) {
7923 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00007924 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00007925 signedOperand = LHS;
7926 unsignedOperand = RHS;
7927 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
7928 signedOperand = RHS;
7929 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00007930 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00007931 CheckTrivialUnsignedComparison(S, E);
7932 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007933 }
7934
John McCallcc7e5bf2010-05-06 08:58:33 +00007935 // Otherwise, calculate the effective range of the signed operand.
7936 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00007937
John McCallcc7e5bf2010-05-06 08:58:33 +00007938 // Go ahead and analyze implicit conversions in the operands. Note
7939 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00007940 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
7941 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00007942
John McCallcc7e5bf2010-05-06 08:58:33 +00007943 // If the signed range is non-negative, -Wsign-compare won't fire,
7944 // but we should still check for comparisons which are always true
7945 // or false.
7946 if (signedRange.NonNegative)
7947 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007948
7949 // For (in)equality comparisons, if the unsigned operand is a
7950 // constant which cannot collide with a overflowed signed operand,
7951 // then reinterpreting the signed operand as unsigned will not
7952 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00007953 if (E->isEqualityOp()) {
7954 unsigned comparisonWidth = S.Context.getIntWidth(T);
7955 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00007956
John McCallcc7e5bf2010-05-06 08:58:33 +00007957 // We should never be unable to prove that the unsigned operand is
7958 // non-negative.
7959 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
7960
7961 if (unsignedRange.Width < comparisonWidth)
7962 return;
7963 }
7964
Douglas Gregorbfb4a212012-05-01 01:53:49 +00007965 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
7966 S.PDiag(diag::warn_mixed_sign_comparison)
7967 << LHS->getType() << RHS->getType()
7968 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00007969}
7970
John McCall1f425642010-11-11 03:21:53 +00007971/// Analyzes an attempt to assign the given value to a bitfield.
7972///
7973/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007974bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
7975 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00007976 assert(Bitfield->isBitField());
7977 if (Bitfield->isInvalidDecl())
7978 return false;
7979
John McCalldeebbcf2010-11-11 05:33:51 +00007980 // White-list bool bitfields.
7981 if (Bitfield->getType()->isBooleanType())
7982 return false;
7983
Douglas Gregor789adec2011-02-04 13:09:01 +00007984 // Ignore value- or type-dependent expressions.
7985 if (Bitfield->getBitWidth()->isValueDependent() ||
7986 Bitfield->getBitWidth()->isTypeDependent() ||
7987 Init->isValueDependent() ||
7988 Init->isTypeDependent())
7989 return false;
7990
John McCall1f425642010-11-11 03:21:53 +00007991 Expr *OriginalInit = Init->IgnoreParenImpCasts();
7992
Richard Smith5fab0c92011-12-28 19:48:30 +00007993 llvm::APSInt Value;
7994 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00007995 return false;
7996
John McCall1f425642010-11-11 03:21:53 +00007997 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00007998 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00007999
Richard Trieu7561ed02016-08-05 02:39:30 +00008000 if (Value.isSigned() && Value.isNegative())
8001 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
8002 if (UO->getOpcode() == UO_Minus)
8003 if (isa<IntegerLiteral>(UO->getSubExpr()))
8004 OriginalWidth = Value.getMinSignedBits();
8005
John McCall1f425642010-11-11 03:21:53 +00008006 if (OriginalWidth <= FieldWidth)
8007 return false;
8008
Eli Friedmanc267a322012-01-26 23:11:39 +00008009 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00008010 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00008011 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00008012
Eli Friedmanc267a322012-01-26 23:11:39 +00008013 // Check whether the stored value is equal to the original value.
8014 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00008015 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00008016 return false;
8017
Eli Friedmanc267a322012-01-26 23:11:39 +00008018 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00008019 // therefore don't strictly fit into a signed bitfield of width 1.
8020 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00008021 return false;
8022
John McCall1f425642010-11-11 03:21:53 +00008023 std::string PrettyValue = Value.toString(10);
8024 std::string PrettyTrunc = TruncatedValue.toString(10);
8025
8026 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8027 << PrettyValue << PrettyTrunc << OriginalInit->getType()
8028 << Init->getSourceRange();
8029
8030 return true;
8031}
8032
John McCalld2a53122010-11-09 23:24:47 +00008033/// Analyze the given simple or compound assignment for warning-worthy
8034/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008035void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00008036 // Just recurse on the LHS.
8037 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8038
8039 // We want to recurse on the RHS as normal unless we're assigning to
8040 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00008041 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008042 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00008043 E->getOperatorLoc())) {
8044 // Recurse, ignoring any implicit conversions on the RHS.
8045 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8046 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00008047 }
8048 }
8049
8050 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8051}
8052
John McCall263a48b2010-01-04 23:31:57 +00008053/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008054void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8055 SourceLocation CContext, unsigned diag,
8056 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008057 if (pruneControlFlow) {
8058 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8059 S.PDiag(diag)
8060 << SourceType << T << E->getSourceRange()
8061 << SourceRange(CContext));
8062 return;
8063 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00008064 S.Diag(E->getExprLoc(), diag)
8065 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8066}
8067
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008068/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008069void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8070 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008071 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008072}
8073
Richard Trieube234c32016-04-21 21:04:55 +00008074
8075/// Diagnose an implicit cast from a floating point value to an integer value.
8076void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8077
8078 SourceLocation CContext) {
8079 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
8080 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
8081
8082 Expr *InnerE = E->IgnoreParenImpCasts();
8083 // We also want to warn on, e.g., "int i = -1.234"
8084 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8085 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8086 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8087
8088 const bool IsLiteral =
8089 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8090
8091 llvm::APFloat Value(0.0);
8092 bool IsConstant =
8093 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8094 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00008095 return DiagnoseImpCast(S, E, T, CContext,
8096 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00008097 }
8098
Chandler Carruth016ef402011-04-10 08:36:24 +00008099 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00008100
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00008101 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8102 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00008103 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8104 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00008105 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00008106 if (IsLiteral) return;
8107 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8108 PruneWarnings);
8109 }
8110
8111 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00008112 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00008113 // Warn on floating point literal to integer.
8114 DiagID = diag::warn_impcast_literal_float_to_integer;
8115 } else if (IntegerValue == 0) {
8116 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
8117 return DiagnoseImpCast(S, E, T, CContext,
8118 diag::warn_impcast_float_integer, PruneWarnings);
8119 }
8120 // Warn on non-zero to zero conversion.
8121 DiagID = diag::warn_impcast_float_to_integer_zero;
8122 } else {
8123 if (IntegerValue.isUnsigned()) {
8124 if (!IntegerValue.isMaxValue()) {
8125 return DiagnoseImpCast(S, E, T, CContext,
8126 diag::warn_impcast_float_integer, PruneWarnings);
8127 }
8128 } else { // IntegerValue.isSigned()
8129 if (!IntegerValue.isMaxSignedValue() &&
8130 !IntegerValue.isMinSignedValue()) {
8131 return DiagnoseImpCast(S, E, T, CContext,
8132 diag::warn_impcast_float_integer, PruneWarnings);
8133 }
8134 }
8135 // Warn on evaluatable floating point expression to integer conversion.
8136 DiagID = diag::warn_impcast_float_to_integer;
8137 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008138
Eli Friedman07185912013-08-29 23:44:43 +00008139 // FIXME: Force the precision of the source value down so we don't print
8140 // digits which are usually useless (we don't really care here if we
8141 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
8142 // would automatically print the shortest representation, but it's a bit
8143 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00008144 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00008145 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
8146 precision = (precision * 59 + 195) / 196;
8147 Value.toString(PrettySourceValue, precision);
8148
David Blaikie9b88cc02012-05-15 17:18:27 +00008149 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00008150 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00008151 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00008152 else
David Blaikie9b88cc02012-05-15 17:18:27 +00008153 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00008154
Richard Trieube234c32016-04-21 21:04:55 +00008155 if (PruneWarnings) {
8156 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8157 S.PDiag(DiagID)
8158 << E->getType() << T.getUnqualifiedType()
8159 << PrettySourceValue << PrettyTargetValue
8160 << E->getSourceRange() << SourceRange(CContext));
8161 } else {
8162 S.Diag(E->getExprLoc(), DiagID)
8163 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8164 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8165 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008166}
8167
John McCall18a2c2c2010-11-09 22:22:12 +00008168std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8169 if (!Range.Width) return "0";
8170
8171 llvm::APSInt ValueInRange = Value;
8172 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00008173 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00008174 return ValueInRange.toString(10);
8175}
8176
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008177bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008178 if (!isa<ImplicitCastExpr>(Ex))
8179 return false;
8180
8181 Expr *InnerE = Ex->IgnoreParenImpCasts();
8182 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8183 const Type *Source =
8184 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8185 if (Target->isDependentType())
8186 return false;
8187
8188 const BuiltinType *FloatCandidateBT =
8189 dyn_cast<BuiltinType>(ToBool ? Source : Target);
8190 const Type *BoolCandidateType = ToBool ? Target : Source;
8191
8192 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8193 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8194}
8195
8196void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8197 SourceLocation CC) {
8198 unsigned NumArgs = TheCall->getNumArgs();
8199 for (unsigned i = 0; i < NumArgs; ++i) {
8200 Expr *CurrA = TheCall->getArg(i);
8201 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8202 continue;
8203
8204 bool IsSwapped = ((i > 0) &&
8205 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8206 IsSwapped |= ((i < (NumArgs - 1)) &&
8207 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8208 if (IsSwapped) {
8209 // Warn on this floating-point to bool conversion.
8210 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8211 CurrA->getType(), CC,
8212 diag::warn_impcast_floating_point_to_bool);
8213 }
8214 }
8215}
8216
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008217void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00008218 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
8219 E->getExprLoc()))
8220 return;
8221
Richard Trieu09d6b802016-01-08 23:35:06 +00008222 // Don't warn on functions which have return type nullptr_t.
8223 if (isa<CallExpr>(E))
8224 return;
8225
Richard Trieu5b993502014-10-15 03:42:06 +00008226 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
8227 const Expr::NullPointerConstantKind NullKind =
8228 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
8229 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
8230 return;
8231
8232 // Return if target type is a safe conversion.
8233 if (T->isAnyPointerType() || T->isBlockPointerType() ||
8234 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8235 return;
8236
8237 SourceLocation Loc = E->getSourceRange().getBegin();
8238
Richard Trieu0a5e1662016-02-13 00:58:53 +00008239 // Venture through the macro stacks to get to the source of macro arguments.
8240 // The new location is a better location than the complete location that was
8241 // passed in.
8242 while (S.SourceMgr.isMacroArgExpansion(Loc))
8243 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8244
8245 while (S.SourceMgr.isMacroArgExpansion(CC))
8246 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8247
Richard Trieu5b993502014-10-15 03:42:06 +00008248 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00008249 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8250 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8251 Loc, S.SourceMgr, S.getLangOpts());
8252 if (MacroName == "NULL")
8253 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00008254 }
8255
8256 // Only warn if the null and context location are in the same macro expansion.
8257 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8258 return;
8259
8260 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8261 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8262 << FixItHint::CreateReplacement(Loc,
8263 S.getFixItZeroLiteralForType(T, Loc));
8264}
8265
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008266void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8267 ObjCArrayLiteral *ArrayLiteral);
8268void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8269 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00008270
8271/// Check a single element within a collection literal against the
8272/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008273void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8274 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008275 // Skip a bitcast to 'id' or qualified 'id'.
8276 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8277 if (ICE->getCastKind() == CK_BitCast &&
8278 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8279 Element = ICE->getSubExpr();
8280 }
8281
8282 QualType ElementType = Element->getType();
8283 ExprResult ElementResult(Element);
8284 if (ElementType->getAs<ObjCObjectPointerType>() &&
8285 S.CheckSingleAssignmentConstraints(TargetElementType,
8286 ElementResult,
8287 false, false)
8288 != Sema::Compatible) {
8289 S.Diag(Element->getLocStart(),
8290 diag::warn_objc_collection_literal_element)
8291 << ElementType << ElementKind << TargetElementType
8292 << Element->getSourceRange();
8293 }
8294
8295 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8296 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8297 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8298 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8299}
8300
8301/// Check an Objective-C array literal being converted to the given
8302/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008303void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8304 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008305 if (!S.NSArrayDecl)
8306 return;
8307
8308 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8309 if (!TargetObjCPtr)
8310 return;
8311
8312 if (TargetObjCPtr->isUnspecialized() ||
8313 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8314 != S.NSArrayDecl->getCanonicalDecl())
8315 return;
8316
8317 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8318 if (TypeArgs.size() != 1)
8319 return;
8320
8321 QualType TargetElementType = TypeArgs[0];
8322 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8323 checkObjCCollectionLiteralElement(S, TargetElementType,
8324 ArrayLiteral->getElement(I),
8325 0);
8326 }
8327}
8328
8329/// Check an Objective-C dictionary literal being converted to the given
8330/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008331void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8332 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008333 if (!S.NSDictionaryDecl)
8334 return;
8335
8336 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8337 if (!TargetObjCPtr)
8338 return;
8339
8340 if (TargetObjCPtr->isUnspecialized() ||
8341 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8342 != S.NSDictionaryDecl->getCanonicalDecl())
8343 return;
8344
8345 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8346 if (TypeArgs.size() != 2)
8347 return;
8348
8349 QualType TargetKeyType = TypeArgs[0];
8350 QualType TargetObjectType = TypeArgs[1];
8351 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8352 auto Element = DictionaryLiteral->getKeyValueElement(I);
8353 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8354 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8355 }
8356}
8357
Richard Trieufc404c72016-02-05 23:02:38 +00008358// Helper function to filter out cases for constant width constant conversion.
8359// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008360bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8361 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00008362 // If initializing from a constant, and the constant starts with '0',
8363 // then it is a binary, octal, or hexadecimal. Allow these constants
8364 // to fill all the bits, even if there is a sign change.
8365 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8366 const char FirstLiteralCharacter =
8367 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8368 if (FirstLiteralCharacter == '0')
8369 return false;
8370 }
8371
8372 // If the CC location points to a '{', and the type is char, then assume
8373 // assume it is an array initialization.
8374 if (CC.isValid() && T->isCharType()) {
8375 const char FirstContextCharacter =
8376 S.getSourceManager().getCharacterData(CC)[0];
8377 if (FirstContextCharacter == '{')
8378 return false;
8379 }
8380
8381 return true;
8382}
8383
John McCallcc7e5bf2010-05-06 08:58:33 +00008384void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00008385 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008386 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00008387
John McCallcc7e5bf2010-05-06 08:58:33 +00008388 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
8389 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
8390 if (Source == Target) return;
8391 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00008392
Chandler Carruthc22845a2011-07-26 05:40:03 +00008393 // If the conversion context location is invalid don't complain. We also
8394 // don't want to emit a warning if the issue occurs from the expansion of
8395 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
8396 // delay this check as long as possible. Once we detect we are in that
8397 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008398 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00008399 return;
8400
Richard Trieu021baa32011-09-23 20:10:00 +00008401 // Diagnose implicit casts to bool.
8402 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
8403 if (isa<StringLiteral>(E))
8404 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00008405 // and expressions, for instance, assert(0 && "error here"), are
8406 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00008407 return DiagnoseImpCast(S, E, T, CC,
8408 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00008409 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
8410 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
8411 // This covers the literal expressions that evaluate to Objective-C
8412 // objects.
8413 return DiagnoseImpCast(S, E, T, CC,
8414 diag::warn_impcast_objective_c_literal_to_bool);
8415 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008416 if (Source->isPointerType() || Source->canDecayToPointerType()) {
8417 // Warn on pointer to bool conversion that is always true.
8418 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
8419 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00008420 }
Richard Trieu021baa32011-09-23 20:10:00 +00008421 }
John McCall263a48b2010-01-04 23:31:57 +00008422
Douglas Gregor5054cb02015-07-07 03:58:22 +00008423 // Check implicit casts from Objective-C collection literals to specialized
8424 // collection types, e.g., NSArray<NSString *> *.
8425 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
8426 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
8427 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
8428 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
8429
John McCall263a48b2010-01-04 23:31:57 +00008430 // Strip vector types.
8431 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008432 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008433 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008434 return;
John McCallacf0ee52010-10-08 02:01:28 +00008435 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008436 }
Chris Lattneree7286f2011-06-14 04:51:15 +00008437
8438 // If the vector cast is cast between two vectors of the same size, it is
8439 // a bitcast, not a conversion.
8440 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
8441 return;
John McCall263a48b2010-01-04 23:31:57 +00008442
8443 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
8444 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
8445 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00008446 if (auto VecTy = dyn_cast<VectorType>(Target))
8447 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00008448
8449 // Strip complex types.
8450 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008451 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008452 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008453 return;
8454
John McCallacf0ee52010-10-08 02:01:28 +00008455 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008456 }
John McCall263a48b2010-01-04 23:31:57 +00008457
8458 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
8459 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
8460 }
8461
8462 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
8463 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
8464
8465 // If the source is floating point...
8466 if (SourceBT && SourceBT->isFloatingPoint()) {
8467 // ...and the target is floating point...
8468 if (TargetBT && TargetBT->isFloatingPoint()) {
8469 // ...then warn if we're dropping FP rank.
8470
8471 // Builtin FP kinds are ordered by increasing FP rank.
8472 if (SourceBT->getKind() > TargetBT->getKind()) {
8473 // Don't warn about float constants that are precisely
8474 // representable in the target type.
8475 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008476 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00008477 // Value might be a float, a float vector, or a float complex.
8478 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00008479 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
8480 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00008481 return;
8482 }
8483
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008484 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008485 return;
8486
John McCallacf0ee52010-10-08 02:01:28 +00008487 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00008488 }
8489 // ... or possibly if we're increasing rank, too
8490 else if (TargetBT->getKind() > SourceBT->getKind()) {
8491 if (S.SourceMgr.isInSystemMacro(CC))
8492 return;
8493
8494 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00008495 }
8496 return;
8497 }
8498
Richard Trieube234c32016-04-21 21:04:55 +00008499 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00008500 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008501 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008502 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00008503
Richard Trieube234c32016-04-21 21:04:55 +00008504 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00008505 }
John McCall263a48b2010-01-04 23:31:57 +00008506
Richard Smith54894fd2015-12-30 01:06:52 +00008507 // Detect the case where a call result is converted from floating-point to
8508 // to bool, and the final argument to the call is converted from bool, to
8509 // discover this typo:
8510 //
8511 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
8512 //
8513 // FIXME: This is an incredibly special case; is there some more general
8514 // way to detect this class of misplaced-parentheses bug?
8515 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008516 // Check last argument of function call to see if it is an
8517 // implicit cast from a type matching the type the result
8518 // is being cast to.
8519 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00008520 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008521 Expr *LastA = CEx->getArg(NumArgs - 1);
8522 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00008523 if (isa<ImplicitCastExpr>(LastA) &&
8524 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008525 // Warn on this floating-point to bool conversion
8526 DiagnoseImpCast(S, E, T, CC,
8527 diag::warn_impcast_floating_point_to_bool);
8528 }
8529 }
8530 }
John McCall263a48b2010-01-04 23:31:57 +00008531 return;
8532 }
8533
Richard Trieu5b993502014-10-15 03:42:06 +00008534 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00008535
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00008536 S.DiscardMisalignedMemberAddress(Target, E);
8537
David Blaikie9366d2b2012-06-19 21:19:06 +00008538 if (!Source->isIntegerType() || !Target->isIntegerType())
8539 return;
8540
David Blaikie7555b6a2012-05-15 16:56:36 +00008541 // TODO: remove this early return once the false positives for constant->bool
8542 // in templates, macros, etc, are reduced or removed.
8543 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
8544 return;
8545
John McCallcc7e5bf2010-05-06 08:58:33 +00008546 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00008547 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00008548
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008549 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00008550 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008551 // TODO: this should happen for bitfield stores, too.
8552 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00008553 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008554 if (S.SourceMgr.isInSystemMacro(CC))
8555 return;
8556
John McCall18a2c2c2010-11-09 22:22:12 +00008557 std::string PrettySourceValue = Value.toString(10);
8558 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008559
Ted Kremenek33ba9952011-10-22 02:37:33 +00008560 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8561 S.PDiag(diag::warn_impcast_integer_precision_constant)
8562 << PrettySourceValue << PrettyTargetValue
8563 << E->getType() << T << E->getSourceRange()
8564 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00008565 return;
8566 }
8567
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008568 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
8569 if (S.SourceMgr.isInSystemMacro(CC))
8570 return;
8571
David Blaikie9455da02012-04-12 22:40:54 +00008572 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00008573 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
8574 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00008575 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00008576 }
8577
Richard Trieudcb55572016-01-29 23:51:16 +00008578 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
8579 SourceRange.NonNegative && Source->isSignedIntegerType()) {
8580 // Warn when doing a signed to signed conversion, warn if the positive
8581 // source value is exactly the width of the target type, which will
8582 // cause a negative value to be stored.
8583
8584 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00008585 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
8586 !S.SourceMgr.isInSystemMacro(CC)) {
8587 if (isSameWidthConstantConversion(S, E, T, CC)) {
8588 std::string PrettySourceValue = Value.toString(10);
8589 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00008590
Richard Trieufc404c72016-02-05 23:02:38 +00008591 S.DiagRuntimeBehavior(
8592 E->getExprLoc(), E,
8593 S.PDiag(diag::warn_impcast_integer_precision_constant)
8594 << PrettySourceValue << PrettyTargetValue << E->getType() << T
8595 << E->getSourceRange() << clang::SourceRange(CC));
8596 return;
Richard Trieudcb55572016-01-29 23:51:16 +00008597 }
8598 }
Richard Trieufc404c72016-02-05 23:02:38 +00008599
Richard Trieudcb55572016-01-29 23:51:16 +00008600 // Fall through for non-constants to give a sign conversion warning.
8601 }
8602
John McCallcc7e5bf2010-05-06 08:58:33 +00008603 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
8604 (!TargetRange.NonNegative && SourceRange.NonNegative &&
8605 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008606 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008607 return;
8608
John McCallcc7e5bf2010-05-06 08:58:33 +00008609 unsigned DiagID = diag::warn_impcast_integer_sign;
8610
8611 // Traditionally, gcc has warned about this under -Wsign-compare.
8612 // We also want to warn about it in -Wconversion.
8613 // So if -Wconversion is off, use a completely identical diagnostic
8614 // in the sign-compare group.
8615 // The conditional-checking code will
8616 if (ICContext) {
8617 DiagID = diag::warn_impcast_integer_sign_conditional;
8618 *ICContext = true;
8619 }
8620
John McCallacf0ee52010-10-08 02:01:28 +00008621 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00008622 }
8623
Douglas Gregora78f1932011-02-22 02:45:07 +00008624 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00008625 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
8626 // type, to give us better diagnostics.
8627 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00008628 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00008629 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8630 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
8631 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
8632 SourceType = S.Context.getTypeDeclType(Enum);
8633 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
8634 }
8635 }
8636
Douglas Gregora78f1932011-02-22 02:45:07 +00008637 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
8638 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00008639 if (SourceEnum->getDecl()->hasNameForLinkage() &&
8640 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008641 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008642 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008643 return;
8644
Douglas Gregor364f7db2011-03-12 00:14:31 +00008645 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00008646 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008647 }
John McCall263a48b2010-01-04 23:31:57 +00008648}
8649
David Blaikie18e9ac72012-05-15 21:57:38 +00008650void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8651 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008652
8653void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00008654 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008655 E = E->IgnoreParenImpCasts();
8656
8657 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00008658 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008659
John McCallacf0ee52010-10-08 02:01:28 +00008660 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008661 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00008662 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00008663}
8664
David Blaikie18e9ac72012-05-15 21:57:38 +00008665void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8666 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00008667 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008668
8669 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00008670 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
8671 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00008672
8673 // If -Wconversion would have warned about either of the candidates
8674 // for a signedness conversion to the context type...
8675 if (!Suspicious) return;
8676
8677 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008678 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00008679 return;
8680
John McCallcc7e5bf2010-05-06 08:58:33 +00008681 // ...then check whether it would have warned about either of the
8682 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00008683 if (E->getType() == T) return;
8684
8685 Suspicious = false;
8686 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
8687 E->getType(), CC, &Suspicious);
8688 if (!Suspicious)
8689 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00008690 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00008691}
8692
Richard Trieu65724892014-11-15 06:37:39 +00008693/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8694/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008695void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00008696 if (S.getLangOpts().Bool)
8697 return;
8698 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
8699}
8700
John McCallcc7e5bf2010-05-06 08:58:33 +00008701/// AnalyzeImplicitConversions - Find and report any interesting
8702/// implicit conversions in the given expression. There are a couple
8703/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008704void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00008705 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00008706 Expr *E = OrigE->IgnoreParenImpCasts();
8707
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00008708 if (E->isTypeDependent() || E->isValueDependent())
8709 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00008710
John McCallcc7e5bf2010-05-06 08:58:33 +00008711 // For conditional operators, we analyze the arguments as if they
8712 // were being fed directly into the output.
8713 if (isa<ConditionalOperator>(E)) {
8714 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00008715 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008716 return;
8717 }
8718
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008719 // Check implicit argument conversions for function calls.
8720 if (CallExpr *Call = dyn_cast<CallExpr>(E))
8721 CheckImplicitArgumentConversions(S, Call, CC);
8722
John McCallcc7e5bf2010-05-06 08:58:33 +00008723 // Go ahead and check any implicit conversions we might have skipped.
8724 // The non-canonical typecheck is just an optimization;
8725 // CheckImplicitConversion will filter out dead implicit conversions.
8726 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00008727 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008728
8729 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00008730
8731 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
8732 // The bound subexpressions in a PseudoObjectExpr are not reachable
8733 // as transitive children.
8734 // FIXME: Use a more uniform representation for this.
8735 for (auto *SE : POE->semantics())
8736 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
8737 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00008738 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00008739
John McCallcc7e5bf2010-05-06 08:58:33 +00008740 // Skip past explicit casts.
8741 if (isa<ExplicitCastExpr>(E)) {
8742 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00008743 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008744 }
8745
John McCalld2a53122010-11-09 23:24:47 +00008746 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8747 // Do a somewhat different check with comparison operators.
8748 if (BO->isComparisonOp())
8749 return AnalyzeComparison(S, BO);
8750
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008751 // And with simple assignments.
8752 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00008753 return AnalyzeAssignment(S, BO);
8754 }
John McCallcc7e5bf2010-05-06 08:58:33 +00008755
8756 // These break the otherwise-useful invariant below. Fortunately,
8757 // we don't really need to recurse into them, because any internal
8758 // expressions should have been analyzed already when they were
8759 // built into statements.
8760 if (isa<StmtExpr>(E)) return;
8761
8762 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00008763 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00008764
8765 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00008766 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00008767 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00008768 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00008769 for (Stmt *SubStmt : E->children()) {
8770 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00008771 if (!ChildExpr)
8772 continue;
8773
Richard Trieu955231d2014-01-25 01:10:35 +00008774 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00008775 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00008776 // Ignore checking string literals that are in logical and operators.
8777 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00008778 continue;
8779 AnalyzeImplicitConversions(S, ChildExpr, CC);
8780 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008781
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008782 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00008783 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
8784 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008785 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00008786
8787 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
8788 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008789 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008790 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008791
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008792 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
8793 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00008794 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008795}
8796
8797} // end anonymous namespace
8798
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00008799static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
8800 unsigned Start, unsigned End) {
8801 bool IllegalParams = false;
8802 for (unsigned I = Start; I <= End; ++I) {
8803 QualType Ty = TheCall->getArg(I)->getType();
8804 // Taking into account implicit conversions,
8805 // allow any integer within 32 bits range
8806 if (!Ty->isIntegerType() ||
8807 S.Context.getTypeSizeInChars(Ty).getQuantity() > 4) {
8808 S.Diag(TheCall->getArg(I)->getLocStart(),
8809 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
8810 IllegalParams = true;
8811 }
8812 // Potentially emit standard warnings for implicit conversions if enabled
8813 // using -Wconversion.
8814 CheckImplicitConversion(S, TheCall->getArg(I), S.Context.UnsignedIntTy,
8815 TheCall->getArg(I)->getLocStart());
8816 }
8817 return IllegalParams;
8818}
8819
Richard Trieuc1888e02014-06-28 23:25:37 +00008820// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
8821// Returns true when emitting a warning about taking the address of a reference.
8822static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00008823 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00008824 E = E->IgnoreParenImpCasts();
8825
8826 const FunctionDecl *FD = nullptr;
8827
8828 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8829 if (!DRE->getDecl()->getType()->isReferenceType())
8830 return false;
8831 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8832 if (!M->getMemberDecl()->getType()->isReferenceType())
8833 return false;
8834 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00008835 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00008836 return false;
8837 FD = Call->getDirectCallee();
8838 } else {
8839 return false;
8840 }
8841
8842 SemaRef.Diag(E->getExprLoc(), PD);
8843
8844 // If possible, point to location of function.
8845 if (FD) {
8846 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
8847 }
8848
8849 return true;
8850}
8851
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008852// Returns true if the SourceLocation is expanded from any macro body.
8853// Returns false if the SourceLocation is invalid, is from not in a macro
8854// expansion, or is from expanded from a top-level macro argument.
8855static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
8856 if (Loc.isInvalid())
8857 return false;
8858
8859 while (Loc.isMacroID()) {
8860 if (SM.isMacroBodyExpansion(Loc))
8861 return true;
8862 Loc = SM.getImmediateMacroCallerLoc(Loc);
8863 }
8864
8865 return false;
8866}
8867
Richard Trieu3bb8b562014-02-26 02:36:06 +00008868/// \brief Diagnose pointers that are always non-null.
8869/// \param E the expression containing the pointer
8870/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
8871/// compared to a null pointer
8872/// \param IsEqual True when the comparison is equal to a null pointer
8873/// \param Range Extra SourceRange to highlight in the diagnostic
8874void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
8875 Expr::NullPointerConstantKind NullKind,
8876 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00008877 if (!E)
8878 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008879
8880 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008881 if (E->getExprLoc().isMacroID()) {
8882 const SourceManager &SM = getSourceManager();
8883 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
8884 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00008885 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008886 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008887 E = E->IgnoreImpCasts();
8888
8889 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
8890
Richard Trieuf7432752014-06-06 21:39:26 +00008891 if (isa<CXXThisExpr>(E)) {
8892 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
8893 : diag::warn_this_bool_conversion;
8894 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
8895 return;
8896 }
8897
Richard Trieu3bb8b562014-02-26 02:36:06 +00008898 bool IsAddressOf = false;
8899
8900 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8901 if (UO->getOpcode() != UO_AddrOf)
8902 return;
8903 IsAddressOf = true;
8904 E = UO->getSubExpr();
8905 }
8906
Richard Trieuc1888e02014-06-28 23:25:37 +00008907 if (IsAddressOf) {
8908 unsigned DiagID = IsCompare
8909 ? diag::warn_address_of_reference_null_compare
8910 : diag::warn_address_of_reference_bool_conversion;
8911 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
8912 << IsEqual;
8913 if (CheckForReference(*this, E, PD)) {
8914 return;
8915 }
8916 }
8917
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008918 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
8919 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00008920 std::string Str;
8921 llvm::raw_string_ostream S(Str);
8922 E->printPretty(S, nullptr, getPrintingPolicy());
8923 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
8924 : diag::warn_cast_nonnull_to_bool;
8925 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
8926 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008927 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00008928 };
8929
8930 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
8931 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
8932 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008933 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
8934 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00008935 return;
8936 }
8937 }
8938 }
8939
Richard Trieu3bb8b562014-02-26 02:36:06 +00008940 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00008941 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008942 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
8943 D = R->getDecl();
8944 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8945 D = M->getMemberDecl();
8946 }
8947
8948 // Weak Decls can be null.
8949 if (!D || D->isWeak())
8950 return;
George Burgess IV850269a2015-12-08 22:02:00 +00008951
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008952 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00008953 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
8954 if (getCurFunction() &&
8955 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008956 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
8957 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00008958 return;
8959 }
8960
8961 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +00008962 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +00008963 assert(ParamIter != FD->param_end());
8964 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
8965
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008966 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
8967 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008968 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +00008969 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008970 }
George Burgess IV850269a2015-12-08 22:02:00 +00008971
8972 for (unsigned ArgNo : NonNull->args()) {
8973 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008974 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008975 return;
8976 }
George Burgess IV850269a2015-12-08 22:02:00 +00008977 }
8978 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008979 }
8980 }
George Burgess IV850269a2015-12-08 22:02:00 +00008981 }
8982
Richard Trieu3bb8b562014-02-26 02:36:06 +00008983 QualType T = D->getType();
8984 const bool IsArray = T->isArrayType();
8985 const bool IsFunction = T->isFunctionType();
8986
Richard Trieuc1888e02014-06-28 23:25:37 +00008987 // Address of function is used to silence the function warning.
8988 if (IsAddressOf && IsFunction) {
8989 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008990 }
8991
8992 // Found nothing.
8993 if (!IsAddressOf && !IsFunction && !IsArray)
8994 return;
8995
8996 // Pretty print the expression for the diagnostic.
8997 std::string Str;
8998 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00008999 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00009000
9001 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9002 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00009003 enum {
9004 AddressOf,
9005 FunctionPointer,
9006 ArrayPointer
9007 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009008 if (IsAddressOf)
9009 DiagType = AddressOf;
9010 else if (IsFunction)
9011 DiagType = FunctionPointer;
9012 else if (IsArray)
9013 DiagType = ArrayPointer;
9014 else
9015 llvm_unreachable("Could not determine diagnostic.");
9016 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9017 << Range << IsEqual;
9018
9019 if (!IsFunction)
9020 return;
9021
9022 // Suggest '&' to silence the function warning.
9023 Diag(E->getExprLoc(), diag::note_function_warning_silence)
9024 << FixItHint::CreateInsertion(E->getLocStart(), "&");
9025
9026 // Check to see if '()' fixit should be emitted.
9027 QualType ReturnType;
9028 UnresolvedSet<4> NonTemplateOverloads;
9029 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9030 if (ReturnType.isNull())
9031 return;
9032
9033 if (IsCompare) {
9034 // There are two cases here. If there is null constant, the only suggest
9035 // for a pointer return type. If the null is 0, then suggest if the return
9036 // type is a pointer or an integer type.
9037 if (!ReturnType->isPointerType()) {
9038 if (NullKind == Expr::NPCK_ZeroExpression ||
9039 NullKind == Expr::NPCK_ZeroLiteral) {
9040 if (!ReturnType->isIntegerType())
9041 return;
9042 } else {
9043 return;
9044 }
9045 }
9046 } else { // !IsCompare
9047 // For function to bool, only suggest if the function pointer has bool
9048 // return type.
9049 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9050 return;
9051 }
9052 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00009053 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00009054}
9055
John McCallcc7e5bf2010-05-06 08:58:33 +00009056/// Diagnoses "dangerous" implicit conversions within the given
9057/// expression (which is a full expression). Implements -Wconversion
9058/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009059///
9060/// \param CC the "context" location of the implicit conversion, i.e.
9061/// the most location of the syntactic entity requiring the implicit
9062/// conversion
9063void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009064 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00009065 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00009066 return;
9067
9068 // Don't diagnose for value- or type-dependent expressions.
9069 if (E->isTypeDependent() || E->isValueDependent())
9070 return;
9071
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009072 // Check for array bounds violations in cases where the check isn't triggered
9073 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9074 // ArraySubscriptExpr is on the RHS of a variable initialization.
9075 CheckArrayAccess(E);
9076
John McCallacf0ee52010-10-08 02:01:28 +00009077 // This is not the right CC for (e.g.) a variable initialization.
9078 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009079}
9080
Richard Trieu65724892014-11-15 06:37:39 +00009081/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9082/// Input argument E is a logical expression.
9083void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9084 ::CheckBoolLikeConversion(*this, E, CC);
9085}
9086
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009087/// Diagnose when expression is an integer constant expression and its evaluation
9088/// results in integer overflow
9089void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00009090 // Use a work list to deal with nested struct initializers.
9091 SmallVector<Expr *, 2> Exprs(1, E);
9092
9093 do {
9094 Expr *E = Exprs.pop_back_val();
9095
9096 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9097 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9098 continue;
9099 }
9100
9101 if (auto InitList = dyn_cast<InitListExpr>(E))
9102 Exprs.append(InitList->inits().begin(), InitList->inits().end());
9103 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009104}
9105
Richard Smithc406cb72013-01-17 01:17:56 +00009106namespace {
9107/// \brief Visitor for expressions which looks for unsequenced operations on the
9108/// same object.
9109class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009110 typedef EvaluatedExprVisitor<SequenceChecker> Base;
9111
Richard Smithc406cb72013-01-17 01:17:56 +00009112 /// \brief A tree of sequenced regions within an expression. Two regions are
9113 /// unsequenced if one is an ancestor or a descendent of the other. When we
9114 /// finish processing an expression with sequencing, such as a comma
9115 /// expression, we fold its tree nodes into its parent, since they are
9116 /// unsequenced with respect to nodes we will visit later.
9117 class SequenceTree {
9118 struct Value {
9119 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9120 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +00009121 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +00009122 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009123 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00009124
9125 public:
9126 /// \brief A region within an expression which may be sequenced with respect
9127 /// to some other region.
9128 class Seq {
9129 explicit Seq(unsigned N) : Index(N) {}
9130 unsigned Index;
9131 friend class SequenceTree;
9132 public:
9133 Seq() : Index(0) {}
9134 };
9135
9136 SequenceTree() { Values.push_back(Value(0)); }
9137 Seq root() const { return Seq(0); }
9138
9139 /// \brief Create a new sequence of operations, which is an unsequenced
9140 /// subset of \p Parent. This sequence of operations is sequenced with
9141 /// respect to other children of \p Parent.
9142 Seq allocate(Seq Parent) {
9143 Values.push_back(Value(Parent.Index));
9144 return Seq(Values.size() - 1);
9145 }
9146
9147 /// \brief Merge a sequence of operations into its parent.
9148 void merge(Seq S) {
9149 Values[S.Index].Merged = true;
9150 }
9151
9152 /// \brief Determine whether two operations are unsequenced. This operation
9153 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9154 /// should have been merged into its parent as appropriate.
9155 bool isUnsequenced(Seq Cur, Seq Old) {
9156 unsigned C = representative(Cur.Index);
9157 unsigned Target = representative(Old.Index);
9158 while (C >= Target) {
9159 if (C == Target)
9160 return true;
9161 C = Values[C].Parent;
9162 }
9163 return false;
9164 }
9165
9166 private:
9167 /// \brief Pick a representative for a sequence.
9168 unsigned representative(unsigned K) {
9169 if (Values[K].Merged)
9170 // Perform path compression as we go.
9171 return Values[K].Parent = representative(Values[K].Parent);
9172 return K;
9173 }
9174 };
9175
9176 /// An object for which we can track unsequenced uses.
9177 typedef NamedDecl *Object;
9178
9179 /// Different flavors of object usage which we track. We only track the
9180 /// least-sequenced usage of each kind.
9181 enum UsageKind {
9182 /// A read of an object. Multiple unsequenced reads are OK.
9183 UK_Use,
9184 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00009185 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00009186 UK_ModAsValue,
9187 /// A modification of an object which is not sequenced before the value
9188 /// computation of the expression, such as n++.
9189 UK_ModAsSideEffect,
9190
9191 UK_Count = UK_ModAsSideEffect + 1
9192 };
9193
9194 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00009195 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00009196 Expr *Use;
9197 SequenceTree::Seq Seq;
9198 };
9199
9200 struct UsageInfo {
9201 UsageInfo() : Diagnosed(false) {}
9202 Usage Uses[UK_Count];
9203 /// Have we issued a diagnostic for this variable already?
9204 bool Diagnosed;
9205 };
9206 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9207
9208 Sema &SemaRef;
9209 /// Sequenced regions within the expression.
9210 SequenceTree Tree;
9211 /// Declaration modifications and references which we have seen.
9212 UsageInfoMap UsageMap;
9213 /// The region we are currently within.
9214 SequenceTree::Seq Region;
9215 /// Filled in with declarations which were modified as a side-effect
9216 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009217 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00009218 /// Expressions to check later. We defer checking these to reduce
9219 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009220 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00009221
9222 /// RAII object wrapping the visitation of a sequenced subexpression of an
9223 /// expression. At the end of this process, the side-effects of the evaluation
9224 /// become sequenced with respect to the value computation of the result, so
9225 /// we downgrade any UK_ModAsSideEffect within the evaluation to
9226 /// UK_ModAsValue.
9227 struct SequencedSubexpression {
9228 SequencedSubexpression(SequenceChecker &Self)
9229 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9230 Self.ModAsSideEffect = &ModAsSideEffect;
9231 }
9232 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +00009233 for (auto &M : llvm::reverse(ModAsSideEffect)) {
9234 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +00009235 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +00009236 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9237 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +00009238 }
9239 Self.ModAsSideEffect = OldModAsSideEffect;
9240 }
9241
9242 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009243 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9244 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00009245 };
9246
Richard Smith40238f02013-06-20 22:21:56 +00009247 /// RAII object wrapping the visitation of a subexpression which we might
9248 /// choose to evaluate as a constant. If any subexpression is evaluated and
9249 /// found to be non-constant, this allows us to suppress the evaluation of
9250 /// the outer expression.
9251 class EvaluationTracker {
9252 public:
9253 EvaluationTracker(SequenceChecker &Self)
9254 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9255 Self.EvalTracker = this;
9256 }
9257 ~EvaluationTracker() {
9258 Self.EvalTracker = Prev;
9259 if (Prev)
9260 Prev->EvalOK &= EvalOK;
9261 }
9262
9263 bool evaluate(const Expr *E, bool &Result) {
9264 if (!EvalOK || E->isValueDependent())
9265 return false;
9266 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9267 return EvalOK;
9268 }
9269
9270 private:
9271 SequenceChecker &Self;
9272 EvaluationTracker *Prev;
9273 bool EvalOK;
9274 } *EvalTracker;
9275
Richard Smithc406cb72013-01-17 01:17:56 +00009276 /// \brief Find the object which is produced by the specified expression,
9277 /// if any.
9278 Object getObject(Expr *E, bool Mod) const {
9279 E = E->IgnoreParenCasts();
9280 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9281 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9282 return getObject(UO->getSubExpr(), Mod);
9283 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9284 if (BO->getOpcode() == BO_Comma)
9285 return getObject(BO->getRHS(), Mod);
9286 if (Mod && BO->isAssignmentOp())
9287 return getObject(BO->getLHS(), Mod);
9288 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9289 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9290 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9291 return ME->getMemberDecl();
9292 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9293 // FIXME: If this is a reference, map through to its value.
9294 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00009295 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00009296 }
9297
9298 /// \brief Note that an object was modified or used by an expression.
9299 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9300 Usage &U = UI.Uses[UK];
9301 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9302 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9303 ModAsSideEffect->push_back(std::make_pair(O, U));
9304 U.Use = Ref;
9305 U.Seq = Region;
9306 }
9307 }
9308 /// \brief Check whether a modification or use conflicts with a prior usage.
9309 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9310 bool IsModMod) {
9311 if (UI.Diagnosed)
9312 return;
9313
9314 const Usage &U = UI.Uses[OtherKind];
9315 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9316 return;
9317
9318 Expr *Mod = U.Use;
9319 Expr *ModOrUse = Ref;
9320 if (OtherKind == UK_Use)
9321 std::swap(Mod, ModOrUse);
9322
9323 SemaRef.Diag(Mod->getExprLoc(),
9324 IsModMod ? diag::warn_unsequenced_mod_mod
9325 : diag::warn_unsequenced_mod_use)
9326 << O << SourceRange(ModOrUse->getExprLoc());
9327 UI.Diagnosed = true;
9328 }
9329
9330 void notePreUse(Object O, Expr *Use) {
9331 UsageInfo &U = UsageMap[O];
9332 // Uses conflict with other modifications.
9333 checkUsage(O, U, Use, UK_ModAsValue, false);
9334 }
9335 void notePostUse(Object O, Expr *Use) {
9336 UsageInfo &U = UsageMap[O];
9337 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9338 addUsage(U, O, Use, UK_Use);
9339 }
9340
9341 void notePreMod(Object O, Expr *Mod) {
9342 UsageInfo &U = UsageMap[O];
9343 // Modifications conflict with other modifications and with uses.
9344 checkUsage(O, U, Mod, UK_ModAsValue, true);
9345 checkUsage(O, U, Mod, UK_Use, false);
9346 }
9347 void notePostMod(Object O, Expr *Use, UsageKind UK) {
9348 UsageInfo &U = UsageMap[O];
9349 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9350 addUsage(U, O, Use, UK);
9351 }
9352
9353public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009354 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00009355 : Base(S.Context), SemaRef(S), Region(Tree.root()),
9356 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009357 Visit(E);
9358 }
9359
9360 void VisitStmt(Stmt *S) {
9361 // Skip all statements which aren't expressions for now.
9362 }
9363
9364 void VisitExpr(Expr *E) {
9365 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00009366 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00009367 }
9368
9369 void VisitCastExpr(CastExpr *E) {
9370 Object O = Object();
9371 if (E->getCastKind() == CK_LValueToRValue)
9372 O = getObject(E->getSubExpr(), false);
9373
9374 if (O)
9375 notePreUse(O, E);
9376 VisitExpr(E);
9377 if (O)
9378 notePostUse(O, E);
9379 }
9380
9381 void VisitBinComma(BinaryOperator *BO) {
9382 // C++11 [expr.comma]p1:
9383 // Every value computation and side effect associated with the left
9384 // expression is sequenced before every value computation and side
9385 // effect associated with the right expression.
9386 SequenceTree::Seq LHS = Tree.allocate(Region);
9387 SequenceTree::Seq RHS = Tree.allocate(Region);
9388 SequenceTree::Seq OldRegion = Region;
9389
9390 {
9391 SequencedSubexpression SeqLHS(*this);
9392 Region = LHS;
9393 Visit(BO->getLHS());
9394 }
9395
9396 Region = RHS;
9397 Visit(BO->getRHS());
9398
9399 Region = OldRegion;
9400
9401 // Forget that LHS and RHS are sequenced. They are both unsequenced
9402 // with respect to other stuff.
9403 Tree.merge(LHS);
9404 Tree.merge(RHS);
9405 }
9406
9407 void VisitBinAssign(BinaryOperator *BO) {
9408 // The modification is sequenced after the value computation of the LHS
9409 // and RHS, so check it before inspecting the operands and update the
9410 // map afterwards.
9411 Object O = getObject(BO->getLHS(), true);
9412 if (!O)
9413 return VisitExpr(BO);
9414
9415 notePreMod(O, BO);
9416
9417 // C++11 [expr.ass]p7:
9418 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
9419 // only once.
9420 //
9421 // Therefore, for a compound assignment operator, O is considered used
9422 // everywhere except within the evaluation of E1 itself.
9423 if (isa<CompoundAssignOperator>(BO))
9424 notePreUse(O, BO);
9425
9426 Visit(BO->getLHS());
9427
9428 if (isa<CompoundAssignOperator>(BO))
9429 notePostUse(O, BO);
9430
9431 Visit(BO->getRHS());
9432
Richard Smith83e37bee2013-06-26 23:16:51 +00009433 // C++11 [expr.ass]p1:
9434 // the assignment is sequenced [...] before the value computation of the
9435 // assignment expression.
9436 // C11 6.5.16/3 has no such rule.
9437 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9438 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00009439 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009440
Richard Smithc406cb72013-01-17 01:17:56 +00009441 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
9442 VisitBinAssign(CAO);
9443 }
9444
9445 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9446 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9447 void VisitUnaryPreIncDec(UnaryOperator *UO) {
9448 Object O = getObject(UO->getSubExpr(), true);
9449 if (!O)
9450 return VisitExpr(UO);
9451
9452 notePreMod(O, UO);
9453 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00009454 // C++11 [expr.pre.incr]p1:
9455 // the expression ++x is equivalent to x+=1
9456 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9457 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00009458 }
9459
9460 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9461 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9462 void VisitUnaryPostIncDec(UnaryOperator *UO) {
9463 Object O = getObject(UO->getSubExpr(), true);
9464 if (!O)
9465 return VisitExpr(UO);
9466
9467 notePreMod(O, UO);
9468 Visit(UO->getSubExpr());
9469 notePostMod(O, UO, UK_ModAsSideEffect);
9470 }
9471
9472 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
9473 void VisitBinLOr(BinaryOperator *BO) {
9474 // The side-effects of the LHS of an '&&' are sequenced before the
9475 // value computation of the RHS, and hence before the value computation
9476 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
9477 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00009478 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00009479 {
9480 SequencedSubexpression Sequenced(*this);
9481 Visit(BO->getLHS());
9482 }
9483
9484 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009485 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00009486 if (!Result)
9487 Visit(BO->getRHS());
9488 } else {
9489 // Check for unsequenced operations in the RHS, treating it as an
9490 // entirely separate evaluation.
9491 //
9492 // FIXME: If there are operations in the RHS which are unsequenced
9493 // with respect to operations outside the RHS, and those operations
9494 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00009495 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00009496 }
Richard Smithc406cb72013-01-17 01:17:56 +00009497 }
9498 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00009499 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00009500 {
9501 SequencedSubexpression Sequenced(*this);
9502 Visit(BO->getLHS());
9503 }
9504
9505 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009506 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00009507 if (Result)
9508 Visit(BO->getRHS());
9509 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00009510 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00009511 }
Richard Smithc406cb72013-01-17 01:17:56 +00009512 }
9513
9514 // Only visit the condition, unless we can be sure which subexpression will
9515 // be chosen.
9516 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00009517 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00009518 {
9519 SequencedSubexpression Sequenced(*this);
9520 Visit(CO->getCond());
9521 }
Richard Smithc406cb72013-01-17 01:17:56 +00009522
9523 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009524 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00009525 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00009526 else {
Richard Smithd33f5202013-01-17 23:18:09 +00009527 WorkList.push_back(CO->getTrueExpr());
9528 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00009529 }
Richard Smithc406cb72013-01-17 01:17:56 +00009530 }
9531
Richard Smithe3dbfe02013-06-30 10:40:20 +00009532 void VisitCallExpr(CallExpr *CE) {
9533 // C++11 [intro.execution]p15:
9534 // When calling a function [...], every value computation and side effect
9535 // associated with any argument expression, or with the postfix expression
9536 // designating the called function, is sequenced before execution of every
9537 // expression or statement in the body of the function [and thus before
9538 // the value computation of its result].
9539 SequencedSubexpression Sequenced(*this);
9540 Base::VisitCallExpr(CE);
9541
9542 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
9543 }
9544
Richard Smithc406cb72013-01-17 01:17:56 +00009545 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009546 // This is a call, so all subexpressions are sequenced before the result.
9547 SequencedSubexpression Sequenced(*this);
9548
Richard Smithc406cb72013-01-17 01:17:56 +00009549 if (!CCE->isListInitialization())
9550 return VisitExpr(CCE);
9551
9552 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009553 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00009554 SequenceTree::Seq Parent = Region;
9555 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
9556 E = CCE->arg_end();
9557 I != E; ++I) {
9558 Region = Tree.allocate(Parent);
9559 Elts.push_back(Region);
9560 Visit(*I);
9561 }
9562
9563 // Forget that the initializers are sequenced.
9564 Region = Parent;
9565 for (unsigned I = 0; I < Elts.size(); ++I)
9566 Tree.merge(Elts[I]);
9567 }
9568
9569 void VisitInitListExpr(InitListExpr *ILE) {
9570 if (!SemaRef.getLangOpts().CPlusPlus11)
9571 return VisitExpr(ILE);
9572
9573 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009574 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00009575 SequenceTree::Seq Parent = Region;
9576 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
9577 Expr *E = ILE->getInit(I);
9578 if (!E) continue;
9579 Region = Tree.allocate(Parent);
9580 Elts.push_back(Region);
9581 Visit(E);
9582 }
9583
9584 // Forget that the initializers are sequenced.
9585 Region = Parent;
9586 for (unsigned I = 0; I < Elts.size(); ++I)
9587 Tree.merge(Elts[I]);
9588 }
9589};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009590} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +00009591
9592void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009593 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00009594 WorkList.push_back(E);
9595 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00009596 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00009597 SequenceChecker(*this, Item, WorkList);
9598 }
Richard Smithc406cb72013-01-17 01:17:56 +00009599}
9600
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009601void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
9602 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009603 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +00009604 if (!E->isInstantiationDependent())
9605 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009606 if (!IsConstexpr && !E->isValueDependent())
9607 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009608 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +00009609}
9610
John McCall1f425642010-11-11 03:21:53 +00009611void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
9612 FieldDecl *BitField,
9613 Expr *Init) {
9614 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
9615}
9616
David Majnemer61a5bbf2015-04-07 22:08:51 +00009617static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
9618 SourceLocation Loc) {
9619 if (!PType->isVariablyModifiedType())
9620 return;
9621 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
9622 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
9623 return;
9624 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00009625 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
9626 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
9627 return;
9628 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00009629 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
9630 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
9631 return;
9632 }
9633
9634 const ArrayType *AT = S.Context.getAsArrayType(PType);
9635 if (!AT)
9636 return;
9637
9638 if (AT->getSizeModifier() != ArrayType::Star) {
9639 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
9640 return;
9641 }
9642
9643 S.Diag(Loc, diag::err_array_star_in_function_definition);
9644}
9645
Mike Stump0c2ec772010-01-21 03:59:47 +00009646/// CheckParmsForFunctionDef - Check that the parameters of the given
9647/// function are appropriate for the definition of a function. This
9648/// takes care of any checks that cannot be performed on the
9649/// declaration itself, e.g., that the types of each of the function
9650/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +00009651bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +00009652 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009653 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +00009654 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009655 // C99 6.7.5.3p4: the parameters in a parameter type list in a
9656 // function declarator that is part of a function definition of
9657 // that function shall not have incomplete type.
9658 //
9659 // This is also C++ [dcl.fct]p6.
9660 if (!Param->isInvalidDecl() &&
9661 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009662 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009663 Param->setInvalidDecl();
9664 HasInvalidParm = true;
9665 }
9666
9667 // C99 6.9.1p5: If the declarator includes a parameter type list, the
9668 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00009669 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00009670 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00009671 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00009672 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00009673 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00009674
9675 // C99 6.7.5.3p12:
9676 // If the function declarator is not part of a definition of that
9677 // function, parameters may have incomplete type and may use the [*]
9678 // notation in their sequences of declarator specifiers to specify
9679 // variable length array types.
9680 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00009681 // FIXME: This diagnostic should point the '[*]' if source-location
9682 // information is added for it.
9683 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00009684
9685 // MSVC destroys objects passed by value in the callee. Therefore a
9686 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00009687 // object's destructor. However, we don't perform any direct access check
9688 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00009689 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
9690 .getCXXABI()
9691 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00009692 if (!Param->isInvalidDecl()) {
9693 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
9694 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
9695 if (!ClassDecl->isInvalidDecl() &&
9696 !ClassDecl->hasIrrelevantDestructor() &&
9697 !ClassDecl->isDependentContext()) {
9698 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9699 MarkFunctionReferenced(Param->getLocation(), Destructor);
9700 DiagnoseUseOfDecl(Destructor, Param->getLocation());
9701 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00009702 }
9703 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00009704 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009705
9706 // Parameters with the pass_object_size attribute only need to be marked
9707 // constant at function definitions. Because we lack information about
9708 // whether we're on a declaration or definition when we're instantiating the
9709 // attribute, we need to check for constness here.
9710 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
9711 if (!Param->getType().isConstQualified())
9712 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
9713 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +00009714 }
9715
9716 return HasInvalidParm;
9717}
John McCall2b5c1b22010-08-12 21:44:57 +00009718
9719/// CheckCastAlign - Implements -Wcast-align, which warns when a
9720/// pointer cast increases the alignment requirements.
9721void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
9722 // This is actually a lot of work to potentially be doing on every
9723 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009724 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00009725 return;
9726
9727 // Ignore dependent types.
9728 if (T->isDependentType() || Op->getType()->isDependentType())
9729 return;
9730
9731 // Require that the destination be a pointer type.
9732 const PointerType *DestPtr = T->getAs<PointerType>();
9733 if (!DestPtr) return;
9734
9735 // If the destination has alignment 1, we're done.
9736 QualType DestPointee = DestPtr->getPointeeType();
9737 if (DestPointee->isIncompleteType()) return;
9738 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
9739 if (DestAlign.isOne()) return;
9740
9741 // Require that the source be a pointer type.
9742 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
9743 if (!SrcPtr) return;
9744 QualType SrcPointee = SrcPtr->getPointeeType();
9745
9746 // Whitelist casts from cv void*. We already implicitly
9747 // whitelisted casts to cv void*, since they have alignment 1.
9748 // Also whitelist casts involving incomplete types, which implicitly
9749 // includes 'void'.
9750 if (SrcPointee->isIncompleteType()) return;
9751
9752 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
9753 if (SrcAlign >= DestAlign) return;
9754
9755 Diag(TRange.getBegin(), diag::warn_cast_align)
9756 << Op->getType() << T
9757 << static_cast<unsigned>(SrcAlign.getQuantity())
9758 << static_cast<unsigned>(DestAlign.getQuantity())
9759 << TRange << Op->getSourceRange();
9760}
9761
Chandler Carruth28389f02011-08-05 09:10:50 +00009762/// \brief Check whether this array fits the idiom of a size-one tail padded
9763/// array member of a struct.
9764///
9765/// We avoid emitting out-of-bounds access warnings for such arrays as they are
9766/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +00009767static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +00009768 const NamedDecl *ND) {
9769 if (Size != 1 || !ND) return false;
9770
9771 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
9772 if (!FD) return false;
9773
9774 // Don't consider sizes resulting from macro expansions or template argument
9775 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00009776
9777 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009778 while (TInfo) {
9779 TypeLoc TL = TInfo->getTypeLoc();
9780 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00009781 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
9782 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009783 TInfo = TDL->getTypeSourceInfo();
9784 continue;
9785 }
David Blaikie6adc78e2013-02-18 22:06:02 +00009786 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
9787 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00009788 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
9789 return false;
9790 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009791 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00009792 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009793
9794 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00009795 if (!RD) return false;
9796 if (RD->isUnion()) return false;
9797 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9798 if (!CRD->isStandardLayout()) return false;
9799 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009800
Benjamin Kramer8c543672011-08-06 03:04:42 +00009801 // See if this is the last field decl in the record.
9802 const Decl *D = FD;
9803 while ((D = D->getNextDeclInContext()))
9804 if (isa<FieldDecl>(D))
9805 return false;
9806 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00009807}
9808
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009809void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009810 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00009811 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009812 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009813 if (IndexExpr->isValueDependent())
9814 return;
9815
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009816 const Type *EffectiveType =
9817 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009818 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009819 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009820 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009821 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00009822 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00009823
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009824 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +00009825 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +00009826 return;
Richard Smith13f67182011-12-16 19:31:14 +00009827 if (IndexNegated)
9828 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00009829
Craig Topperc3ec1492014-05-26 06:22:03 +00009830 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00009831 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9832 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00009833 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00009834 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00009835
Ted Kremeneke4b316c2011-02-23 23:06:04 +00009836 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009837 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00009838 if (!size.isStrictlyPositive())
9839 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009840
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009841 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +00009842 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009843 // Make sure we're comparing apples to apples when comparing index to size
9844 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
9845 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00009846 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00009847 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009848 if (ptrarith_typesize != array_typesize) {
9849 // There's a cast to a different size type involved
9850 uint64_t ratio = array_typesize / ptrarith_typesize;
9851 // TODO: Be smarter about handling cases where array_typesize is not a
9852 // multiple of ptrarith_typesize
9853 if (ptrarith_typesize * ratio == array_typesize)
9854 size *= llvm::APInt(size.getBitWidth(), ratio);
9855 }
9856 }
9857
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009858 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009859 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009860 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009861 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009862
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009863 // For array subscripting the index must be less than size, but for pointer
9864 // arithmetic also allow the index (offset) to be equal to size since
9865 // computing the next address after the end of the array is legal and
9866 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009867 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00009868 return;
9869
9870 // Also don't warn for arrays of size 1 which are members of some
9871 // structure. These are often used to approximate flexible arrays in C89
9872 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009873 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00009874 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009875
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009876 // Suppress the warning if the subscript expression (as identified by the
9877 // ']' location) and the index expression are both from macro expansions
9878 // within a system header.
9879 if (ASE) {
9880 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
9881 ASE->getRBracketLoc());
9882 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
9883 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
9884 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00009885 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009886 return;
9887 }
9888 }
9889
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009890 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009891 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009892 DiagID = diag::warn_array_index_exceeds_bounds;
9893
9894 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9895 PDiag(DiagID) << index.toString(10, true)
9896 << size.toString(10, true)
9897 << (unsigned)size.getLimitedValue(~0U)
9898 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009899 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009900 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009901 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009902 DiagID = diag::warn_ptr_arith_precedes_bounds;
9903 if (index.isNegative()) index = -index;
9904 }
9905
9906 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9907 PDiag(DiagID) << index.toString(10, true)
9908 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00009909 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00009910
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00009911 if (!ND) {
9912 // Try harder to find a NamedDecl to point at in the note.
9913 while (const ArraySubscriptExpr *ASE =
9914 dyn_cast<ArraySubscriptExpr>(BaseExpr))
9915 BaseExpr = ASE->getBase()->IgnoreParenCasts();
9916 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9917 ND = dyn_cast<NamedDecl>(DRE->getDecl());
9918 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9919 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9920 }
9921
Chandler Carruth1af88f12011-02-17 21:10:52 +00009922 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009923 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
9924 PDiag(diag::note_array_index_out_of_bounds)
9925 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00009926}
9927
Ted Kremenekdf26df72011-03-01 18:41:00 +00009928void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009929 int AllowOnePastEnd = 0;
9930 while (expr) {
9931 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00009932 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009933 case Stmt::ArraySubscriptExprClass: {
9934 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009935 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009936 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00009937 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009938 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009939 case Stmt::OMPArraySectionExprClass: {
9940 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
9941 if (ASE->getLowerBound())
9942 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
9943 /*ASE=*/nullptr, AllowOnePastEnd > 0);
9944 return;
9945 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009946 case Stmt::UnaryOperatorClass: {
9947 // Only unwrap the * and & unary operators
9948 const UnaryOperator *UO = cast<UnaryOperator>(expr);
9949 expr = UO->getSubExpr();
9950 switch (UO->getOpcode()) {
9951 case UO_AddrOf:
9952 AllowOnePastEnd++;
9953 break;
9954 case UO_Deref:
9955 AllowOnePastEnd--;
9956 break;
9957 default:
9958 return;
9959 }
9960 break;
9961 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009962 case Stmt::ConditionalOperatorClass: {
9963 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
9964 if (const Expr *lhs = cond->getLHS())
9965 CheckArrayAccess(lhs);
9966 if (const Expr *rhs = cond->getRHS())
9967 CheckArrayAccess(rhs);
9968 return;
9969 }
9970 default:
9971 return;
9972 }
Peter Collingbourne91147592011-04-15 00:35:48 +00009973 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009974}
John McCall31168b02011-06-15 23:02:42 +00009975
9976//===--- CHECK: Objective-C retain cycles ----------------------------------//
9977
9978namespace {
9979 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00009980 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00009981 VarDecl *Variable;
9982 SourceRange Range;
9983 SourceLocation Loc;
9984 bool Indirect;
9985
9986 void setLocsFrom(Expr *e) {
9987 Loc = e->getExprLoc();
9988 Range = e->getSourceRange();
9989 }
9990 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009991} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009992
9993/// Consider whether capturing the given variable can possibly lead to
9994/// a retain cycle.
9995static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00009996 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00009997 // lifetime. In MRR, it's captured strongly if the variable is
9998 // __block and has an appropriate type.
9999 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10000 return false;
10001
10002 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010003 if (ref)
10004 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000010005 return true;
10006}
10007
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010008static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000010009 while (true) {
10010 e = e->IgnoreParens();
10011 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10012 switch (cast->getCastKind()) {
10013 case CK_BitCast:
10014 case CK_LValueBitCast:
10015 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000010016 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000010017 e = cast->getSubExpr();
10018 continue;
10019
John McCall31168b02011-06-15 23:02:42 +000010020 default:
10021 return false;
10022 }
10023 }
10024
10025 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10026 ObjCIvarDecl *ivar = ref->getDecl();
10027 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10028 return false;
10029
10030 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010031 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000010032 return false;
10033
10034 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10035 owner.Indirect = true;
10036 return true;
10037 }
10038
10039 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10040 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10041 if (!var) return false;
10042 return considerVariable(var, ref, owner);
10043 }
10044
John McCall31168b02011-06-15 23:02:42 +000010045 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10046 if (member->isArrow()) return false;
10047
10048 // Don't count this as an indirect ownership.
10049 e = member->getBase();
10050 continue;
10051 }
10052
John McCallfe96e0b2011-11-06 09:01:30 +000010053 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10054 // Only pay attention to pseudo-objects on property references.
10055 ObjCPropertyRefExpr *pre
10056 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10057 ->IgnoreParens());
10058 if (!pre) return false;
10059 if (pre->isImplicitProperty()) return false;
10060 ObjCPropertyDecl *property = pre->getExplicitProperty();
10061 if (!property->isRetaining() &&
10062 !(property->getPropertyIvarDecl() &&
10063 property->getPropertyIvarDecl()->getType()
10064 .getObjCLifetime() == Qualifiers::OCL_Strong))
10065 return false;
10066
10067 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010068 if (pre->isSuperReceiver()) {
10069 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10070 if (!owner.Variable)
10071 return false;
10072 owner.Loc = pre->getLocation();
10073 owner.Range = pre->getSourceRange();
10074 return true;
10075 }
John McCallfe96e0b2011-11-06 09:01:30 +000010076 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10077 ->getSourceExpr());
10078 continue;
10079 }
10080
John McCall31168b02011-06-15 23:02:42 +000010081 // Array ivars?
10082
10083 return false;
10084 }
10085}
10086
10087namespace {
10088 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10089 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10090 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010091 Context(Context), Variable(variable), Capturer(nullptr),
10092 VarWillBeReased(false) {}
10093 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000010094 VarDecl *Variable;
10095 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010096 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +000010097
10098 void VisitDeclRefExpr(DeclRefExpr *ref) {
10099 if (ref->getDecl() == Variable && !Capturer)
10100 Capturer = ref;
10101 }
10102
John McCall31168b02011-06-15 23:02:42 +000010103 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10104 if (Capturer) return;
10105 Visit(ref->getBase());
10106 if (Capturer && ref->isFreeIvar())
10107 Capturer = ref;
10108 }
10109
10110 void VisitBlockExpr(BlockExpr *block) {
10111 // Look inside nested blocks
10112 if (block->getBlockDecl()->capturesVariable(Variable))
10113 Visit(block->getBlockDecl()->getBody());
10114 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000010115
10116 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
10117 if (Capturer) return;
10118 if (OVE->getSourceExpr())
10119 Visit(OVE->getSourceExpr());
10120 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010121 void VisitBinaryOperator(BinaryOperator *BinOp) {
10122 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
10123 return;
10124 Expr *LHS = BinOp->getLHS();
10125 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
10126 if (DRE->getDecl() != Variable)
10127 return;
10128 if (Expr *RHS = BinOp->getRHS()) {
10129 RHS = RHS->IgnoreParenCasts();
10130 llvm::APSInt Value;
10131 VarWillBeReased =
10132 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
10133 }
10134 }
10135 }
John McCall31168b02011-06-15 23:02:42 +000010136 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010137} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010138
10139/// Check whether the given argument is a block which captures a
10140/// variable.
10141static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
10142 assert(owner.Variable && owner.Loc.isValid());
10143
10144 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000010145
10146 // Look through [^{...} copy] and Block_copy(^{...}).
10147 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
10148 Selector Cmd = ME->getSelector();
10149 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
10150 e = ME->getInstanceReceiver();
10151 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000010152 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000010153 e = e->IgnoreParenCasts();
10154 }
10155 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
10156 if (CE->getNumArgs() == 1) {
10157 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000010158 if (Fn) {
10159 const IdentifierInfo *FnI = Fn->getIdentifier();
10160 if (FnI && FnI->isStr("_Block_copy")) {
10161 e = CE->getArg(0)->IgnoreParenCasts();
10162 }
10163 }
Jordan Rose67e887c2012-09-17 17:54:30 +000010164 }
10165 }
10166
John McCall31168b02011-06-15 23:02:42 +000010167 BlockExpr *block = dyn_cast<BlockExpr>(e);
10168 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000010169 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000010170
10171 FindCaptureVisitor visitor(S.Context, owner.Variable);
10172 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010173 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000010174}
10175
10176static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10177 RetainCycleOwner &owner) {
10178 assert(capturer);
10179 assert(owner.Variable && owner.Loc.isValid());
10180
10181 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10182 << owner.Variable << capturer->getSourceRange();
10183 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10184 << owner.Indirect << owner.Range;
10185}
10186
10187/// Check for a keyword selector that starts with the word 'add' or
10188/// 'set'.
10189static bool isSetterLikeSelector(Selector sel) {
10190 if (sel.isUnarySelector()) return false;
10191
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010192 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000010193 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010194 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000010195 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010196 else if (str.startswith("add")) {
10197 // Specially whitelist 'addOperationWithBlock:'.
10198 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
10199 return false;
10200 str = str.substr(3);
10201 }
John McCall31168b02011-06-15 23:02:42 +000010202 else
10203 return false;
10204
10205 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000010206 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000010207}
10208
Benjamin Kramer3a743452015-03-09 15:03:32 +000010209static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
10210 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010211 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
10212 Message->getReceiverInterface(),
10213 NSAPI::ClassId_NSMutableArray);
10214 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010215 return None;
10216 }
10217
10218 Selector Sel = Message->getSelector();
10219
10220 Optional<NSAPI::NSArrayMethodKind> MKOpt =
10221 S.NSAPIObj->getNSArrayMethodKind(Sel);
10222 if (!MKOpt) {
10223 return None;
10224 }
10225
10226 NSAPI::NSArrayMethodKind MK = *MKOpt;
10227
10228 switch (MK) {
10229 case NSAPI::NSMutableArr_addObject:
10230 case NSAPI::NSMutableArr_insertObjectAtIndex:
10231 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
10232 return 0;
10233 case NSAPI::NSMutableArr_replaceObjectAtIndex:
10234 return 1;
10235
10236 default:
10237 return None;
10238 }
10239
10240 return None;
10241}
10242
10243static
10244Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10245 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010246 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10247 Message->getReceiverInterface(),
10248 NSAPI::ClassId_NSMutableDictionary);
10249 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010250 return None;
10251 }
10252
10253 Selector Sel = Message->getSelector();
10254
10255 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10256 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10257 if (!MKOpt) {
10258 return None;
10259 }
10260
10261 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10262
10263 switch (MK) {
10264 case NSAPI::NSMutableDict_setObjectForKey:
10265 case NSAPI::NSMutableDict_setValueForKey:
10266 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10267 return 0;
10268
10269 default:
10270 return None;
10271 }
10272
10273 return None;
10274}
10275
10276static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010277 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10278 Message->getReceiverInterface(),
10279 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000010280
Alex Denisov5dfac812015-08-06 04:51:14 +000010281 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10282 Message->getReceiverInterface(),
10283 NSAPI::ClassId_NSMutableOrderedSet);
10284 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010285 return None;
10286 }
10287
10288 Selector Sel = Message->getSelector();
10289
10290 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10291 if (!MKOpt) {
10292 return None;
10293 }
10294
10295 NSAPI::NSSetMethodKind MK = *MKOpt;
10296
10297 switch (MK) {
10298 case NSAPI::NSMutableSet_addObject:
10299 case NSAPI::NSOrderedSet_setObjectAtIndex:
10300 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10301 case NSAPI::NSOrderedSet_insertObjectAtIndex:
10302 return 0;
10303 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10304 return 1;
10305 }
10306
10307 return None;
10308}
10309
10310void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10311 if (!Message->isInstanceMessage()) {
10312 return;
10313 }
10314
10315 Optional<int> ArgOpt;
10316
10317 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10318 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10319 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10320 return;
10321 }
10322
10323 int ArgIndex = *ArgOpt;
10324
Alex Denisove1d882c2015-03-04 17:55:52 +000010325 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10326 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10327 Arg = OE->getSourceExpr()->IgnoreImpCasts();
10328 }
10329
Alex Denisov5dfac812015-08-06 04:51:14 +000010330 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010331 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010332 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010333 Diag(Message->getSourceRange().getBegin(),
10334 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000010335 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000010336 }
10337 }
Alex Denisov5dfac812015-08-06 04:51:14 +000010338 } else {
10339 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10340
10341 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10342 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10343 }
10344
10345 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10346 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10347 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10348 ValueDecl *Decl = ReceiverRE->getDecl();
10349 Diag(Message->getSourceRange().getBegin(),
10350 diag::warn_objc_circular_container)
10351 << Decl->getName() << Decl->getName();
10352 if (!ArgRE->isObjCSelfExpr()) {
10353 Diag(Decl->getLocation(),
10354 diag::note_objc_circular_container_declared_here)
10355 << Decl->getName();
10356 }
10357 }
10358 }
10359 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
10360 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
10361 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
10362 ObjCIvarDecl *Decl = IvarRE->getDecl();
10363 Diag(Message->getSourceRange().getBegin(),
10364 diag::warn_objc_circular_container)
10365 << Decl->getName() << Decl->getName();
10366 Diag(Decl->getLocation(),
10367 diag::note_objc_circular_container_declared_here)
10368 << Decl->getName();
10369 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010370 }
10371 }
10372 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010373}
10374
John McCall31168b02011-06-15 23:02:42 +000010375/// Check a message send to see if it's likely to cause a retain cycle.
10376void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
10377 // Only check instance methods whose selector looks like a setter.
10378 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
10379 return;
10380
10381 // Try to find a variable that the receiver is strongly owned by.
10382 RetainCycleOwner owner;
10383 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010384 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000010385 return;
10386 } else {
10387 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
10388 owner.Variable = getCurMethodDecl()->getSelfDecl();
10389 owner.Loc = msg->getSuperLoc();
10390 owner.Range = msg->getSuperLoc();
10391 }
10392
10393 // Check whether the receiver is captured by any of the arguments.
10394 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
10395 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
10396 return diagnoseRetainCycle(*this, capturer, owner);
10397}
10398
10399/// Check a property assign to see if it's likely to cause a retain cycle.
10400void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
10401 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010402 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000010403 return;
10404
10405 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
10406 diagnoseRetainCycle(*this, capturer, owner);
10407}
10408
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010409void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
10410 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000010411 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010412 return;
10413
10414 // Because we don't have an expression for the variable, we have to set the
10415 // location explicitly here.
10416 Owner.Loc = Var->getLocation();
10417 Owner.Range = Var->getSourceRange();
10418
10419 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
10420 diagnoseRetainCycle(*this, Capturer, Owner);
10421}
10422
Ted Kremenek9304da92012-12-21 08:04:28 +000010423static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
10424 Expr *RHS, bool isProperty) {
10425 // Check if RHS is an Objective-C object literal, which also can get
10426 // immediately zapped in a weak reference. Note that we explicitly
10427 // allow ObjCStringLiterals, since those are designed to never really die.
10428 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010429
Ted Kremenek64873352012-12-21 22:46:35 +000010430 // This enum needs to match with the 'select' in
10431 // warn_objc_arc_literal_assign (off-by-1).
10432 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
10433 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
10434 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010435
10436 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000010437 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000010438 << (isProperty ? 0 : 1)
10439 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010440
10441 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000010442}
10443
Ted Kremenekc1f014a2012-12-21 19:45:30 +000010444static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
10445 Qualifiers::ObjCLifetime LT,
10446 Expr *RHS, bool isProperty) {
10447 // Strip off any implicit cast added to get to the one ARC-specific.
10448 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
10449 if (cast->getCastKind() == CK_ARCConsumeObject) {
10450 S.Diag(Loc, diag::warn_arc_retained_assign)
10451 << (LT == Qualifiers::OCL_ExplicitNone)
10452 << (isProperty ? 0 : 1)
10453 << RHS->getSourceRange();
10454 return true;
10455 }
10456 RHS = cast->getSubExpr();
10457 }
10458
10459 if (LT == Qualifiers::OCL_Weak &&
10460 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
10461 return true;
10462
10463 return false;
10464}
10465
Ted Kremenekb36234d2012-12-21 08:04:20 +000010466bool Sema::checkUnsafeAssigns(SourceLocation Loc,
10467 QualType LHS, Expr *RHS) {
10468 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
10469
10470 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
10471 return false;
10472
10473 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
10474 return true;
10475
10476 return false;
10477}
10478
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010479void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
10480 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010481 QualType LHSType;
10482 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010483 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010484 ObjCPropertyRefExpr *PRE
10485 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
10486 if (PRE && !PRE->isImplicitProperty()) {
10487 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10488 if (PD)
10489 LHSType = PD->getType();
10490 }
10491
10492 if (LHSType.isNull())
10493 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000010494
10495 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
10496
10497 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010498 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000010499 getCurFunction()->markSafeWeakUse(LHS);
10500 }
10501
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010502 if (checkUnsafeAssigns(Loc, LHSType, RHS))
10503 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000010504
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010505 // FIXME. Check for other life times.
10506 if (LT != Qualifiers::OCL_None)
10507 return;
10508
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010509 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010510 if (PRE->isImplicitProperty())
10511 return;
10512 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10513 if (!PD)
10514 return;
10515
Bill Wendling44426052012-12-20 19:22:21 +000010516 unsigned Attributes = PD->getPropertyAttributes();
10517 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010518 // when 'assign' attribute was not explicitly specified
10519 // by user, ignore it and rely on property type itself
10520 // for lifetime info.
10521 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
10522 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
10523 LHSType->isObjCRetainableType())
10524 return;
10525
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010526 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000010527 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010528 Diag(Loc, diag::warn_arc_retained_property_assign)
10529 << RHS->getSourceRange();
10530 return;
10531 }
10532 RHS = cast->getSubExpr();
10533 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010534 }
Bill Wendling44426052012-12-20 19:22:21 +000010535 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000010536 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
10537 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000010538 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010539 }
10540}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010541
10542//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
10543
10544namespace {
10545bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
10546 SourceLocation StmtLoc,
10547 const NullStmt *Body) {
10548 // Do not warn if the body is a macro that expands to nothing, e.g:
10549 //
10550 // #define CALL(x)
10551 // if (condition)
10552 // CALL(0);
10553 //
10554 if (Body->hasLeadingEmptyMacro())
10555 return false;
10556
10557 // Get line numbers of statement and body.
10558 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000010559 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010560 &StmtLineInvalid);
10561 if (StmtLineInvalid)
10562 return false;
10563
10564 bool BodyLineInvalid;
10565 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
10566 &BodyLineInvalid);
10567 if (BodyLineInvalid)
10568 return false;
10569
10570 // Warn if null statement and body are on the same line.
10571 if (StmtLine != BodyLine)
10572 return false;
10573
10574 return true;
10575}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010576} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010577
10578void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
10579 const Stmt *Body,
10580 unsigned DiagID) {
10581 // Since this is a syntactic check, don't emit diagnostic for template
10582 // instantiations, this just adds noise.
10583 if (CurrentInstantiationScope)
10584 return;
10585
10586 // The body should be a null statement.
10587 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10588 if (!NBody)
10589 return;
10590
10591 // Do the usual checks.
10592 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10593 return;
10594
10595 Diag(NBody->getSemiLoc(), DiagID);
10596 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10597}
10598
10599void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
10600 const Stmt *PossibleBody) {
10601 assert(!CurrentInstantiationScope); // Ensured by caller
10602
10603 SourceLocation StmtLoc;
10604 const Stmt *Body;
10605 unsigned DiagID;
10606 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
10607 StmtLoc = FS->getRParenLoc();
10608 Body = FS->getBody();
10609 DiagID = diag::warn_empty_for_body;
10610 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
10611 StmtLoc = WS->getCond()->getSourceRange().getEnd();
10612 Body = WS->getBody();
10613 DiagID = diag::warn_empty_while_body;
10614 } else
10615 return; // Neither `for' nor `while'.
10616
10617 // The body should be a null statement.
10618 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10619 if (!NBody)
10620 return;
10621
10622 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010623 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010624 return;
10625
10626 // Do the usual checks.
10627 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10628 return;
10629
10630 // `for(...);' and `while(...);' are popular idioms, so in order to keep
10631 // noise level low, emit diagnostics only if for/while is followed by a
10632 // CompoundStmt, e.g.:
10633 // for (int i = 0; i < n; i++);
10634 // {
10635 // a(i);
10636 // }
10637 // or if for/while is followed by a statement with more indentation
10638 // than for/while itself:
10639 // for (int i = 0; i < n; i++);
10640 // a(i);
10641 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
10642 if (!ProbableTypo) {
10643 bool BodyColInvalid;
10644 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
10645 PossibleBody->getLocStart(),
10646 &BodyColInvalid);
10647 if (BodyColInvalid)
10648 return;
10649
10650 bool StmtColInvalid;
10651 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
10652 S->getLocStart(),
10653 &StmtColInvalid);
10654 if (StmtColInvalid)
10655 return;
10656
10657 if (BodyCol > StmtCol)
10658 ProbableTypo = true;
10659 }
10660
10661 if (ProbableTypo) {
10662 Diag(NBody->getSemiLoc(), DiagID);
10663 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10664 }
10665}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010666
Richard Trieu36d0b2b2015-01-13 02:32:02 +000010667//===--- CHECK: Warn on self move with std::move. -------------------------===//
10668
10669/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
10670void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
10671 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000010672 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
10673 return;
10674
10675 if (!ActiveTemplateInstantiations.empty())
10676 return;
10677
10678 // Strip parens and casts away.
10679 LHSExpr = LHSExpr->IgnoreParenImpCasts();
10680 RHSExpr = RHSExpr->IgnoreParenImpCasts();
10681
10682 // Check for a call expression
10683 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
10684 if (!CE || CE->getNumArgs() != 1)
10685 return;
10686
10687 // Check for a call to std::move
10688 const FunctionDecl *FD = CE->getDirectCallee();
10689 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
10690 !FD->getIdentifier()->isStr("move"))
10691 return;
10692
10693 // Get argument from std::move
10694 RHSExpr = CE->getArg(0);
10695
10696 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10697 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10698
10699 // Two DeclRefExpr's, check that the decls are the same.
10700 if (LHSDeclRef && RHSDeclRef) {
10701 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10702 return;
10703 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10704 RHSDeclRef->getDecl()->getCanonicalDecl())
10705 return;
10706
10707 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10708 << LHSExpr->getSourceRange()
10709 << RHSExpr->getSourceRange();
10710 return;
10711 }
10712
10713 // Member variables require a different approach to check for self moves.
10714 // MemberExpr's are the same if every nested MemberExpr refers to the same
10715 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
10716 // the base Expr's are CXXThisExpr's.
10717 const Expr *LHSBase = LHSExpr;
10718 const Expr *RHSBase = RHSExpr;
10719 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
10720 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
10721 if (!LHSME || !RHSME)
10722 return;
10723
10724 while (LHSME && RHSME) {
10725 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
10726 RHSME->getMemberDecl()->getCanonicalDecl())
10727 return;
10728
10729 LHSBase = LHSME->getBase();
10730 RHSBase = RHSME->getBase();
10731 LHSME = dyn_cast<MemberExpr>(LHSBase);
10732 RHSME = dyn_cast<MemberExpr>(RHSBase);
10733 }
10734
10735 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
10736 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
10737 if (LHSDeclRef && RHSDeclRef) {
10738 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10739 return;
10740 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10741 RHSDeclRef->getDecl()->getCanonicalDecl())
10742 return;
10743
10744 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10745 << LHSExpr->getSourceRange()
10746 << RHSExpr->getSourceRange();
10747 return;
10748 }
10749
10750 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
10751 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10752 << LHSExpr->getSourceRange()
10753 << RHSExpr->getSourceRange();
10754}
10755
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010756//===--- Layout compatibility ----------------------------------------------//
10757
10758namespace {
10759
10760bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
10761
10762/// \brief Check if two enumeration types are layout-compatible.
10763bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
10764 // C++11 [dcl.enum] p8:
10765 // Two enumeration types are layout-compatible if they have the same
10766 // underlying type.
10767 return ED1->isComplete() && ED2->isComplete() &&
10768 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
10769}
10770
10771/// \brief Check if two fields are layout-compatible.
10772bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
10773 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
10774 return false;
10775
10776 if (Field1->isBitField() != Field2->isBitField())
10777 return false;
10778
10779 if (Field1->isBitField()) {
10780 // Make sure that the bit-fields are the same length.
10781 unsigned Bits1 = Field1->getBitWidthValue(C);
10782 unsigned Bits2 = Field2->getBitWidthValue(C);
10783
10784 if (Bits1 != Bits2)
10785 return false;
10786 }
10787
10788 return true;
10789}
10790
10791/// \brief Check if two standard-layout structs are layout-compatible.
10792/// (C++11 [class.mem] p17)
10793bool isLayoutCompatibleStruct(ASTContext &C,
10794 RecordDecl *RD1,
10795 RecordDecl *RD2) {
10796 // If both records are C++ classes, check that base classes match.
10797 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
10798 // If one of records is a CXXRecordDecl we are in C++ mode,
10799 // thus the other one is a CXXRecordDecl, too.
10800 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
10801 // Check number of base classes.
10802 if (D1CXX->getNumBases() != D2CXX->getNumBases())
10803 return false;
10804
10805 // Check the base classes.
10806 for (CXXRecordDecl::base_class_const_iterator
10807 Base1 = D1CXX->bases_begin(),
10808 BaseEnd1 = D1CXX->bases_end(),
10809 Base2 = D2CXX->bases_begin();
10810 Base1 != BaseEnd1;
10811 ++Base1, ++Base2) {
10812 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
10813 return false;
10814 }
10815 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
10816 // If only RD2 is a C++ class, it should have zero base classes.
10817 if (D2CXX->getNumBases() > 0)
10818 return false;
10819 }
10820
10821 // Check the fields.
10822 RecordDecl::field_iterator Field2 = RD2->field_begin(),
10823 Field2End = RD2->field_end(),
10824 Field1 = RD1->field_begin(),
10825 Field1End = RD1->field_end();
10826 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
10827 if (!isLayoutCompatible(C, *Field1, *Field2))
10828 return false;
10829 }
10830 if (Field1 != Field1End || Field2 != Field2End)
10831 return false;
10832
10833 return true;
10834}
10835
10836/// \brief Check if two standard-layout unions are layout-compatible.
10837/// (C++11 [class.mem] p18)
10838bool isLayoutCompatibleUnion(ASTContext &C,
10839 RecordDecl *RD1,
10840 RecordDecl *RD2) {
10841 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010842 for (auto *Field2 : RD2->fields())
10843 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010844
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010845 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010846 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
10847 I = UnmatchedFields.begin(),
10848 E = UnmatchedFields.end();
10849
10850 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010851 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010852 bool Result = UnmatchedFields.erase(*I);
10853 (void) Result;
10854 assert(Result);
10855 break;
10856 }
10857 }
10858 if (I == E)
10859 return false;
10860 }
10861
10862 return UnmatchedFields.empty();
10863}
10864
10865bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
10866 if (RD1->isUnion() != RD2->isUnion())
10867 return false;
10868
10869 if (RD1->isUnion())
10870 return isLayoutCompatibleUnion(C, RD1, RD2);
10871 else
10872 return isLayoutCompatibleStruct(C, RD1, RD2);
10873}
10874
10875/// \brief Check if two types are layout-compatible in C++11 sense.
10876bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
10877 if (T1.isNull() || T2.isNull())
10878 return false;
10879
10880 // C++11 [basic.types] p11:
10881 // If two types T1 and T2 are the same type, then T1 and T2 are
10882 // layout-compatible types.
10883 if (C.hasSameType(T1, T2))
10884 return true;
10885
10886 T1 = T1.getCanonicalType().getUnqualifiedType();
10887 T2 = T2.getCanonicalType().getUnqualifiedType();
10888
10889 const Type::TypeClass TC1 = T1->getTypeClass();
10890 const Type::TypeClass TC2 = T2->getTypeClass();
10891
10892 if (TC1 != TC2)
10893 return false;
10894
10895 if (TC1 == Type::Enum) {
10896 return isLayoutCompatible(C,
10897 cast<EnumType>(T1)->getDecl(),
10898 cast<EnumType>(T2)->getDecl());
10899 } else if (TC1 == Type::Record) {
10900 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
10901 return false;
10902
10903 return isLayoutCompatible(C,
10904 cast<RecordType>(T1)->getDecl(),
10905 cast<RecordType>(T2)->getDecl());
10906 }
10907
10908 return false;
10909}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010910} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010911
10912//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
10913
10914namespace {
10915/// \brief Given a type tag expression find the type tag itself.
10916///
10917/// \param TypeExpr Type tag expression, as it appears in user's code.
10918///
10919/// \param VD Declaration of an identifier that appears in a type tag.
10920///
10921/// \param MagicValue Type tag magic value.
10922bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
10923 const ValueDecl **VD, uint64_t *MagicValue) {
10924 while(true) {
10925 if (!TypeExpr)
10926 return false;
10927
10928 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
10929
10930 switch (TypeExpr->getStmtClass()) {
10931 case Stmt::UnaryOperatorClass: {
10932 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
10933 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
10934 TypeExpr = UO->getSubExpr();
10935 continue;
10936 }
10937 return false;
10938 }
10939
10940 case Stmt::DeclRefExprClass: {
10941 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
10942 *VD = DRE->getDecl();
10943 return true;
10944 }
10945
10946 case Stmt::IntegerLiteralClass: {
10947 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
10948 llvm::APInt MagicValueAPInt = IL->getValue();
10949 if (MagicValueAPInt.getActiveBits() <= 64) {
10950 *MagicValue = MagicValueAPInt.getZExtValue();
10951 return true;
10952 } else
10953 return false;
10954 }
10955
10956 case Stmt::BinaryConditionalOperatorClass:
10957 case Stmt::ConditionalOperatorClass: {
10958 const AbstractConditionalOperator *ACO =
10959 cast<AbstractConditionalOperator>(TypeExpr);
10960 bool Result;
10961 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
10962 if (Result)
10963 TypeExpr = ACO->getTrueExpr();
10964 else
10965 TypeExpr = ACO->getFalseExpr();
10966 continue;
10967 }
10968 return false;
10969 }
10970
10971 case Stmt::BinaryOperatorClass: {
10972 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
10973 if (BO->getOpcode() == BO_Comma) {
10974 TypeExpr = BO->getRHS();
10975 continue;
10976 }
10977 return false;
10978 }
10979
10980 default:
10981 return false;
10982 }
10983 }
10984}
10985
10986/// \brief Retrieve the C type corresponding to type tag TypeExpr.
10987///
10988/// \param TypeExpr Expression that specifies a type tag.
10989///
10990/// \param MagicValues Registered magic values.
10991///
10992/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
10993/// kind.
10994///
10995/// \param TypeInfo Information about the corresponding C type.
10996///
10997/// \returns true if the corresponding C type was found.
10998bool GetMatchingCType(
10999 const IdentifierInfo *ArgumentKind,
11000 const Expr *TypeExpr, const ASTContext &Ctx,
11001 const llvm::DenseMap<Sema::TypeTagMagicValue,
11002 Sema::TypeTagData> *MagicValues,
11003 bool &FoundWrongKind,
11004 Sema::TypeTagData &TypeInfo) {
11005 FoundWrongKind = false;
11006
11007 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000011008 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011009
11010 uint64_t MagicValue;
11011
11012 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11013 return false;
11014
11015 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000011016 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011017 if (I->getArgumentKind() != ArgumentKind) {
11018 FoundWrongKind = true;
11019 return false;
11020 }
11021 TypeInfo.Type = I->getMatchingCType();
11022 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11023 TypeInfo.MustBeNull = I->getMustBeNull();
11024 return true;
11025 }
11026 return false;
11027 }
11028
11029 if (!MagicValues)
11030 return false;
11031
11032 llvm::DenseMap<Sema::TypeTagMagicValue,
11033 Sema::TypeTagData>::const_iterator I =
11034 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11035 if (I == MagicValues->end())
11036 return false;
11037
11038 TypeInfo = I->second;
11039 return true;
11040}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011041} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011042
11043void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11044 uint64_t MagicValue, QualType Type,
11045 bool LayoutCompatible,
11046 bool MustBeNull) {
11047 if (!TypeTagForDatatypeMagicValues)
11048 TypeTagForDatatypeMagicValues.reset(
11049 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11050
11051 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11052 (*TypeTagForDatatypeMagicValues)[Magic] =
11053 TypeTagData(Type, LayoutCompatible, MustBeNull);
11054}
11055
11056namespace {
11057bool IsSameCharType(QualType T1, QualType T2) {
11058 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11059 if (!BT1)
11060 return false;
11061
11062 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11063 if (!BT2)
11064 return false;
11065
11066 BuiltinType::Kind T1Kind = BT1->getKind();
11067 BuiltinType::Kind T2Kind = BT2->getKind();
11068
11069 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
11070 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
11071 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11072 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11073}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011074} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011075
11076void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11077 const Expr * const *ExprArgs) {
11078 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11079 bool IsPointerAttr = Attr->getIsPointer();
11080
11081 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11082 bool FoundWrongKind;
11083 TypeTagData TypeInfo;
11084 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11085 TypeTagForDatatypeMagicValues.get(),
11086 FoundWrongKind, TypeInfo)) {
11087 if (FoundWrongKind)
11088 Diag(TypeTagExpr->getExprLoc(),
11089 diag::warn_type_tag_for_datatype_wrong_kind)
11090 << TypeTagExpr->getSourceRange();
11091 return;
11092 }
11093
11094 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11095 if (IsPointerAttr) {
11096 // Skip implicit cast of pointer to `void *' (as a function argument).
11097 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000011098 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000011099 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011100 ArgumentExpr = ICE->getSubExpr();
11101 }
11102 QualType ArgumentType = ArgumentExpr->getType();
11103
11104 // Passing a `void*' pointer shouldn't trigger a warning.
11105 if (IsPointerAttr && ArgumentType->isVoidPointerType())
11106 return;
11107
11108 if (TypeInfo.MustBeNull) {
11109 // Type tag with matching void type requires a null pointer.
11110 if (!ArgumentExpr->isNullPointerConstant(Context,
11111 Expr::NPC_ValueDependentIsNotNull)) {
11112 Diag(ArgumentExpr->getExprLoc(),
11113 diag::warn_type_safety_null_pointer_required)
11114 << ArgumentKind->getName()
11115 << ArgumentExpr->getSourceRange()
11116 << TypeTagExpr->getSourceRange();
11117 }
11118 return;
11119 }
11120
11121 QualType RequiredType = TypeInfo.Type;
11122 if (IsPointerAttr)
11123 RequiredType = Context.getPointerType(RequiredType);
11124
11125 bool mismatch = false;
11126 if (!TypeInfo.LayoutCompatible) {
11127 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
11128
11129 // C++11 [basic.fundamental] p1:
11130 // Plain char, signed char, and unsigned char are three distinct types.
11131 //
11132 // But we treat plain `char' as equivalent to `signed char' or `unsigned
11133 // char' depending on the current char signedness mode.
11134 if (mismatch)
11135 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
11136 RequiredType->getPointeeType())) ||
11137 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
11138 mismatch = false;
11139 } else
11140 if (IsPointerAttr)
11141 mismatch = !isLayoutCompatible(Context,
11142 ArgumentType->getPointeeType(),
11143 RequiredType->getPointeeType());
11144 else
11145 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
11146
11147 if (mismatch)
11148 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000011149 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011150 << TypeInfo.LayoutCompatible << RequiredType
11151 << ArgumentExpr->getSourceRange()
11152 << TypeTagExpr->getSourceRange();
11153}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011154
11155void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11156 CharUnits Alignment) {
11157 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
11158}
11159
11160void Sema::DiagnoseMisalignedMembers() {
11161 for (MisalignedMember &m : MisalignedMembers) {
11162 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
11163 << m.MD << m.RD << m.E->getSourceRange();
11164 }
11165 MisalignedMembers.clear();
11166}
11167
11168void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
11169 if (!T->isPointerType())
11170 return;
11171 if (isa<UnaryOperator>(E) &&
11172 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
11173 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11174 if (isa<MemberExpr>(Op)) {
11175 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
11176 MisalignedMember(Op));
11177 if (MA != MisalignedMembers.end() &&
11178 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)
11179 MisalignedMembers.erase(MA);
11180 }
11181 }
11182}
11183
11184void Sema::RefersToMemberWithReducedAlignment(
11185 Expr *E,
11186 std::function<void(Expr *, RecordDecl *, ValueDecl *, CharUnits)> Action) {
11187 const auto *ME = dyn_cast<MemberExpr>(E);
11188 while (ME && isa<FieldDecl>(ME->getMemberDecl())) {
11189 QualType BaseType = ME->getBase()->getType();
11190 if (ME->isArrow())
11191 BaseType = BaseType->getPointeeType();
11192 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
11193
11194 ValueDecl *MD = ME->getMemberDecl();
11195 bool ByteAligned = Context.getTypeAlignInChars(MD->getType()).isOne();
11196 if (ByteAligned) // Attribute packed does not have any effect.
11197 break;
11198
11199 if (!ByteAligned &&
11200 (RD->hasAttr<PackedAttr>() || (MD->hasAttr<PackedAttr>()))) {
11201 CharUnits Alignment = std::min(Context.getTypeAlignInChars(MD->getType()),
11202 Context.getTypeAlignInChars(BaseType));
11203 // Notify that this expression designates a member with reduced alignment
11204 Action(E, RD, MD, Alignment);
11205 break;
11206 }
11207 ME = dyn_cast<MemberExpr>(ME->getBase());
11208 }
11209}
11210
11211void Sema::CheckAddressOfPackedMember(Expr *rhs) {
11212 using namespace std::placeholders;
11213 RefersToMemberWithReducedAlignment(
11214 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
11215 _2, _3, _4));
11216}
11217