blob: f3f204ffa04ee7389a0e552e073fbd3ae7e9dbec [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() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00003243 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3244 // Promotable integers are UB, but enumerations need a bit of
3245 // extra checking to see what their promotable type actually is.
3246 if (!Type->isPromotableIntegerType())
3247 return false;
3248 if (!Type->isEnumeralType())
3249 return true;
3250 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3251 return !(ED &&
3252 Context.typesAreCompatible(ED->getPromotionType(), Type));
3253 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00003254 unsigned Reason = 0;
3255 if (Type->isReferenceType()) Reason = 1;
3256 else if (IsCRegister) Reason = 2;
3257 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003258 Diag(ParamLoc, diag::note_parameter_type) << Type;
3259 }
3260
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003261 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003262 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003263}
Chris Lattner43be2e62007-12-19 23:59:04 +00003264
Charles Davisc7d5c942015-09-17 20:55:33 +00003265/// Check the arguments to '__builtin_va_start' for validity, and that
3266/// it was called from a function of the native ABI.
3267/// Emit an error and return true on failure; return false on success.
3268bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3269 // On x86-64 Unix, don't allow this in Win64 ABI functions.
3270 // On x64 Windows, don't allow this in System V ABI functions.
3271 // (Yes, that means there's no corresponding way to support variadic
3272 // System V ABI functions on Windows.)
3273 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3274 unsigned OS = Context.getTargetInfo().getTriple().getOS();
3275 clang::CallingConv CC = CC_C;
3276 if (const FunctionDecl *FD = getCurFunctionDecl())
3277 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3278 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3279 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3280 return Diag(TheCall->getCallee()->getLocStart(),
3281 diag::err_va_start_used_in_wrong_abi_function)
3282 << (OS != llvm::Triple::Win32);
3283 }
3284 return SemaBuiltinVAStartImpl(TheCall);
3285}
3286
3287/// Check the arguments to '__builtin_ms_va_start' for validity, and that
3288/// it was called from a Win64 ABI function.
3289/// Emit an error and return true on failure; return false on success.
3290bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3291 // This only makes sense for x86-64.
3292 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3293 Expr *Callee = TheCall->getCallee();
3294 if (TT.getArch() != llvm::Triple::x86_64)
3295 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3296 // Don't allow this in System V ABI functions.
3297 clang::CallingConv CC = CC_C;
3298 if (const FunctionDecl *FD = getCurFunctionDecl())
3299 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3300 if (CC == CC_X86_64SysV ||
3301 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3302 return Diag(Callee->getLocStart(),
3303 diag::err_ms_va_start_used_in_sysv_function);
3304 return SemaBuiltinVAStartImpl(TheCall);
3305}
3306
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003307bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3308 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3309 // const char *named_addr);
3310
3311 Expr *Func = Call->getCallee();
3312
3313 if (Call->getNumArgs() < 3)
3314 return Diag(Call->getLocEnd(),
3315 diag::err_typecheck_call_too_few_args_at_least)
3316 << 0 /*function call*/ << 3 << Call->getNumArgs();
3317
3318 // Determine whether the current function is variadic or not.
3319 bool IsVariadic;
3320 if (BlockScopeInfo *CurBlock = getCurBlock())
3321 IsVariadic = CurBlock->TheDecl->isVariadic();
3322 else if (FunctionDecl *FD = getCurFunctionDecl())
3323 IsVariadic = FD->isVariadic();
3324 else if (ObjCMethodDecl *MD = getCurMethodDecl())
3325 IsVariadic = MD->isVariadic();
3326 else
3327 llvm_unreachable("unexpected statement type");
3328
3329 if (!IsVariadic) {
3330 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3331 return true;
3332 }
3333
3334 // Type-check the first argument normally.
3335 if (checkBuiltinArgument(*this, Call, 0))
3336 return true;
3337
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003338 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003339 unsigned ArgNo;
3340 QualType Type;
3341 } ArgumentTypes[] = {
3342 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3343 { 2, Context.getSizeType() },
3344 };
3345
3346 for (const auto &AT : ArgumentTypes) {
3347 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3348 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3349 continue;
3350 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3351 << Arg->getType() << AT.Type << 1 /* different class */
3352 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3353 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3354 }
3355
3356 return false;
3357}
3358
Chris Lattner2da14fb2007-12-20 00:26:33 +00003359/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3360/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003361bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3362 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003363 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003364 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003365 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003366 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003367 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003368 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003369 << SourceRange(TheCall->getArg(2)->getLocStart(),
3370 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003371
John Wiegley01296292011-04-08 18:41:53 +00003372 ExprResult OrigArg0 = TheCall->getArg(0);
3373 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003374
Chris Lattner2da14fb2007-12-20 00:26:33 +00003375 // Do standard promotions between the two arguments, returning their common
3376 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003377 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003378 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3379 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003380
3381 // Make sure any conversions are pushed back into the call; this is
3382 // type safe since unordered compare builtins are declared as "_Bool
3383 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003384 TheCall->setArg(0, OrigArg0.get());
3385 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003386
John Wiegley01296292011-04-08 18:41:53 +00003387 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003388 return false;
3389
Chris Lattner2da14fb2007-12-20 00:26:33 +00003390 // If the common type isn't a real floating type, then the arguments were
3391 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003392 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00003393 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003394 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00003395 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3396 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003397
Chris Lattner2da14fb2007-12-20 00:26:33 +00003398 return false;
3399}
3400
Benjamin Kramer634fc102010-02-15 22:42:31 +00003401/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3402/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00003403/// to check everything. We expect the last argument to be a floating point
3404/// value.
3405bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3406 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00003407 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003408 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00003409 if (TheCall->getNumArgs() > NumArgs)
3410 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003411 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003412 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00003413 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003414 (*(TheCall->arg_end()-1))->getLocEnd());
3415
Benjamin Kramer64aae502010-02-16 10:07:31 +00003416 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00003417
Eli Friedman7e4faac2009-08-31 20:06:00 +00003418 if (OrigArg->isTypeDependent())
3419 return false;
3420
Chris Lattner68784ef2010-05-06 05:50:07 +00003421 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00003422 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00003423 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003424 diag::err_typecheck_call_invalid_unary_fp)
3425 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003426
Chris Lattner68784ef2010-05-06 05:50:07 +00003427 // If this is an implicit conversion from float -> double, remove it.
3428 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3429 Expr *CastArg = Cast->getSubExpr();
3430 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3431 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
3432 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00003433 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00003434 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00003435 }
3436 }
3437
Eli Friedman7e4faac2009-08-31 20:06:00 +00003438 return false;
3439}
3440
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003441/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3442// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00003443ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00003444 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003445 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00003446 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00003447 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3448 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003449
Nate Begemana0110022010-06-08 00:16:34 +00003450 // Determine which of the following types of shufflevector we're checking:
3451 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00003452 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00003453 QualType resType = TheCall->getArg(0)->getType();
3454 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00003455
Douglas Gregorc25f7662009-05-19 22:10:17 +00003456 if (!TheCall->getArg(0)->isTypeDependent() &&
3457 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00003458 QualType LHSType = TheCall->getArg(0)->getType();
3459 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00003460
Craig Topperbaca3892013-07-29 06:47:04 +00003461 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3462 return ExprError(Diag(TheCall->getLocStart(),
3463 diag::err_shufflevector_non_vector)
3464 << SourceRange(TheCall->getArg(0)->getLocStart(),
3465 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003466
Nate Begemana0110022010-06-08 00:16:34 +00003467 numElements = LHSType->getAs<VectorType>()->getNumElements();
3468 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00003469
Nate Begemana0110022010-06-08 00:16:34 +00003470 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3471 // with mask. If so, verify that RHS is an integer vector type with the
3472 // same number of elts as lhs.
3473 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00003474 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00003475 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00003476 return ExprError(Diag(TheCall->getLocStart(),
3477 diag::err_shufflevector_incompatible_vector)
3478 << SourceRange(TheCall->getArg(1)->getLocStart(),
3479 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003480 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00003481 return ExprError(Diag(TheCall->getLocStart(),
3482 diag::err_shufflevector_incompatible_vector)
3483 << SourceRange(TheCall->getArg(0)->getLocStart(),
3484 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00003485 } else if (numElements != numResElements) {
3486 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00003487 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003488 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003489 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003490 }
3491
3492 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00003493 if (TheCall->getArg(i)->isTypeDependent() ||
3494 TheCall->getArg(i)->isValueDependent())
3495 continue;
3496
Nate Begemana0110022010-06-08 00:16:34 +00003497 llvm::APSInt Result(32);
3498 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3499 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003500 diag::err_shufflevector_nonconstant_argument)
3501 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003502
Craig Topper50ad5b72013-08-03 17:40:38 +00003503 // Allow -1 which will be translated to undef in the IR.
3504 if (Result.isSigned() && Result.isAllOnesValue())
3505 continue;
3506
Chris Lattner7ab824e2008-08-10 02:05:13 +00003507 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003508 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003509 diag::err_shufflevector_argument_too_large)
3510 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003511 }
3512
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003513 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003514
Chris Lattner7ab824e2008-08-10 02:05:13 +00003515 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003516 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00003517 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003518 }
3519
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003520 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3521 TheCall->getCallee()->getLocStart(),
3522 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003523}
Chris Lattner43be2e62007-12-19 23:59:04 +00003524
Hal Finkelc4d7c822013-09-18 03:29:45 +00003525/// SemaConvertVectorExpr - Handle __builtin_convertvector
3526ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3527 SourceLocation BuiltinLoc,
3528 SourceLocation RParenLoc) {
3529 ExprValueKind VK = VK_RValue;
3530 ExprObjectKind OK = OK_Ordinary;
3531 QualType DstTy = TInfo->getType();
3532 QualType SrcTy = E->getType();
3533
3534 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3535 return ExprError(Diag(BuiltinLoc,
3536 diag::err_convertvector_non_vector)
3537 << E->getSourceRange());
3538 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3539 return ExprError(Diag(BuiltinLoc,
3540 diag::err_convertvector_non_vector_type));
3541
3542 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3543 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3544 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3545 if (SrcElts != DstElts)
3546 return ExprError(Diag(BuiltinLoc,
3547 diag::err_convertvector_incompatible_vector)
3548 << E->getSourceRange());
3549 }
3550
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003551 return new (Context)
3552 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003553}
3554
Daniel Dunbarb7257262008-07-21 22:59:13 +00003555/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3556// This is declared to take (const void*, ...) and can take two
3557// optional constant int args.
3558bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003559 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003560
Chris Lattner3b054132008-11-19 05:08:23 +00003561 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003562 return Diag(TheCall->getLocEnd(),
3563 diag::err_typecheck_call_too_many_args_at_most)
3564 << 0 /*function call*/ << 3 << NumArgs
3565 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003566
3567 // Argument 0 is checked for us and the remaining arguments must be
3568 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003569 for (unsigned i = 1; i != NumArgs; ++i)
3570 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003571 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003572
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003573 return false;
3574}
3575
Hal Finkelf0417332014-07-17 14:25:55 +00003576/// SemaBuiltinAssume - Handle __assume (MS Extension).
3577// __assume does not evaluate its arguments, and should warn if its argument
3578// has side effects.
3579bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3580 Expr *Arg = TheCall->getArg(0);
3581 if (Arg->isInstantiationDependent()) return false;
3582
3583 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003584 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003585 << Arg->getSourceRange()
3586 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3587
3588 return false;
3589}
3590
3591/// Handle __builtin_assume_aligned. This is declared
3592/// as (const void*, size_t, ...) and can take one optional constant int arg.
3593bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3594 unsigned NumArgs = TheCall->getNumArgs();
3595
3596 if (NumArgs > 3)
3597 return Diag(TheCall->getLocEnd(),
3598 diag::err_typecheck_call_too_many_args_at_most)
3599 << 0 /*function call*/ << 3 << NumArgs
3600 << TheCall->getSourceRange();
3601
3602 // The alignment must be a constant integer.
3603 Expr *Arg = TheCall->getArg(1);
3604
3605 // We can't check the value of a dependent argument.
3606 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3607 llvm::APSInt Result;
3608 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3609 return true;
3610
3611 if (!Result.isPowerOf2())
3612 return Diag(TheCall->getLocStart(),
3613 diag::err_alignment_not_power_of_two)
3614 << Arg->getSourceRange();
3615 }
3616
3617 if (NumArgs > 2) {
3618 ExprResult Arg(TheCall->getArg(2));
3619 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3620 Context.getSizeType(), false);
3621 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3622 if (Arg.isInvalid()) return true;
3623 TheCall->setArg(2, Arg.get());
3624 }
Hal Finkelf0417332014-07-17 14:25:55 +00003625
3626 return false;
3627}
3628
Eric Christopher8d0c6212010-04-17 02:26:23 +00003629/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3630/// TheCall is a constant expression.
3631bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3632 llvm::APSInt &Result) {
3633 Expr *Arg = TheCall->getArg(ArgNum);
3634 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3635 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3636
3637 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3638
3639 if (!Arg->isIntegerConstantExpr(Result, Context))
3640 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00003641 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00003642
Chris Lattnerd545ad12009-09-23 06:06:36 +00003643 return false;
3644}
3645
Richard Sandiford28940af2014-04-16 08:47:51 +00003646/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3647/// TheCall is a constant expression in the range [Low, High].
3648bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3649 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00003650 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003651
3652 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00003653 Expr *Arg = TheCall->getArg(ArgNum);
3654 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003655 return false;
3656
Eric Christopher8d0c6212010-04-17 02:26:23 +00003657 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00003658 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003659 return true;
3660
Richard Sandiford28940af2014-04-16 08:47:51 +00003661 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00003662 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00003663 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00003664
3665 return false;
3666}
3667
Luke Cheeseman59b2d832015-06-15 17:51:01 +00003668/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
3669/// TheCall is an ARM/AArch64 special register string literal.
3670bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
3671 int ArgNum, unsigned ExpectedFieldNum,
3672 bool AllowName) {
3673 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3674 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
3675 BuiltinID == ARM::BI__builtin_arm_rsr ||
3676 BuiltinID == ARM::BI__builtin_arm_rsrp ||
3677 BuiltinID == ARM::BI__builtin_arm_wsr ||
3678 BuiltinID == ARM::BI__builtin_arm_wsrp;
3679 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3680 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3681 BuiltinID == AArch64::BI__builtin_arm_rsr ||
3682 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3683 BuiltinID == AArch64::BI__builtin_arm_wsr ||
3684 BuiltinID == AArch64::BI__builtin_arm_wsrp;
3685 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
3686
3687 // We can't check the value of a dependent argument.
3688 Expr *Arg = TheCall->getArg(ArgNum);
3689 if (Arg->isTypeDependent() || Arg->isValueDependent())
3690 return false;
3691
3692 // Check if the argument is a string literal.
3693 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3694 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3695 << Arg->getSourceRange();
3696
3697 // Check the type of special register given.
3698 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3699 SmallVector<StringRef, 6> Fields;
3700 Reg.split(Fields, ":");
3701
3702 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
3703 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3704 << Arg->getSourceRange();
3705
3706 // If the string is the name of a register then we cannot check that it is
3707 // valid here but if the string is of one the forms described in ACLE then we
3708 // can check that the supplied fields are integers and within the valid
3709 // ranges.
3710 if (Fields.size() > 1) {
3711 bool FiveFields = Fields.size() == 5;
3712
3713 bool ValidString = true;
3714 if (IsARMBuiltin) {
3715 ValidString &= Fields[0].startswith_lower("cp") ||
3716 Fields[0].startswith_lower("p");
3717 if (ValidString)
3718 Fields[0] =
3719 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
3720
3721 ValidString &= Fields[2].startswith_lower("c");
3722 if (ValidString)
3723 Fields[2] = Fields[2].drop_front(1);
3724
3725 if (FiveFields) {
3726 ValidString &= Fields[3].startswith_lower("c");
3727 if (ValidString)
3728 Fields[3] = Fields[3].drop_front(1);
3729 }
3730 }
3731
3732 SmallVector<int, 5> Ranges;
3733 if (FiveFields)
3734 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
3735 else
3736 Ranges.append({15, 7, 15});
3737
3738 for (unsigned i=0; i<Fields.size(); ++i) {
3739 int IntField;
3740 ValidString &= !Fields[i].getAsInteger(10, IntField);
3741 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
3742 }
3743
3744 if (!ValidString)
3745 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3746 << Arg->getSourceRange();
3747
3748 } else if (IsAArch64Builtin && Fields.size() == 1) {
3749 // If the register name is one of those that appear in the condition below
3750 // and the special register builtin being used is one of the write builtins,
3751 // then we require that the argument provided for writing to the register
3752 // is an integer constant expression. This is because it will be lowered to
3753 // an MSR (immediate) instruction, so we need to know the immediate at
3754 // compile time.
3755 if (TheCall->getNumArgs() != 2)
3756 return false;
3757
3758 std::string RegLower = Reg.lower();
3759 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
3760 RegLower != "pan" && RegLower != "uao")
3761 return false;
3762
3763 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3764 }
3765
3766 return false;
3767}
3768
Eli Friedmanc97d0142009-05-03 06:04:26 +00003769/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003770/// This checks that the target supports __builtin_longjmp and
3771/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003772bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003773 if (!Context.getTargetInfo().hasSjLjLowering())
3774 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
3775 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3776
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003777 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00003778 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00003779
Eric Christopher8d0c6212010-04-17 02:26:23 +00003780 // TODO: This is less than ideal. Overload this to take a value.
3781 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3782 return true;
3783
3784 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003785 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3786 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3787
3788 return false;
3789}
3790
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003791/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3792/// This checks that the target supports __builtin_setjmp.
3793bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3794 if (!Context.getTargetInfo().hasSjLjLowering())
3795 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3796 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3797 return false;
3798}
3799
Richard Smithd7293d72013-08-05 18:49:43 +00003800namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003801class UncoveredArgHandler {
3802 enum { Unknown = -1, AllCovered = -2 };
3803 signed FirstUncoveredArg;
3804 SmallVector<const Expr *, 4> DiagnosticExprs;
3805
3806public:
3807 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
3808
3809 bool hasUncoveredArg() const {
3810 return (FirstUncoveredArg >= 0);
3811 }
3812
3813 unsigned getUncoveredArg() const {
3814 assert(hasUncoveredArg() && "no uncovered argument");
3815 return FirstUncoveredArg;
3816 }
3817
3818 void setAllCovered() {
3819 // A string has been found with all arguments covered, so clear out
3820 // the diagnostics.
3821 DiagnosticExprs.clear();
3822 FirstUncoveredArg = AllCovered;
3823 }
3824
3825 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
3826 assert(NewFirstUncoveredArg >= 0 && "Outside range");
3827
3828 // Don't update if a previous string covers all arguments.
3829 if (FirstUncoveredArg == AllCovered)
3830 return;
3831
3832 // UncoveredArgHandler tracks the highest uncovered argument index
3833 // and with it all the strings that match this index.
3834 if (NewFirstUncoveredArg == FirstUncoveredArg)
3835 DiagnosticExprs.push_back(StrExpr);
3836 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
3837 DiagnosticExprs.clear();
3838 DiagnosticExprs.push_back(StrExpr);
3839 FirstUncoveredArg = NewFirstUncoveredArg;
3840 }
3841 }
3842
3843 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
3844};
3845
Richard Smithd7293d72013-08-05 18:49:43 +00003846enum StringLiteralCheckType {
3847 SLCT_NotALiteral,
3848 SLCT_UncheckedLiteral,
3849 SLCT_CheckedLiteral
3850};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003851} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00003852
Stephen Hines6a17e512016-09-14 20:20:14 +00003853static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003854 const Expr *OrigFormatExpr,
3855 ArrayRef<const Expr *> Args,
3856 bool HasVAListArg, unsigned format_idx,
3857 unsigned firstDataArg,
3858 Sema::FormatStringType Type,
3859 bool inFunctionCall,
3860 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003861 llvm::SmallBitVector &CheckedVarArgs,
3862 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003863
Richard Smith55ce3522012-06-25 20:30:08 +00003864// Determine if an expression is a string literal or constant string.
3865// If this function returns false on the arguments to a function expecting a
3866// format string, we will usually need to emit a warning.
3867// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00003868static StringLiteralCheckType
3869checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
3870 bool HasVAListArg, unsigned format_idx,
3871 unsigned firstDataArg, Sema::FormatStringType Type,
3872 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003873 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines6a17e512016-09-14 20:20:14 +00003874 UncoveredArgHandler &UncoveredArg) {
Ted Kremenek808829352010-09-09 03:51:39 +00003875 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00003876 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00003877 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003878
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003879 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00003880
Richard Smithd7293d72013-08-05 18:49:43 +00003881 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00003882 // Technically -Wformat-nonliteral does not warn about this case.
3883 // The behavior of printf and friends in this case is implementation
3884 // dependent. Ideally if the format string cannot be null then
3885 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00003886 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00003887
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003888 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00003889 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003890 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00003891 // The expression is a literal if both sub-expressions were, and it was
3892 // completely checked only if both sub-expressions were checked.
3893 const AbstractConditionalOperator *C =
3894 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003895
3896 // Determine whether it is necessary to check both sub-expressions, for
3897 // example, because the condition expression is a constant that can be
3898 // evaluated at compile time.
3899 bool CheckLeft = true, CheckRight = true;
3900
3901 bool Cond;
3902 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
3903 if (Cond)
3904 CheckRight = false;
3905 else
3906 CheckLeft = false;
3907 }
3908
3909 StringLiteralCheckType Left;
3910 if (!CheckLeft)
3911 Left = SLCT_UncheckedLiteral;
3912 else {
3913 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
3914 HasVAListArg, format_idx, firstDataArg,
3915 Type, CallType, InFunctionCall,
Stephen Hines6a17e512016-09-14 20:20:14 +00003916 CheckedVarArgs, UncoveredArg);
3917 if (Left == SLCT_NotALiteral || !CheckRight)
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003918 return Left;
3919 }
3920
Richard Smith55ce3522012-06-25 20:30:08 +00003921 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00003922 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003923 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003924 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines6a17e512016-09-14 20:20:14 +00003925 UncoveredArg);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003926
3927 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003928 }
3929
3930 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00003931 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3932 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003933 }
3934
John McCallc07a0c72011-02-17 10:25:35 +00003935 case Stmt::OpaqueValueExprClass:
3936 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3937 E = src;
3938 goto tryAgain;
3939 }
Richard Smith55ce3522012-06-25 20:30:08 +00003940 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00003941
Ted Kremeneka8890832011-02-24 23:03:04 +00003942 case Stmt::PredefinedExprClass:
3943 // While __func__, etc., are technically not string literals, they
3944 // cannot contain format specifiers and thus are not a security
3945 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00003946 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00003947
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003948 case Stmt::DeclRefExprClass: {
3949 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003950
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003951 // As an exception, do not flag errors for variables binding to
3952 // const string literals.
3953 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3954 bool isConstant = false;
3955 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003956
Richard Smithd7293d72013-08-05 18:49:43 +00003957 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3958 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003959 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00003960 isConstant = T.isConstant(S.Context) &&
3961 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00003962 } else if (T->isObjCObjectPointerType()) {
3963 // In ObjC, there is usually no "const ObjectPointer" type,
3964 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00003965 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003966 }
Mike Stump11289f42009-09-09 15:08:12 +00003967
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003968 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003969 if (const Expr *Init = VD->getAnyInitializer()) {
3970 // Look through initializers like const char c[] = { "foo" }
3971 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3972 if (InitList->isStringLiteralInit())
3973 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3974 }
Richard Smithd7293d72013-08-05 18:49:43 +00003975 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003976 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003977 firstDataArg, Type, CallType,
Stephen Hines6a17e512016-09-14 20:20:14 +00003978 /*InFunctionCall*/false, CheckedVarArgs,
3979 UncoveredArg);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003980 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003981 }
Mike Stump11289f42009-09-09 15:08:12 +00003982
Anders Carlssonb012ca92009-06-28 19:55:58 +00003983 // For vprintf* functions (i.e., HasVAListArg==true), we add a
3984 // special check to see if the format string is a function parameter
3985 // of the function calling the printf function. If the function
3986 // has an attribute indicating it is a printf-like function, then we
3987 // should suppress warnings concerning non-literals being used in a call
3988 // to a vprintf function. For example:
3989 //
3990 // void
3991 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3992 // va_list ap;
3993 // va_start(ap, fmt);
3994 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
3995 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00003996 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003997 if (HasVAListArg) {
3998 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3999 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4000 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004001 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004002 // adjust for implicit parameter
4003 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4004 if (MD->isInstance())
4005 ++PVIndex;
4006 // We also check if the formats are compatible.
4007 // We can't pass a 'scanf' string to a 'printf' function.
4008 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00004009 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00004010 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004011 }
4012 }
4013 }
4014 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004015 }
Mike Stump11289f42009-09-09 15:08:12 +00004016
Richard Smith55ce3522012-06-25 20:30:08 +00004017 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004018 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004019
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004020 case Stmt::CallExprClass:
4021 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004022 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004023 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4024 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4025 unsigned ArgIndex = FA->getFormatIdx();
4026 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4027 if (MD->isInstance())
4028 --ArgIndex;
4029 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00004030
Richard Smithd7293d72013-08-05 18:49:43 +00004031 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004032 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00004033 Type, CallType, InFunctionCall,
Stephen Hines6a17e512016-09-14 20:20:14 +00004034 CheckedVarArgs, UncoveredArg);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004035 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4036 unsigned BuiltinID = FD->getBuiltinID();
4037 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4038 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4039 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00004040 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004041 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004042 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004043 InFunctionCall, CheckedVarArgs,
Stephen Hines6a17e512016-09-14 20:20:14 +00004044 UncoveredArg);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004045 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004046 }
4047 }
Mike Stump11289f42009-09-09 15:08:12 +00004048
Richard Smith55ce3522012-06-25 20:30:08 +00004049 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004050 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004051 case Stmt::ObjCStringLiteralClass:
4052 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00004053 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004054
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004055 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004056 StrE = ObjCFExpr->getString();
4057 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004058 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004059
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004060 if (StrE) {
Stephen Hines6a17e512016-09-14 20:20:14 +00004061 CheckFormatString(S, StrE, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004062 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004063 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00004064 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004065 }
Mike Stump11289f42009-09-09 15:08:12 +00004066
Richard Smith55ce3522012-06-25 20:30:08 +00004067 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004068 }
Mike Stump11289f42009-09-09 15:08:12 +00004069
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004070 default:
Richard Smith55ce3522012-06-25 20:30:08 +00004071 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004072 }
4073}
4074
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004075Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00004076 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004077 .Case("scanf", FST_Scanf)
4078 .Cases("printf", "printf0", FST_Printf)
4079 .Cases("NSString", "CFString", FST_NSString)
4080 .Case("strftime", FST_Strftime)
4081 .Case("strfmon", FST_Strfmon)
4082 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004083 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004084 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004085 .Default(FST_Unknown);
4086}
4087
Jordan Rose3e0ec582012-07-19 18:10:23 +00004088/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00004089/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00004090/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004091bool Sema::CheckFormatArguments(const FormatAttr *Format,
4092 ArrayRef<const Expr *> Args,
4093 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004094 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004095 SourceLocation Loc, SourceRange Range,
4096 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00004097 FormatStringInfo FSI;
4098 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004099 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00004100 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00004101 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00004102 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004103}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00004104
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004105bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004106 bool HasVAListArg, unsigned format_idx,
4107 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004108 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004109 SourceLocation Loc, SourceRange Range,
4110 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004111 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004112 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004113 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00004114 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004115 }
Mike Stump11289f42009-09-09 15:08:12 +00004116
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004117 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004118
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004119 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00004120 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004121 // Dynamically generated format strings are difficult to
4122 // automatically vet at compile time. Requiring that format strings
4123 // are string literals: (1) permits the checking of format strings by
4124 // the compiler and thereby (2) can practically remove the source of
4125 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00004126
Mike Stump11289f42009-09-09 15:08:12 +00004127 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00004128 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00004129 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00004130 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004131 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00004132 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00004133 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4134 format_idx, firstDataArg, Type, CallType,
Stephen Hines6a17e512016-09-14 20:20:14 +00004135 /*IsFunctionCall*/true, CheckedVarArgs,
4136 UncoveredArg);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004137
4138 // Generate a diagnostic where an uncovered argument is detected.
4139 if (UncoveredArg.hasUncoveredArg()) {
4140 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4141 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4142 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4143 }
4144
Richard Smith55ce3522012-06-25 20:30:08 +00004145 if (CT != SLCT_NotALiteral)
4146 // Literal format string found, check done!
4147 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00004148
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004149 // Strftime is particular as it always uses a single 'time' argument,
4150 // so it is safe to pass a non-literal string.
4151 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00004152 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004153
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004154 // Do not emit diag when the string param is a macro expansion and the
4155 // format is either NSString or CFString. This is a hack to prevent
4156 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4157 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004158 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4159 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00004160 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004161
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004162 // If there are no arguments specified, warn with -Wformat-security, otherwise
4163 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004164 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00004165 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4166 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004167 switch (Type) {
4168 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004169 break;
4170 case FST_Kprintf:
4171 case FST_FreeBSDKPrintf:
4172 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00004173 Diag(FormatLoc, diag::note_format_security_fixit)
4174 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004175 break;
4176 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00004177 Diag(FormatLoc, diag::note_format_security_fixit)
4178 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004179 break;
4180 }
4181 } else {
4182 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004183 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004184 }
Richard Smith55ce3522012-06-25 20:30:08 +00004185 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004186}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004187
Ted Kremenekab278de2010-01-28 23:39:18 +00004188namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00004189class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4190protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00004191 Sema &S;
Stephen Hines6a17e512016-09-14 20:20:14 +00004192 const StringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00004193 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00004194 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00004195 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00004196 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00004197 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004198 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00004199 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00004200 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00004201 bool usesPositionalArgs;
4202 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004203 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00004204 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00004205 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004206 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004207
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004208public:
Stephen Hines6a17e512016-09-14 20:20:14 +00004209 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00004210 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004211 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004212 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004213 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004214 Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004215 llvm::SmallBitVector &CheckedVarArgs,
4216 UncoveredArgHandler &UncoveredArg)
Ted Kremenekab278de2010-01-28 23:39:18 +00004217 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004218 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
4219 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004220 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00004221 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00004222 inFunctionCall(inFunctionCall), CallType(callType),
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004223 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00004224 CoveredArgs.resize(numDataArgs);
4225 CoveredArgs.reset();
4226 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004227
Ted Kremenek019d2242010-01-29 01:50:07 +00004228 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004229
Ted Kremenek02087932010-07-16 02:11:22 +00004230 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004231 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004232
Jordan Rose92303592012-09-08 04:00:03 +00004233 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004234 const analyze_format_string::FormatSpecifier &FS,
4235 const analyze_format_string::ConversionSpecifier &CS,
4236 const char *startSpecifier, unsigned specifierLen,
4237 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00004238
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004239 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004240 const analyze_format_string::FormatSpecifier &FS,
4241 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004242
4243 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004244 const analyze_format_string::ConversionSpecifier &CS,
4245 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004246
Craig Toppere14c0f82014-03-12 04:55:44 +00004247 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004248
Craig Toppere14c0f82014-03-12 04:55:44 +00004249 void HandleInvalidPosition(const char *startSpecifier,
4250 unsigned specifierLen,
4251 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004252
Craig Toppere14c0f82014-03-12 04:55:44 +00004253 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004254
Craig Toppere14c0f82014-03-12 04:55:44 +00004255 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004256
Richard Trieu03cf7b72011-10-28 00:41:25 +00004257 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00004258 static void
4259 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4260 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4261 bool IsStringLocation, Range StringRange,
4262 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004263
Ted Kremenek02087932010-07-16 02:11:22 +00004264protected:
Ted Kremenekce815422010-07-19 21:25:57 +00004265 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4266 const char *startSpec,
4267 unsigned specifierLen,
4268 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004269
4270 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4271 const char *startSpec,
4272 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00004273
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004274 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00004275 CharSourceRange getSpecifierRange(const char *startSpecifier,
4276 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00004277 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004278
Ted Kremenek5739de72010-01-29 01:06:55 +00004279 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004280
4281 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4282 const analyze_format_string::ConversionSpecifier &CS,
4283 const char *startSpecifier, unsigned specifierLen,
4284 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004285
4286 template <typename Range>
4287 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4288 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004289 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00004290};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004291} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004292
Ted Kremenek02087932010-07-16 02:11:22 +00004293SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00004294 return OrigFormatExpr->getSourceRange();
4295}
4296
Ted Kremenek02087932010-07-16 02:11:22 +00004297CharSourceRange CheckFormatHandler::
4298getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00004299 SourceLocation Start = getLocationOfByte(startSpecifier);
4300 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
4301
4302 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004303 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00004304
4305 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004306}
4307
Ted Kremenek02087932010-07-16 02:11:22 +00004308SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines6a17e512016-09-14 20:20:14 +00004309 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00004310}
4311
Ted Kremenek02087932010-07-16 02:11:22 +00004312void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4313 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00004314 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4315 getLocationOfByte(startSpecifier),
4316 /*IsStringLocation*/true,
4317 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00004318}
4319
Jordan Rose92303592012-09-08 04:00:03 +00004320void CheckFormatHandler::HandleInvalidLengthModifier(
4321 const analyze_format_string::FormatSpecifier &FS,
4322 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00004323 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00004324 using namespace analyze_format_string;
4325
4326 const LengthModifier &LM = FS.getLengthModifier();
4327 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4328
4329 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004330 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00004331 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004332 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004333 getLocationOfByte(LM.getStart()),
4334 /*IsStringLocation*/true,
4335 getSpecifierRange(startSpecifier, specifierLen));
4336
4337 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4338 << FixedLM->toString()
4339 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4340
4341 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004342 FixItHint Hint;
4343 if (DiagID == diag::warn_format_nonsensical_length)
4344 Hint = FixItHint::CreateRemoval(LMRange);
4345
4346 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004347 getLocationOfByte(LM.getStart()),
4348 /*IsStringLocation*/true,
4349 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00004350 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00004351 }
4352}
4353
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004354void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00004355 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004356 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004357 using namespace analyze_format_string;
4358
4359 const LengthModifier &LM = FS.getLengthModifier();
4360 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4361
4362 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004363 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00004364 if (FixedLM) {
4365 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4366 << LM.toString() << 0,
4367 getLocationOfByte(LM.getStart()),
4368 /*IsStringLocation*/true,
4369 getSpecifierRange(startSpecifier, specifierLen));
4370
4371 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4372 << FixedLM->toString()
4373 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4374
4375 } else {
4376 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4377 << LM.toString() << 0,
4378 getLocationOfByte(LM.getStart()),
4379 /*IsStringLocation*/true,
4380 getSpecifierRange(startSpecifier, specifierLen));
4381 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004382}
4383
4384void CheckFormatHandler::HandleNonStandardConversionSpecifier(
4385 const analyze_format_string::ConversionSpecifier &CS,
4386 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00004387 using namespace analyze_format_string;
4388
4389 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00004390 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00004391 if (FixedCS) {
4392 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4393 << CS.toString() << /*conversion specifier*/1,
4394 getLocationOfByte(CS.getStart()),
4395 /*IsStringLocation*/true,
4396 getSpecifierRange(startSpecifier, specifierLen));
4397
4398 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
4399 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
4400 << FixedCS->toString()
4401 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
4402 } else {
4403 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4404 << CS.toString() << /*conversion specifier*/1,
4405 getLocationOfByte(CS.getStart()),
4406 /*IsStringLocation*/true,
4407 getSpecifierRange(startSpecifier, specifierLen));
4408 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004409}
4410
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004411void CheckFormatHandler::HandlePosition(const char *startPos,
4412 unsigned posLen) {
4413 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
4414 getLocationOfByte(startPos),
4415 /*IsStringLocation*/true,
4416 getSpecifierRange(startPos, posLen));
4417}
4418
Ted Kremenekd1668192010-02-27 01:41:03 +00004419void
Ted Kremenek02087932010-07-16 02:11:22 +00004420CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
4421 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004422 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
4423 << (unsigned) p,
4424 getLocationOfByte(startPos), /*IsStringLocation*/true,
4425 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00004426}
4427
Ted Kremenek02087932010-07-16 02:11:22 +00004428void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00004429 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004430 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
4431 getLocationOfByte(startPos),
4432 /*IsStringLocation*/true,
4433 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00004434}
4435
Ted Kremenek02087932010-07-16 02:11:22 +00004436void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004437 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00004438 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004439 EmitFormatDiagnostic(
4440 S.PDiag(diag::warn_printf_format_string_contains_null_char),
4441 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
4442 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00004443 }
Ted Kremenek02087932010-07-16 02:11:22 +00004444}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004445
Jordan Rose58bbe422012-07-19 18:10:08 +00004446// Note that this may return NULL if there was an error parsing or building
4447// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00004448const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004449 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00004450}
4451
4452void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004453 // Does the number of data arguments exceed the number of
4454 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00004455 if (!HasVAListArg) {
4456 // Find any arguments that weren't covered.
4457 CoveredArgs.flip();
4458 signed notCoveredArg = CoveredArgs.find_first();
4459 if (notCoveredArg >= 0) {
4460 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004461 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
4462 } else {
4463 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00004464 }
4465 }
4466}
4467
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004468void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
4469 const Expr *ArgExpr) {
4470 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
4471 "Invalid state");
4472
4473 if (!ArgExpr)
4474 return;
4475
4476 SourceLocation Loc = ArgExpr->getLocStart();
4477
4478 if (S.getSourceManager().isInSystemMacro(Loc))
4479 return;
4480
4481 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
4482 for (auto E : DiagnosticExprs)
4483 PDiag << E->getSourceRange();
4484
4485 CheckFormatHandler::EmitFormatDiagnostic(
4486 S, IsFunctionCall, DiagnosticExprs[0],
4487 PDiag, Loc, /*IsStringLocation*/false,
4488 DiagnosticExprs[0]->getSourceRange());
4489}
4490
Ted Kremenekce815422010-07-19 21:25:57 +00004491bool
4492CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
4493 SourceLocation Loc,
4494 const char *startSpec,
4495 unsigned specifierLen,
4496 const char *csStart,
4497 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00004498 bool keepGoing = true;
4499 if (argIndex < NumDataArgs) {
4500 // Consider the argument coverered, even though the specifier doesn't
4501 // make sense.
4502 CoveredArgs.set(argIndex);
4503 }
4504 else {
4505 // If argIndex exceeds the number of data arguments we
4506 // don't issue a warning because that is just a cascade of warnings (and
4507 // they may have intended '%%' anyway). We don't want to continue processing
4508 // the format string after this point, however, as we will like just get
4509 // gibberish when trying to match arguments.
4510 keepGoing = false;
4511 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00004512
4513 StringRef Specifier(csStart, csLen);
4514
4515 // If the specifier in non-printable, it could be the first byte of a UTF-8
4516 // sequence. In that case, print the UTF-8 code point. If not, print the byte
4517 // hex value.
4518 std::string CodePointStr;
4519 if (!llvm::sys::locale::isPrint(*csStart)) {
4520 UTF32 CodePoint;
4521 const UTF8 **B = reinterpret_cast<const UTF8 **>(&csStart);
4522 const UTF8 *E =
4523 reinterpret_cast<const UTF8 *>(csStart + csLen);
4524 ConversionResult Result =
4525 llvm::convertUTF8Sequence(B, E, &CodePoint, strictConversion);
4526
4527 if (Result != conversionOK) {
4528 unsigned char FirstChar = *csStart;
4529 CodePoint = (UTF32)FirstChar;
4530 }
4531
4532 llvm::raw_string_ostream OS(CodePointStr);
4533 if (CodePoint < 256)
4534 OS << "\\x" << llvm::format("%02x", CodePoint);
4535 else if (CodePoint <= 0xFFFF)
4536 OS << "\\u" << llvm::format("%04x", CodePoint);
4537 else
4538 OS << "\\U" << llvm::format("%08x", CodePoint);
4539 OS.flush();
4540 Specifier = CodePointStr;
4541 }
4542
4543 EmitFormatDiagnostic(
4544 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
4545 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
4546
Ted Kremenekce815422010-07-19 21:25:57 +00004547 return keepGoing;
4548}
4549
Richard Trieu03cf7b72011-10-28 00:41:25 +00004550void
4551CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
4552 const char *startSpec,
4553 unsigned specifierLen) {
4554 EmitFormatDiagnostic(
4555 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
4556 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
4557}
4558
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004559bool
4560CheckFormatHandler::CheckNumArgs(
4561 const analyze_format_string::FormatSpecifier &FS,
4562 const analyze_format_string::ConversionSpecifier &CS,
4563 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
4564
4565 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004566 PartialDiagnostic PDiag = FS.usesPositionalArg()
4567 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
4568 << (argIndex+1) << NumDataArgs)
4569 : S.PDiag(diag::warn_printf_insufficient_data_args);
4570 EmitFormatDiagnostic(
4571 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
4572 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004573
4574 // Since more arguments than conversion tokens are given, by extension
4575 // all arguments are covered, so mark this as so.
4576 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004577 return false;
4578 }
4579 return true;
4580}
4581
Richard Trieu03cf7b72011-10-28 00:41:25 +00004582template<typename Range>
4583void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
4584 SourceLocation Loc,
4585 bool IsStringLocation,
4586 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00004587 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004588 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00004589 Loc, IsStringLocation, StringRange, FixIt);
4590}
4591
4592/// \brief If the format string is not within the funcion call, emit a note
4593/// so that the function call and string are in diagnostic messages.
4594///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004595/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00004596/// call and only one diagnostic message will be produced. Otherwise, an
4597/// extra note will be emitted pointing to location of the format string.
4598///
4599/// \param ArgumentExpr the expression that is passed as the format string
4600/// argument in the function call. Used for getting locations when two
4601/// diagnostics are emitted.
4602///
4603/// \param PDiag the callee should already have provided any strings for the
4604/// diagnostic message. This function only adds locations and fixits
4605/// to diagnostics.
4606///
4607/// \param Loc primary location for diagnostic. If two diagnostics are
4608/// required, one will be at Loc and a new SourceLocation will be created for
4609/// the other one.
4610///
4611/// \param IsStringLocation if true, Loc points to the format string should be
4612/// used for the note. Otherwise, Loc points to the argument list and will
4613/// be used with PDiag.
4614///
4615/// \param StringRange some or all of the string to highlight. This is
4616/// templated so it can accept either a CharSourceRange or a SourceRange.
4617///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004618/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00004619template <typename Range>
4620void CheckFormatHandler::EmitFormatDiagnostic(
4621 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
4622 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
4623 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00004624 if (InFunctionCall) {
4625 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
4626 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004627 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00004628 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004629 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
4630 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00004631
4632 const Sema::SemaDiagnosticBuilder &Note =
4633 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
4634 diag::note_format_string_defined);
4635
4636 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004637 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004638 }
4639}
4640
Ted Kremenek02087932010-07-16 02:11:22 +00004641//===--- CHECK: Printf format string checking ------------------------------===//
4642
4643namespace {
4644class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004645 bool ObjCContext;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004646
Ted Kremenek02087932010-07-16 02:11:22 +00004647public:
Stephen Hines6a17e512016-09-14 20:20:14 +00004648 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek02087932010-07-16 02:11:22 +00004649 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004650 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00004651 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004652 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004653 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004654 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004655 llvm::SmallBitVector &CheckedVarArgs,
4656 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00004657 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4658 numDataArgs, beg, hasVAListArg, Args,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004659 formatIdx, inFunctionCall, CallType, CheckedVarArgs,
4660 UncoveredArg),
Richard Smithd7293d72013-08-05 18:49:43 +00004661 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004662 {}
4663
Ted Kremenek02087932010-07-16 02:11:22 +00004664 bool HandleInvalidPrintfConversionSpecifier(
4665 const analyze_printf::PrintfSpecifier &FS,
4666 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004667 unsigned specifierLen) override;
4668
Ted Kremenek02087932010-07-16 02:11:22 +00004669 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
4670 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004671 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004672 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4673 const char *StartSpecifier,
4674 unsigned SpecifierLen,
4675 const Expr *E);
4676
Ted Kremenek02087932010-07-16 02:11:22 +00004677 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
4678 const char *startSpecifier, unsigned specifierLen);
4679 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
4680 const analyze_printf::OptionalAmount &Amt,
4681 unsigned type,
4682 const char *startSpecifier, unsigned specifierLen);
4683 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
4684 const analyze_printf::OptionalFlag &flag,
4685 const char *startSpecifier, unsigned specifierLen);
4686 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
4687 const analyze_printf::OptionalFlag &ignoredFlag,
4688 const analyze_printf::OptionalFlag &flag,
4689 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004690 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00004691 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00004692
4693 void HandleEmptyObjCModifierFlag(const char *startFlag,
4694 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004695
Ted Kremenek2b417712015-07-02 05:39:16 +00004696 void HandleInvalidObjCModifierFlag(const char *startFlag,
4697 unsigned flagLen) override;
4698
4699 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
4700 const char *flagsEnd,
4701 const char *conversionPosition)
4702 override;
4703};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004704} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00004705
4706bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
4707 const analyze_printf::PrintfSpecifier &FS,
4708 const char *startSpecifier,
4709 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004710 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004711 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004712
Ted Kremenekce815422010-07-19 21:25:57 +00004713 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4714 getLocationOfByte(CS.getStart()),
4715 startSpecifier, specifierLen,
4716 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00004717}
4718
Ted Kremenek02087932010-07-16 02:11:22 +00004719bool CheckPrintfHandler::HandleAmount(
4720 const analyze_format_string::OptionalAmount &Amt,
4721 unsigned k, const char *startSpecifier,
4722 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004723 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004724 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00004725 unsigned argIndex = Amt.getArgIndex();
4726 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004727 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
4728 << k,
4729 getLocationOfByte(Amt.getStart()),
4730 /*IsStringLocation*/true,
4731 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004732 // Don't do any more checking. We will just emit
4733 // spurious errors.
4734 return false;
4735 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004736
Ted Kremenek5739de72010-01-29 01:06:55 +00004737 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00004738 // Although not in conformance with C99, we also allow the argument to be
4739 // an 'unsigned int' as that is a reasonably safe case. GCC also
4740 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00004741 CoveredArgs.set(argIndex);
4742 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004743 if (!Arg)
4744 return false;
4745
Ted Kremenek5739de72010-01-29 01:06:55 +00004746 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004747
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004748 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
4749 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004750
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004751 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004752 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004753 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00004754 << T << Arg->getSourceRange(),
4755 getLocationOfByte(Amt.getStart()),
4756 /*IsStringLocation*/true,
4757 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004758 // Don't do any more checking. We will just emit
4759 // spurious errors.
4760 return false;
4761 }
4762 }
4763 }
4764 return true;
4765}
Ted Kremenek5739de72010-01-29 01:06:55 +00004766
Tom Careb49ec692010-06-17 19:00:27 +00004767void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00004768 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004769 const analyze_printf::OptionalAmount &Amt,
4770 unsigned type,
4771 const char *startSpecifier,
4772 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004773 const analyze_printf::PrintfConversionSpecifier &CS =
4774 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00004775
Richard Trieu03cf7b72011-10-28 00:41:25 +00004776 FixItHint fixit =
4777 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
4778 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
4779 Amt.getConstantLength()))
4780 : FixItHint();
4781
4782 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
4783 << type << CS.toString(),
4784 getLocationOfByte(Amt.getStart()),
4785 /*IsStringLocation*/true,
4786 getSpecifierRange(startSpecifier, specifierLen),
4787 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00004788}
4789
Ted Kremenek02087932010-07-16 02:11:22 +00004790void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004791 const analyze_printf::OptionalFlag &flag,
4792 const char *startSpecifier,
4793 unsigned specifierLen) {
4794 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004795 const analyze_printf::PrintfConversionSpecifier &CS =
4796 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00004797 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
4798 << flag.toString() << CS.toString(),
4799 getLocationOfByte(flag.getPosition()),
4800 /*IsStringLocation*/true,
4801 getSpecifierRange(startSpecifier, specifierLen),
4802 FixItHint::CreateRemoval(
4803 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004804}
4805
4806void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00004807 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004808 const analyze_printf::OptionalFlag &ignoredFlag,
4809 const analyze_printf::OptionalFlag &flag,
4810 const char *startSpecifier,
4811 unsigned specifierLen) {
4812 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004813 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
4814 << ignoredFlag.toString() << flag.toString(),
4815 getLocationOfByte(ignoredFlag.getPosition()),
4816 /*IsStringLocation*/true,
4817 getSpecifierRange(startSpecifier, specifierLen),
4818 FixItHint::CreateRemoval(
4819 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004820}
4821
Ted Kremenek2b417712015-07-02 05:39:16 +00004822// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4823// bool IsStringLocation, Range StringRange,
4824// ArrayRef<FixItHint> Fixit = None);
4825
4826void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
4827 unsigned flagLen) {
4828 // Warn about an empty flag.
4829 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
4830 getLocationOfByte(startFlag),
4831 /*IsStringLocation*/true,
4832 getSpecifierRange(startFlag, flagLen));
4833}
4834
4835void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
4836 unsigned flagLen) {
4837 // Warn about an invalid flag.
4838 auto Range = getSpecifierRange(startFlag, flagLen);
4839 StringRef flag(startFlag, flagLen);
4840 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
4841 getLocationOfByte(startFlag),
4842 /*IsStringLocation*/true,
4843 Range, FixItHint::CreateRemoval(Range));
4844}
4845
4846void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
4847 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
4848 // Warn about using '[...]' without a '@' conversion.
4849 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
4850 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
4851 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
4852 getLocationOfByte(conversionPosition),
4853 /*IsStringLocation*/true,
4854 Range, FixItHint::CreateRemoval(Range));
4855}
4856
Richard Smith55ce3522012-06-25 20:30:08 +00004857// Determines if the specified is a C++ class or struct containing
4858// a member with the specified name and kind (e.g. a CXXMethodDecl named
4859// "c_str()").
4860template<typename MemberKind>
4861static llvm::SmallPtrSet<MemberKind*, 1>
4862CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
4863 const RecordType *RT = Ty->getAs<RecordType>();
4864 llvm::SmallPtrSet<MemberKind*, 1> Results;
4865
4866 if (!RT)
4867 return Results;
4868 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00004869 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00004870 return Results;
4871
Alp Tokerb6cc5922014-05-03 03:45:55 +00004872 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00004873 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00004874 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00004875
4876 // We just need to include all members of the right kind turned up by the
4877 // filter, at this point.
4878 if (S.LookupQualifiedName(R, RT->getDecl()))
4879 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4880 NamedDecl *decl = (*I)->getUnderlyingDecl();
4881 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
4882 Results.insert(FK);
4883 }
4884 return Results;
4885}
4886
Richard Smith2868a732014-02-28 01:36:39 +00004887/// Check if we could call '.c_str()' on an object.
4888///
4889/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
4890/// allow the call, or if it would be ambiguous).
4891bool Sema::hasCStrMethod(const Expr *E) {
4892 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4893 MethodSet Results =
4894 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
4895 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4896 MI != ME; ++MI)
4897 if ((*MI)->getMinRequiredArguments() == 0)
4898 return true;
4899 return false;
4900}
4901
Richard Smith55ce3522012-06-25 20:30:08 +00004902// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004903// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00004904// Returns true when a c_str() conversion method is found.
4905bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00004906 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00004907 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4908
4909 MethodSet Results =
4910 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
4911
4912 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4913 MI != ME; ++MI) {
4914 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00004915 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00004916 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00004917 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00004918 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00004919 S.Diag(E->getLocStart(), diag::note_printf_c_str)
4920 << "c_str()"
4921 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
4922 return true;
4923 }
4924 }
4925
4926 return false;
4927}
4928
Ted Kremenekab278de2010-01-28 23:39:18 +00004929bool
Ted Kremenek02087932010-07-16 02:11:22 +00004930CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00004931 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00004932 const char *startSpecifier,
4933 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004934 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00004935 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004936 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00004937
Ted Kremenek6cd69422010-07-19 22:01:06 +00004938 if (FS.consumesDataArgument()) {
4939 if (atFirstArg) {
4940 atFirstArg = false;
4941 usesPositionalArgs = FS.usesPositionalArg();
4942 }
4943 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004944 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4945 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004946 return false;
4947 }
Ted Kremenek5739de72010-01-29 01:06:55 +00004948 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004949
Ted Kremenekd1668192010-02-27 01:41:03 +00004950 // First check if the field width, precision, and conversion specifier
4951 // have matching data arguments.
4952 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
4953 startSpecifier, specifierLen)) {
4954 return false;
4955 }
4956
4957 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
4958 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004959 return false;
4960 }
4961
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004962 if (!CS.consumesDataArgument()) {
4963 // FIXME: Technically specifying a precision or field width here
4964 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00004965 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004966 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004967
Ted Kremenek4a49d982010-02-26 19:18:41 +00004968 // Consume the argument.
4969 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00004970 if (argIndex < NumDataArgs) {
4971 // The check to see if the argIndex is valid will come later.
4972 // We set the bit here because we may exit early from this
4973 // function if we encounter some other error.
4974 CoveredArgs.set(argIndex);
4975 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00004976
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004977 // FreeBSD kernel extensions.
4978 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
4979 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
4980 // We need at least two arguments.
4981 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4982 return false;
4983
4984 // Claim the second argument.
4985 CoveredArgs.set(argIndex + 1);
4986
4987 // Type check the first argument (int for %b, pointer for %D)
4988 const Expr *Ex = getDataArg(argIndex);
4989 const analyze_printf::ArgType &AT =
4990 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4991 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4992 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4993 EmitFormatDiagnostic(
4994 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4995 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4996 << false << Ex->getSourceRange(),
4997 Ex->getLocStart(), /*IsStringLocation*/false,
4998 getSpecifierRange(startSpecifier, specifierLen));
4999
5000 // Type check the second argument (char * for both %b and %D)
5001 Ex = getDataArg(argIndex + 1);
5002 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5003 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5004 EmitFormatDiagnostic(
5005 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5006 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5007 << false << Ex->getSourceRange(),
5008 Ex->getLocStart(), /*IsStringLocation*/false,
5009 getSpecifierRange(startSpecifier, specifierLen));
5010
5011 return true;
5012 }
5013
Ted Kremenek4a49d982010-02-26 19:18:41 +00005014 // Check for using an Objective-C specific conversion specifier
5015 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005016 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00005017 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5018 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00005019 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005020
Tom Careb49ec692010-06-17 19:00:27 +00005021 // Check for invalid use of field width
5022 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00005023 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00005024 startSpecifier, specifierLen);
5025 }
5026
5027 // Check for invalid use of precision
5028 if (!FS.hasValidPrecision()) {
5029 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5030 startSpecifier, specifierLen);
5031 }
5032
5033 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00005034 if (!FS.hasValidThousandsGroupingPrefix())
5035 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005036 if (!FS.hasValidLeadingZeros())
5037 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5038 if (!FS.hasValidPlusPrefix())
5039 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00005040 if (!FS.hasValidSpacePrefix())
5041 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005042 if (!FS.hasValidAlternativeForm())
5043 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5044 if (!FS.hasValidLeftJustified())
5045 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5046
5047 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00005048 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5049 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5050 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005051 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5052 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5053 startSpecifier, specifierLen);
5054
5055 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005056 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005057 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5058 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005059 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005060 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005061 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005062 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5063 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00005064
Jordan Rose92303592012-09-08 04:00:03 +00005065 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5066 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5067
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005068 // The remaining checks depend on the data arguments.
5069 if (HasVAListArg)
5070 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005071
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005072 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005073 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005074
Jordan Rose58bbe422012-07-19 18:10:08 +00005075 const Expr *Arg = getDataArg(argIndex);
5076 if (!Arg)
5077 return true;
5078
5079 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00005080}
5081
Jordan Roseaee34382012-09-05 22:56:26 +00005082static bool requiresParensToAddCast(const Expr *E) {
5083 // FIXME: We should have a general way to reason about operator
5084 // precedence and whether parens are actually needed here.
5085 // Take care of a few common cases where they aren't.
5086 const Expr *Inside = E->IgnoreImpCasts();
5087 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5088 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5089
5090 switch (Inside->getStmtClass()) {
5091 case Stmt::ArraySubscriptExprClass:
5092 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005093 case Stmt::CharacterLiteralClass:
5094 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005095 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005096 case Stmt::FloatingLiteralClass:
5097 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005098 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005099 case Stmt::ObjCArrayLiteralClass:
5100 case Stmt::ObjCBoolLiteralExprClass:
5101 case Stmt::ObjCBoxedExprClass:
5102 case Stmt::ObjCDictionaryLiteralClass:
5103 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005104 case Stmt::ObjCIvarRefExprClass:
5105 case Stmt::ObjCMessageExprClass:
5106 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005107 case Stmt::ObjCStringLiteralClass:
5108 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005109 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005110 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005111 case Stmt::UnaryOperatorClass:
5112 return false;
5113 default:
5114 return true;
5115 }
5116}
5117
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005118static std::pair<QualType, StringRef>
5119shouldNotPrintDirectly(const ASTContext &Context,
5120 QualType IntendedTy,
5121 const Expr *E) {
5122 // Use a 'while' to peel off layers of typedefs.
5123 QualType TyTy = IntendedTy;
5124 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5125 StringRef Name = UserTy->getDecl()->getName();
5126 QualType CastTy = llvm::StringSwitch<QualType>(Name)
5127 .Case("NSInteger", Context.LongTy)
5128 .Case("NSUInteger", Context.UnsignedLongTy)
5129 .Case("SInt32", Context.IntTy)
5130 .Case("UInt32", Context.UnsignedIntTy)
5131 .Default(QualType());
5132
5133 if (!CastTy.isNull())
5134 return std::make_pair(CastTy, Name);
5135
5136 TyTy = UserTy->desugar();
5137 }
5138
5139 // Strip parens if necessary.
5140 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5141 return shouldNotPrintDirectly(Context,
5142 PE->getSubExpr()->getType(),
5143 PE->getSubExpr());
5144
5145 // If this is a conditional expression, then its result type is constructed
5146 // via usual arithmetic conversions and thus there might be no necessary
5147 // typedef sugar there. Recurse to operands to check for NSInteger &
5148 // Co. usage condition.
5149 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5150 QualType TrueTy, FalseTy;
5151 StringRef TrueName, FalseName;
5152
5153 std::tie(TrueTy, TrueName) =
5154 shouldNotPrintDirectly(Context,
5155 CO->getTrueExpr()->getType(),
5156 CO->getTrueExpr());
5157 std::tie(FalseTy, FalseName) =
5158 shouldNotPrintDirectly(Context,
5159 CO->getFalseExpr()->getType(),
5160 CO->getFalseExpr());
5161
5162 if (TrueTy == FalseTy)
5163 return std::make_pair(TrueTy, TrueName);
5164 else if (TrueTy.isNull())
5165 return std::make_pair(FalseTy, FalseName);
5166 else if (FalseTy.isNull())
5167 return std::make_pair(TrueTy, TrueName);
5168 }
5169
5170 return std::make_pair(QualType(), StringRef());
5171}
5172
Richard Smith55ce3522012-06-25 20:30:08 +00005173bool
5174CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5175 const char *StartSpecifier,
5176 unsigned SpecifierLen,
5177 const Expr *E) {
5178 using namespace analyze_format_string;
5179 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005180 // Now type check the data expression that matches the
5181 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005182 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
5183 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00005184 if (!AT.isValid())
5185 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00005186
Jordan Rose598ec092012-12-05 18:44:40 +00005187 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00005188 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5189 ExprTy = TET->getUnderlyingExpr()->getType();
5190 }
5191
Seth Cantrellb4802962015-03-04 03:12:10 +00005192 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5193
5194 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00005195 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005196 }
Jordan Rose98709982012-06-04 22:48:57 +00005197
Jordan Rose22b74712012-09-05 22:56:19 +00005198 // Look through argument promotions for our error message's reported type.
5199 // This includes the integral and floating promotions, but excludes array
5200 // and function pointer decay; seeing that an argument intended to be a
5201 // string has type 'char [6]' is probably more confusing than 'char *'.
5202 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5203 if (ICE->getCastKind() == CK_IntegralCast ||
5204 ICE->getCastKind() == CK_FloatingCast) {
5205 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00005206 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00005207
5208 // Check if we didn't match because of an implicit cast from a 'char'
5209 // or 'short' to an 'int'. This is done because printf is a varargs
5210 // function.
5211 if (ICE->getType() == S.Context.IntTy ||
5212 ICE->getType() == S.Context.UnsignedIntTy) {
5213 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00005214 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00005215 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00005216 }
Jordan Rose98709982012-06-04 22:48:57 +00005217 }
Jordan Rose598ec092012-12-05 18:44:40 +00005218 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5219 // Special case for 'a', which has type 'int' in C.
5220 // Note, however, that we do /not/ want to treat multibyte constants like
5221 // 'MooV' as characters! This form is deprecated but still exists.
5222 if (ExprTy == S.Context.IntTy)
5223 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5224 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00005225 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005226
Jordan Rosebc53ed12014-05-31 04:12:14 +00005227 // Look through enums to their underlying type.
5228 bool IsEnum = false;
5229 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5230 ExprTy = EnumTy->getDecl()->getIntegerType();
5231 IsEnum = true;
5232 }
5233
Jordan Rose0e5badd2012-12-05 18:44:49 +00005234 // %C in an Objective-C context prints a unichar, not a wchar_t.
5235 // If the argument is an integer of some kind, believe the %C and suggest
5236 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00005237 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00005238 if (ObjCContext &&
5239 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5240 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5241 !ExprTy->isCharType()) {
5242 // 'unichar' is defined as a typedef of unsigned short, but we should
5243 // prefer using the typedef if it is visible.
5244 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00005245
5246 // While we are here, check if the value is an IntegerLiteral that happens
5247 // to be within the valid range.
5248 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5249 const llvm::APInt &V = IL->getValue();
5250 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5251 return true;
5252 }
5253
Jordan Rose0e5badd2012-12-05 18:44:49 +00005254 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5255 Sema::LookupOrdinaryName);
5256 if (S.LookupName(Result, S.getCurScope())) {
5257 NamedDecl *ND = Result.getFoundDecl();
5258 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5259 if (TD->getUnderlyingType() == IntendedTy)
5260 IntendedTy = S.Context.getTypedefType(TD);
5261 }
5262 }
5263 }
5264
5265 // Special-case some of Darwin's platform-independence types by suggesting
5266 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005267 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00005268 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005269 QualType CastTy;
5270 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5271 if (!CastTy.isNull()) {
5272 IntendedTy = CastTy;
5273 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00005274 }
5275 }
5276
Jordan Rose22b74712012-09-05 22:56:19 +00005277 // We may be able to offer a FixItHint if it is a supported type.
5278 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00005279 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00005280 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005281
Jordan Rose22b74712012-09-05 22:56:19 +00005282 if (success) {
5283 // Get the fix string from the fixed format specifier
5284 SmallString<16> buf;
5285 llvm::raw_svector_ostream os(buf);
5286 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005287
Jordan Roseaee34382012-09-05 22:56:26 +00005288 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5289
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005290 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00005291 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5292 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5293 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5294 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00005295 // In this case, the specifier is wrong and should be changed to match
5296 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00005297 EmitFormatDiagnostic(S.PDiag(diag)
5298 << AT.getRepresentativeTypeName(S.Context)
5299 << IntendedTy << IsEnum << E->getSourceRange(),
5300 E->getLocStart(),
5301 /*IsStringLocation*/ false, SpecRange,
5302 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00005303 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00005304 // The canonical type for formatting this value is different from the
5305 // actual type of the expression. (This occurs, for example, with Darwin's
5306 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
5307 // should be printed as 'long' for 64-bit compatibility.)
5308 // Rather than emitting a normal format/argument mismatch, we want to
5309 // add a cast to the recommended type (and correct the format string
5310 // if necessary).
5311 SmallString<16> CastBuf;
5312 llvm::raw_svector_ostream CastFix(CastBuf);
5313 CastFix << "(";
5314 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
5315 CastFix << ")";
5316
5317 SmallVector<FixItHint,4> Hints;
5318 if (!AT.matchesType(S.Context, IntendedTy))
5319 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
5320
5321 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
5322 // If there's already a cast present, just replace it.
5323 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
5324 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
5325
5326 } else if (!requiresParensToAddCast(E)) {
5327 // If the expression has high enough precedence,
5328 // just write the C-style cast.
5329 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5330 CastFix.str()));
5331 } else {
5332 // Otherwise, add parens around the expression as well as the cast.
5333 CastFix << "(";
5334 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5335 CastFix.str()));
5336
Alp Tokerb6cc5922014-05-03 03:45:55 +00005337 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00005338 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
5339 }
5340
Jordan Rose0e5badd2012-12-05 18:44:49 +00005341 if (ShouldNotPrintDirectly) {
5342 // The expression has a type that should not be printed directly.
5343 // We extract the name from the typedef because we don't want to show
5344 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005345 StringRef Name;
5346 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
5347 Name = TypedefTy->getDecl()->getName();
5348 else
5349 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00005350 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00005351 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00005352 << E->getSourceRange(),
5353 E->getLocStart(), /*IsStringLocation=*/false,
5354 SpecRange, Hints);
5355 } else {
5356 // In this case, the expression could be printed using a different
5357 // specifier, but we've decided that the specifier is probably correct
5358 // and we should cast instead. Just use the normal warning message.
5359 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00005360 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5361 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00005362 << E->getSourceRange(),
5363 E->getLocStart(), /*IsStringLocation*/false,
5364 SpecRange, Hints);
5365 }
Jordan Roseaee34382012-09-05 22:56:26 +00005366 }
Jordan Rose22b74712012-09-05 22:56:19 +00005367 } else {
5368 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
5369 SpecifierLen);
5370 // Since the warning for passing non-POD types to variadic functions
5371 // was deferred until now, we emit a warning for non-POD
5372 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00005373 switch (S.isValidVarArgType(ExprTy)) {
5374 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00005375 case Sema::VAK_ValidInCXX11: {
5376 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5377 if (match == analyze_printf::ArgType::NoMatchPedantic) {
5378 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5379 }
Richard Smithd7293d72013-08-05 18:49:43 +00005380
Seth Cantrellb4802962015-03-04 03:12:10 +00005381 EmitFormatDiagnostic(
5382 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
5383 << IsEnum << CSR << E->getSourceRange(),
5384 E->getLocStart(), /*IsStringLocation*/ false, CSR);
5385 break;
5386 }
Richard Smithd7293d72013-08-05 18:49:43 +00005387 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00005388 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00005389 EmitFormatDiagnostic(
5390 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005391 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00005392 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00005393 << CallType
5394 << AT.getRepresentativeTypeName(S.Context)
5395 << CSR
5396 << E->getSourceRange(),
5397 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00005398 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00005399 break;
5400
5401 case Sema::VAK_Invalid:
5402 if (ExprTy->isObjCObjectType())
5403 EmitFormatDiagnostic(
5404 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
5405 << S.getLangOpts().CPlusPlus11
5406 << ExprTy
5407 << CallType
5408 << AT.getRepresentativeTypeName(S.Context)
5409 << CSR
5410 << E->getSourceRange(),
5411 E->getLocStart(), /*IsStringLocation*/false, CSR);
5412 else
5413 // FIXME: If this is an initializer list, suggest removing the braces
5414 // or inserting a cast to the target type.
5415 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
5416 << isa<InitListExpr>(E) << ExprTy << CallType
5417 << AT.getRepresentativeTypeName(S.Context)
5418 << E->getSourceRange();
5419 break;
5420 }
5421
5422 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
5423 "format string specifier index out of range");
5424 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005425 }
5426
Ted Kremenekab278de2010-01-28 23:39:18 +00005427 return true;
5428}
5429
Ted Kremenek02087932010-07-16 02:11:22 +00005430//===--- CHECK: Scanf format string checking ------------------------------===//
5431
5432namespace {
5433class CheckScanfHandler : public CheckFormatHandler {
5434public:
Stephen Hines6a17e512016-09-14 20:20:14 +00005435 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek02087932010-07-16 02:11:22 +00005436 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005437 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005438 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005439 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005440 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005441 llvm::SmallBitVector &CheckedVarArgs,
5442 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00005443 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
5444 numDataArgs, beg, hasVAListArg,
5445 Args, formatIdx, inFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005446 CheckedVarArgs, UncoveredArg)
Jordan Rose3e0ec582012-07-19 18:10:23 +00005447 {}
Ted Kremenek02087932010-07-16 02:11:22 +00005448
5449 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
5450 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005451 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00005452
5453 bool HandleInvalidScanfConversionSpecifier(
5454 const analyze_scanf::ScanfSpecifier &FS,
5455 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005456 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005457
Craig Toppere14c0f82014-03-12 04:55:44 +00005458 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00005459};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005460} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005461
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005462void CheckScanfHandler::HandleIncompleteScanList(const char *start,
5463 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005464 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
5465 getLocationOfByte(end), /*IsStringLocation*/true,
5466 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005467}
5468
Ted Kremenekce815422010-07-19 21:25:57 +00005469bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
5470 const analyze_scanf::ScanfSpecifier &FS,
5471 const char *startSpecifier,
5472 unsigned specifierLen) {
5473
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005474 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005475 FS.getConversionSpecifier();
5476
5477 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5478 getLocationOfByte(CS.getStart()),
5479 startSpecifier, specifierLen,
5480 CS.getStart(), CS.getLength());
5481}
5482
Ted Kremenek02087932010-07-16 02:11:22 +00005483bool CheckScanfHandler::HandleScanfSpecifier(
5484 const analyze_scanf::ScanfSpecifier &FS,
5485 const char *startSpecifier,
5486 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00005487 using namespace analyze_scanf;
5488 using namespace analyze_format_string;
5489
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005490 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005491
Ted Kremenek6cd69422010-07-19 22:01:06 +00005492 // Handle case where '%' and '*' don't consume an argument. These shouldn't
5493 // be used to decide if we are using positional arguments consistently.
5494 if (FS.consumesDataArgument()) {
5495 if (atFirstArg) {
5496 atFirstArg = false;
5497 usesPositionalArgs = FS.usesPositionalArg();
5498 }
5499 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005500 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5501 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005502 return false;
5503 }
Ted Kremenek02087932010-07-16 02:11:22 +00005504 }
5505
5506 // Check if the field with is non-zero.
5507 const OptionalAmount &Amt = FS.getFieldWidth();
5508 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
5509 if (Amt.getConstantAmount() == 0) {
5510 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
5511 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00005512 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
5513 getLocationOfByte(Amt.getStart()),
5514 /*IsStringLocation*/true, R,
5515 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00005516 }
5517 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005518
Ted Kremenek02087932010-07-16 02:11:22 +00005519 if (!FS.consumesDataArgument()) {
5520 // FIXME: Technically specifying a precision or field width here
5521 // makes no sense. Worth issuing a warning at some point.
5522 return true;
5523 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005524
Ted Kremenek02087932010-07-16 02:11:22 +00005525 // Consume the argument.
5526 unsigned argIndex = FS.getArgIndex();
5527 if (argIndex < NumDataArgs) {
5528 // The check to see if the argIndex is valid will come later.
5529 // We set the bit here because we may exit early from this
5530 // function if we encounter some other error.
5531 CoveredArgs.set(argIndex);
5532 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005533
Ted Kremenek4407ea42010-07-20 20:04:47 +00005534 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005535 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005536 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5537 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005538 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005539 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005540 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005541 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5542 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005543
Jordan Rose92303592012-09-08 04:00:03 +00005544 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5545 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5546
Ted Kremenek02087932010-07-16 02:11:22 +00005547 // The remaining checks depend on the data arguments.
5548 if (HasVAListArg)
5549 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005550
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005551 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00005552 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00005553
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005554 // Check that the argument type matches the format specifier.
5555 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005556 if (!Ex)
5557 return true;
5558
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00005559 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00005560
5561 if (!AT.isValid()) {
5562 return true;
5563 }
5564
Seth Cantrellb4802962015-03-04 03:12:10 +00005565 analyze_format_string::ArgType::MatchKind match =
5566 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00005567 if (match == analyze_format_string::ArgType::Match) {
5568 return true;
5569 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005570
Seth Cantrell79340072015-03-04 05:58:08 +00005571 ScanfSpecifier fixedFS = FS;
5572 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
5573 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005574
Seth Cantrell79340072015-03-04 05:58:08 +00005575 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5576 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5577 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5578 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005579
Seth Cantrell79340072015-03-04 05:58:08 +00005580 if (success) {
5581 // Get the fix string from the fixed format specifier.
5582 SmallString<128> buf;
5583 llvm::raw_svector_ostream os(buf);
5584 fixedFS.toString(os);
5585
5586 EmitFormatDiagnostic(
5587 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
5588 << Ex->getType() << false << Ex->getSourceRange(),
5589 Ex->getLocStart(),
5590 /*IsStringLocation*/ false,
5591 getSpecifierRange(startSpecifier, specifierLen),
5592 FixItHint::CreateReplacement(
5593 getSpecifierRange(startSpecifier, specifierLen), os.str()));
5594 } else {
5595 EmitFormatDiagnostic(S.PDiag(diag)
5596 << AT.getRepresentativeTypeName(S.Context)
5597 << Ex->getType() << false << Ex->getSourceRange(),
5598 Ex->getLocStart(),
5599 /*IsStringLocation*/ false,
5600 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005601 }
5602
Ted Kremenek02087932010-07-16 02:11:22 +00005603 return true;
5604}
5605
Stephen Hines6a17e512016-09-14 20:20:14 +00005606static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005607 const Expr *OrigFormatExpr,
5608 ArrayRef<const Expr *> Args,
5609 bool HasVAListArg, unsigned format_idx,
5610 unsigned firstDataArg,
5611 Sema::FormatStringType Type,
5612 bool inFunctionCall,
5613 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005614 llvm::SmallBitVector &CheckedVarArgs,
5615 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00005616 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00005617 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005618 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005619 S, inFunctionCall, Args[format_idx],
5620 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005621 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005622 return;
5623 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005624
Ted Kremenekab278de2010-01-28 23:39:18 +00005625 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005626 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00005627 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005628 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005629 const ConstantArrayType *T =
5630 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005631 assert(T && "String literal not of constant array type!");
5632 size_t TypeSize = T->getSize().getZExtValue();
5633 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005634 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005635
5636 // Emit a warning if the string literal is truncated and does not contain an
5637 // embedded null character.
5638 if (TypeSize <= StrRef.size() &&
5639 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
5640 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005641 S, inFunctionCall, Args[format_idx],
5642 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005643 FExpr->getLocStart(),
5644 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
5645 return;
5646 }
5647
Ted Kremenekab278de2010-01-28 23:39:18 +00005648 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00005649 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005650 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005651 S, inFunctionCall, Args[format_idx],
5652 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005653 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005654 return;
5655 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005656
5657 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
5658 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) {
5659 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
5660 numDataArgs, (Type == Sema::FST_NSString ||
5661 Type == Sema::FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005662 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005663 inFunctionCall, CallType, CheckedVarArgs,
5664 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005665
Hans Wennborg23926bd2011-12-15 10:25:47 +00005666 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005667 S.getLangOpts(),
5668 S.Context.getTargetInfo(),
5669 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00005670 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005671 } else if (Type == Sema::FST_Scanf) {
5672 CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005673 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005674 inFunctionCall, CallType, CheckedVarArgs,
5675 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005676
Hans Wennborg23926bd2011-12-15 10:25:47 +00005677 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005678 S.getLangOpts(),
5679 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00005680 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005681 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00005682}
5683
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00005684bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
5685 // Str - The format string. NOTE: this is NOT null-terminated!
5686 StringRef StrRef = FExpr->getString();
5687 const char *Str = StrRef.data();
5688 // Account for cases where the string literal is truncated in a declaration.
5689 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
5690 assert(T && "String literal not of constant array type!");
5691 size_t TypeSize = T->getSize().getZExtValue();
5692 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5693 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
5694 getLangOpts(),
5695 Context.getTargetInfo());
5696}
5697
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005698//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
5699
5700// Returns the related absolute value function that is larger, of 0 if one
5701// does not exist.
5702static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
5703 switch (AbsFunction) {
5704 default:
5705 return 0;
5706
5707 case Builtin::BI__builtin_abs:
5708 return Builtin::BI__builtin_labs;
5709 case Builtin::BI__builtin_labs:
5710 return Builtin::BI__builtin_llabs;
5711 case Builtin::BI__builtin_llabs:
5712 return 0;
5713
5714 case Builtin::BI__builtin_fabsf:
5715 return Builtin::BI__builtin_fabs;
5716 case Builtin::BI__builtin_fabs:
5717 return Builtin::BI__builtin_fabsl;
5718 case Builtin::BI__builtin_fabsl:
5719 return 0;
5720
5721 case Builtin::BI__builtin_cabsf:
5722 return Builtin::BI__builtin_cabs;
5723 case Builtin::BI__builtin_cabs:
5724 return Builtin::BI__builtin_cabsl;
5725 case Builtin::BI__builtin_cabsl:
5726 return 0;
5727
5728 case Builtin::BIabs:
5729 return Builtin::BIlabs;
5730 case Builtin::BIlabs:
5731 return Builtin::BIllabs;
5732 case Builtin::BIllabs:
5733 return 0;
5734
5735 case Builtin::BIfabsf:
5736 return Builtin::BIfabs;
5737 case Builtin::BIfabs:
5738 return Builtin::BIfabsl;
5739 case Builtin::BIfabsl:
5740 return 0;
5741
5742 case Builtin::BIcabsf:
5743 return Builtin::BIcabs;
5744 case Builtin::BIcabs:
5745 return Builtin::BIcabsl;
5746 case Builtin::BIcabsl:
5747 return 0;
5748 }
5749}
5750
5751// Returns the argument type of the absolute value function.
5752static QualType getAbsoluteValueArgumentType(ASTContext &Context,
5753 unsigned AbsType) {
5754 if (AbsType == 0)
5755 return QualType();
5756
5757 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
5758 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
5759 if (Error != ASTContext::GE_None)
5760 return QualType();
5761
5762 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
5763 if (!FT)
5764 return QualType();
5765
5766 if (FT->getNumParams() != 1)
5767 return QualType();
5768
5769 return FT->getParamType(0);
5770}
5771
5772// Returns the best absolute value function, or zero, based on type and
5773// current absolute value function.
5774static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
5775 unsigned AbsFunctionKind) {
5776 unsigned BestKind = 0;
5777 uint64_t ArgSize = Context.getTypeSize(ArgType);
5778 for (unsigned Kind = AbsFunctionKind; Kind != 0;
5779 Kind = getLargerAbsoluteValueFunction(Kind)) {
5780 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
5781 if (Context.getTypeSize(ParamType) >= ArgSize) {
5782 if (BestKind == 0)
5783 BestKind = Kind;
5784 else if (Context.hasSameType(ParamType, ArgType)) {
5785 BestKind = Kind;
5786 break;
5787 }
5788 }
5789 }
5790 return BestKind;
5791}
5792
5793enum AbsoluteValueKind {
5794 AVK_Integer,
5795 AVK_Floating,
5796 AVK_Complex
5797};
5798
5799static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
5800 if (T->isIntegralOrEnumerationType())
5801 return AVK_Integer;
5802 if (T->isRealFloatingType())
5803 return AVK_Floating;
5804 if (T->isAnyComplexType())
5805 return AVK_Complex;
5806
5807 llvm_unreachable("Type not integer, floating, or complex");
5808}
5809
5810// Changes the absolute value function to a different type. Preserves whether
5811// the function is a builtin.
5812static unsigned changeAbsFunction(unsigned AbsKind,
5813 AbsoluteValueKind ValueKind) {
5814 switch (ValueKind) {
5815 case AVK_Integer:
5816 switch (AbsKind) {
5817 default:
5818 return 0;
5819 case Builtin::BI__builtin_fabsf:
5820 case Builtin::BI__builtin_fabs:
5821 case Builtin::BI__builtin_fabsl:
5822 case Builtin::BI__builtin_cabsf:
5823 case Builtin::BI__builtin_cabs:
5824 case Builtin::BI__builtin_cabsl:
5825 return Builtin::BI__builtin_abs;
5826 case Builtin::BIfabsf:
5827 case Builtin::BIfabs:
5828 case Builtin::BIfabsl:
5829 case Builtin::BIcabsf:
5830 case Builtin::BIcabs:
5831 case Builtin::BIcabsl:
5832 return Builtin::BIabs;
5833 }
5834 case AVK_Floating:
5835 switch (AbsKind) {
5836 default:
5837 return 0;
5838 case Builtin::BI__builtin_abs:
5839 case Builtin::BI__builtin_labs:
5840 case Builtin::BI__builtin_llabs:
5841 case Builtin::BI__builtin_cabsf:
5842 case Builtin::BI__builtin_cabs:
5843 case Builtin::BI__builtin_cabsl:
5844 return Builtin::BI__builtin_fabsf;
5845 case Builtin::BIabs:
5846 case Builtin::BIlabs:
5847 case Builtin::BIllabs:
5848 case Builtin::BIcabsf:
5849 case Builtin::BIcabs:
5850 case Builtin::BIcabsl:
5851 return Builtin::BIfabsf;
5852 }
5853 case AVK_Complex:
5854 switch (AbsKind) {
5855 default:
5856 return 0;
5857 case Builtin::BI__builtin_abs:
5858 case Builtin::BI__builtin_labs:
5859 case Builtin::BI__builtin_llabs:
5860 case Builtin::BI__builtin_fabsf:
5861 case Builtin::BI__builtin_fabs:
5862 case Builtin::BI__builtin_fabsl:
5863 return Builtin::BI__builtin_cabsf;
5864 case Builtin::BIabs:
5865 case Builtin::BIlabs:
5866 case Builtin::BIllabs:
5867 case Builtin::BIfabsf:
5868 case Builtin::BIfabs:
5869 case Builtin::BIfabsl:
5870 return Builtin::BIcabsf;
5871 }
5872 }
5873 llvm_unreachable("Unable to convert function");
5874}
5875
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00005876static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005877 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
5878 if (!FnInfo)
5879 return 0;
5880
5881 switch (FDecl->getBuiltinID()) {
5882 default:
5883 return 0;
5884 case Builtin::BI__builtin_abs:
5885 case Builtin::BI__builtin_fabs:
5886 case Builtin::BI__builtin_fabsf:
5887 case Builtin::BI__builtin_fabsl:
5888 case Builtin::BI__builtin_labs:
5889 case Builtin::BI__builtin_llabs:
5890 case Builtin::BI__builtin_cabs:
5891 case Builtin::BI__builtin_cabsf:
5892 case Builtin::BI__builtin_cabsl:
5893 case Builtin::BIabs:
5894 case Builtin::BIlabs:
5895 case Builtin::BIllabs:
5896 case Builtin::BIfabs:
5897 case Builtin::BIfabsf:
5898 case Builtin::BIfabsl:
5899 case Builtin::BIcabs:
5900 case Builtin::BIcabsf:
5901 case Builtin::BIcabsl:
5902 return FDecl->getBuiltinID();
5903 }
5904 llvm_unreachable("Unknown Builtin type");
5905}
5906
5907// If the replacement is valid, emit a note with replacement function.
5908// Additionally, suggest including the proper header if not already included.
5909static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00005910 unsigned AbsKind, QualType ArgType) {
5911 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00005912 const char *HeaderName = nullptr;
5913 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005914 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
5915 FunctionName = "std::abs";
5916 if (ArgType->isIntegralOrEnumerationType()) {
5917 HeaderName = "cstdlib";
5918 } else if (ArgType->isRealFloatingType()) {
5919 HeaderName = "cmath";
5920 } else {
5921 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005922 }
Richard Trieubeffb832014-04-15 23:47:53 +00005923
5924 // Lookup all std::abs
5925 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00005926 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00005927 R.suppressDiagnostics();
5928 S.LookupQualifiedName(R, Std);
5929
5930 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005931 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005932 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
5933 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
5934 } else {
5935 FDecl = dyn_cast<FunctionDecl>(I);
5936 }
5937 if (!FDecl)
5938 continue;
5939
5940 // Found std::abs(), check that they are the right ones.
5941 if (FDecl->getNumParams() != 1)
5942 continue;
5943
5944 // Check that the parameter type can handle the argument.
5945 QualType ParamType = FDecl->getParamDecl(0)->getType();
5946 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
5947 S.Context.getTypeSize(ArgType) <=
5948 S.Context.getTypeSize(ParamType)) {
5949 // Found a function, don't need the header hint.
5950 EmitHeaderHint = false;
5951 break;
5952 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005953 }
Richard Trieubeffb832014-04-15 23:47:53 +00005954 }
5955 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00005956 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00005957 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
5958
5959 if (HeaderName) {
5960 DeclarationName DN(&S.Context.Idents.get(FunctionName));
5961 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
5962 R.suppressDiagnostics();
5963 S.LookupName(R, S.getCurScope());
5964
5965 if (R.isSingleResult()) {
5966 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
5967 if (FD && FD->getBuiltinID() == AbsKind) {
5968 EmitHeaderHint = false;
5969 } else {
5970 return;
5971 }
5972 } else if (!R.empty()) {
5973 return;
5974 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005975 }
5976 }
5977
5978 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00005979 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005980
Richard Trieubeffb832014-04-15 23:47:53 +00005981 if (!HeaderName)
5982 return;
5983
5984 if (!EmitHeaderHint)
5985 return;
5986
Alp Toker5d96e0a2014-07-11 20:53:51 +00005987 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5988 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00005989}
5990
5991static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5992 if (!FDecl)
5993 return false;
5994
5995 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5996 return false;
5997
5998 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5999
6000 while (ND && ND->isInlineNamespace()) {
6001 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006002 }
Richard Trieubeffb832014-04-15 23:47:53 +00006003
6004 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
6005 return false;
6006
6007 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
6008 return false;
6009
6010 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006011}
6012
6013// Warn when using the wrong abs() function.
6014void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
6015 const FunctionDecl *FDecl,
6016 IdentifierInfo *FnInfo) {
6017 if (Call->getNumArgs() != 1)
6018 return;
6019
6020 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00006021 bool IsStdAbs = IsFunctionStdAbs(FDecl);
6022 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006023 return;
6024
6025 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6026 QualType ParamType = Call->getArg(0)->getType();
6027
Alp Toker5d96e0a2014-07-11 20:53:51 +00006028 // Unsigned types cannot be negative. Suggest removing the absolute value
6029 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006030 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00006031 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00006032 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006033 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6034 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00006035 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006036 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6037 return;
6038 }
6039
David Majnemer7f77eb92015-11-15 03:04:34 +00006040 // Taking the absolute value of a pointer is very suspicious, they probably
6041 // wanted to index into an array, dereference a pointer, call a function, etc.
6042 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6043 unsigned DiagType = 0;
6044 if (ArgType->isFunctionType())
6045 DiagType = 1;
6046 else if (ArgType->isArrayType())
6047 DiagType = 2;
6048
6049 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6050 return;
6051 }
6052
Richard Trieubeffb832014-04-15 23:47:53 +00006053 // std::abs has overloads which prevent most of the absolute value problems
6054 // from occurring.
6055 if (IsStdAbs)
6056 return;
6057
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006058 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6059 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6060
6061 // The argument and parameter are the same kind. Check if they are the right
6062 // size.
6063 if (ArgValueKind == ParamValueKind) {
6064 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6065 return;
6066
6067 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6068 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6069 << FDecl << ArgType << ParamType;
6070
6071 if (NewAbsKind == 0)
6072 return;
6073
6074 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006075 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006076 return;
6077 }
6078
6079 // ArgValueKind != ParamValueKind
6080 // The wrong type of absolute value function was used. Attempt to find the
6081 // proper one.
6082 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6083 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6084 if (NewAbsKind == 0)
6085 return;
6086
6087 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6088 << FDecl << ParamValueKind << ArgValueKind;
6089
6090 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006091 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006092}
6093
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006094//===--- CHECK: Standard memory functions ---------------------------------===//
6095
Nico Weber0e6daef2013-12-26 23:38:39 +00006096/// \brief Takes the expression passed to the size_t parameter of functions
6097/// such as memcmp, strncat, etc and warns if it's a comparison.
6098///
6099/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6100static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6101 IdentifierInfo *FnName,
6102 SourceLocation FnLoc,
6103 SourceLocation RParenLoc) {
6104 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6105 if (!Size)
6106 return false;
6107
6108 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6109 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6110 return false;
6111
Nico Weber0e6daef2013-12-26 23:38:39 +00006112 SourceRange SizeRange = Size->getSourceRange();
6113 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6114 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00006115 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006116 << FnName << FixItHint::CreateInsertion(
6117 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00006118 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00006119 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00006120 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00006121 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6122 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00006123
6124 return true;
6125}
6126
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006127/// \brief Determine whether the given type is or contains a dynamic class type
6128/// (e.g., whether it has a vtable).
6129static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6130 bool &IsContained) {
6131 // Look through array types while ignoring qualifiers.
6132 const Type *Ty = T->getBaseElementTypeUnsafe();
6133 IsContained = false;
6134
6135 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6136 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00006137 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006138 return nullptr;
6139
6140 if (RD->isDynamicClass())
6141 return RD;
6142
6143 // Check all the fields. If any bases were dynamic, the class is dynamic.
6144 // It's impossible for a class to transitively contain itself by value, so
6145 // infinite recursion is impossible.
6146 for (auto *FD : RD->fields()) {
6147 bool SubContained;
6148 if (const CXXRecordDecl *ContainedRD =
6149 getContainedDynamicClass(FD->getType(), SubContained)) {
6150 IsContained = true;
6151 return ContainedRD;
6152 }
6153 }
6154
6155 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00006156}
6157
Chandler Carruth889ed862011-06-21 23:04:20 +00006158/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006159/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00006160static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00006161 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006162 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6163 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6164 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006165
Craig Topperc3ec1492014-05-26 06:22:03 +00006166 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006167}
6168
Chandler Carruth889ed862011-06-21 23:04:20 +00006169/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00006170static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006171 if (const UnaryExprOrTypeTraitExpr *SizeOf =
6172 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6173 if (SizeOf->getKind() == clang::UETT_SizeOf)
6174 return SizeOf->getTypeOfArgument();
6175
6176 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00006177}
6178
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006179/// \brief Check for dangerous or invalid arguments to memset().
6180///
Chandler Carruthac687262011-06-03 06:23:57 +00006181/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006182/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6183/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006184///
6185/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006186void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00006187 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006188 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00006189 assert(BId != 0);
6190
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006191 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00006192 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006193 unsigned ExpectedNumArgs =
6194 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00006195 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006196 return;
6197
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006198 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00006199 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006200 unsigned LenArg =
6201 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00006202 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006203
Nico Weber0e6daef2013-12-26 23:38:39 +00006204 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6205 Call->getLocStart(), Call->getRParenLoc()))
6206 return;
6207
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006208 // We have special checking when the length is a sizeof expression.
6209 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6210 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6211 llvm::FoldingSetNodeID SizeOfArgID;
6212
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00006213 // Although widely used, 'bzero' is not a standard function. Be more strict
6214 // with the argument types before allowing diagnostics and only allow the
6215 // form bzero(ptr, sizeof(...)).
6216 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6217 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
6218 return;
6219
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006220 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6221 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006222 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006223
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006224 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00006225 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006226 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00006227 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00006228
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006229 // Never warn about void type pointers. This can be used to suppress
6230 // false positives.
6231 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006232 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006233
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006234 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6235 // actually comparing the expressions for equality. Because computing the
6236 // expression IDs can be expensive, we only do this if the diagnostic is
6237 // enabled.
6238 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006239 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6240 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006241 // We only compute IDs for expressions if the warning is enabled, and
6242 // cache the sizeof arg's ID.
6243 if (SizeOfArgID == llvm::FoldingSetNodeID())
6244 SizeOfArg->Profile(SizeOfArgID, Context, true);
6245 llvm::FoldingSetNodeID DestID;
6246 Dest->Profile(DestID, Context, true);
6247 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00006248 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6249 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006250 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00006251 StringRef ReadableName = FnName->getName();
6252
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006253 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00006254 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006255 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00006256 if (!PointeeTy->isIncompleteType() &&
6257 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006258 ActionIdx = 2; // If the pointee's size is sizeof(char),
6259 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00006260
6261 // If the function is defined as a builtin macro, do not show macro
6262 // expansion.
6263 SourceLocation SL = SizeOfArg->getExprLoc();
6264 SourceRange DSR = Dest->getSourceRange();
6265 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006266 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00006267
6268 if (SM.isMacroArgExpansion(SL)) {
6269 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
6270 SL = SM.getSpellingLoc(SL);
6271 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
6272 SM.getSpellingLoc(DSR.getEnd()));
6273 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
6274 SM.getSpellingLoc(SSR.getEnd()));
6275 }
6276
Anna Zaksd08d9152012-05-30 23:14:52 +00006277 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006278 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00006279 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00006280 << PointeeTy
6281 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00006282 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00006283 << SSR);
6284 DiagRuntimeBehavior(SL, SizeOfArg,
6285 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
6286 << ActionIdx
6287 << SSR);
6288
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006289 break;
6290 }
6291 }
6292
6293 // Also check for cases where the sizeof argument is the exact same
6294 // type as the memory argument, and where it points to a user-defined
6295 // record type.
6296 if (SizeOfArgTy != QualType()) {
6297 if (PointeeTy->isRecordType() &&
6298 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
6299 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
6300 PDiag(diag::warn_sizeof_pointer_type_memaccess)
6301 << FnName << SizeOfArgTy << ArgIdx
6302 << PointeeTy << Dest->getSourceRange()
6303 << LenExpr->getSourceRange());
6304 break;
6305 }
Nico Weberc5e73862011-06-14 16:14:58 +00006306 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00006307 } else if (DestTy->isArrayType()) {
6308 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00006309 }
Nico Weberc5e73862011-06-14 16:14:58 +00006310
Nico Weberc44b35e2015-03-21 17:37:46 +00006311 if (PointeeTy == QualType())
6312 continue;
Anna Zaks22122702012-01-17 00:37:07 +00006313
Nico Weberc44b35e2015-03-21 17:37:46 +00006314 // Always complain about dynamic classes.
6315 bool IsContained;
6316 if (const CXXRecordDecl *ContainedRD =
6317 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00006318
Nico Weberc44b35e2015-03-21 17:37:46 +00006319 unsigned OperationType = 0;
6320 // "overwritten" if we're warning about the destination for any call
6321 // but memcmp; otherwise a verb appropriate to the call.
6322 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
6323 if (BId == Builtin::BImemcpy)
6324 OperationType = 1;
6325 else if(BId == Builtin::BImemmove)
6326 OperationType = 2;
6327 else if (BId == Builtin::BImemcmp)
6328 OperationType = 3;
6329 }
6330
John McCall31168b02011-06-15 23:02:42 +00006331 DiagRuntimeBehavior(
6332 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00006333 PDiag(diag::warn_dyn_class_memaccess)
6334 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
6335 << FnName << IsContained << ContainedRD << OperationType
6336 << Call->getCallee()->getSourceRange());
6337 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
6338 BId != Builtin::BImemset)
6339 DiagRuntimeBehavior(
6340 Dest->getExprLoc(), Dest,
6341 PDiag(diag::warn_arc_object_memaccess)
6342 << ArgIdx << FnName << PointeeTy
6343 << Call->getCallee()->getSourceRange());
6344 else
6345 continue;
6346
6347 DiagRuntimeBehavior(
6348 Dest->getExprLoc(), Dest,
6349 PDiag(diag::note_bad_memaccess_silence)
6350 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
6351 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006352 }
6353}
6354
Ted Kremenek6865f772011-08-18 20:55:45 +00006355// A little helper routine: ignore addition and subtraction of integer literals.
6356// This intentionally does not ignore all integer constant expressions because
6357// we don't want to remove sizeof().
6358static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
6359 Ex = Ex->IgnoreParenCasts();
6360
6361 for (;;) {
6362 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
6363 if (!BO || !BO->isAdditiveOp())
6364 break;
6365
6366 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
6367 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
6368
6369 if (isa<IntegerLiteral>(RHS))
6370 Ex = LHS;
6371 else if (isa<IntegerLiteral>(LHS))
6372 Ex = RHS;
6373 else
6374 break;
6375 }
6376
6377 return Ex;
6378}
6379
Anna Zaks13b08572012-08-08 21:42:23 +00006380static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
6381 ASTContext &Context) {
6382 // Only handle constant-sized or VLAs, but not flexible members.
6383 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
6384 // Only issue the FIXIT for arrays of size > 1.
6385 if (CAT->getSize().getSExtValue() <= 1)
6386 return false;
6387 } else if (!Ty->isVariableArrayType()) {
6388 return false;
6389 }
6390 return true;
6391}
6392
Ted Kremenek6865f772011-08-18 20:55:45 +00006393// Warn if the user has made the 'size' argument to strlcpy or strlcat
6394// be the size of the source, instead of the destination.
6395void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
6396 IdentifierInfo *FnName) {
6397
6398 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00006399 unsigned NumArgs = Call->getNumArgs();
6400 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00006401 return;
6402
6403 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
6404 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00006405 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00006406
6407 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
6408 Call->getLocStart(), Call->getRParenLoc()))
6409 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00006410
6411 // Look for 'strlcpy(dst, x, sizeof(x))'
6412 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
6413 CompareWithSrc = Ex;
6414 else {
6415 // Look for 'strlcpy(dst, x, strlen(x))'
6416 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00006417 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
6418 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00006419 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
6420 }
6421 }
6422
6423 if (!CompareWithSrc)
6424 return;
6425
6426 // Determine if the argument to sizeof/strlen is equal to the source
6427 // argument. In principle there's all kinds of things you could do
6428 // here, for instance creating an == expression and evaluating it with
6429 // EvaluateAsBooleanCondition, but this uses a more direct technique:
6430 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
6431 if (!SrcArgDRE)
6432 return;
6433
6434 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
6435 if (!CompareWithSrcDRE ||
6436 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
6437 return;
6438
6439 const Expr *OriginalSizeArg = Call->getArg(2);
6440 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
6441 << OriginalSizeArg->getSourceRange() << FnName;
6442
6443 // Output a FIXIT hint if the destination is an array (rather than a
6444 // pointer to an array). This could be enhanced to handle some
6445 // pointers if we know the actual size, like if DstArg is 'array+2'
6446 // we could say 'sizeof(array)-2'.
6447 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00006448 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00006449 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00006450
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006451 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00006452 llvm::raw_svector_ostream OS(sizeString);
6453 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006454 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00006455 OS << ")";
6456
6457 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
6458 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
6459 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00006460}
6461
Anna Zaks314cd092012-02-01 19:08:57 +00006462/// Check if two expressions refer to the same declaration.
6463static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
6464 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
6465 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
6466 return D1->getDecl() == D2->getDecl();
6467 return false;
6468}
6469
6470static const Expr *getStrlenExprArg(const Expr *E) {
6471 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6472 const FunctionDecl *FD = CE->getDirectCallee();
6473 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00006474 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00006475 return CE->getArg(0)->IgnoreParenCasts();
6476 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006477 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00006478}
6479
6480// Warn on anti-patterns as the 'size' argument to strncat.
6481// The correct size argument should look like following:
6482// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
6483void Sema::CheckStrncatArguments(const CallExpr *CE,
6484 IdentifierInfo *FnName) {
6485 // Don't crash if the user has the wrong number of arguments.
6486 if (CE->getNumArgs() < 3)
6487 return;
6488 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
6489 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
6490 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
6491
Nico Weber0e6daef2013-12-26 23:38:39 +00006492 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
6493 CE->getRParenLoc()))
6494 return;
6495
Anna Zaks314cd092012-02-01 19:08:57 +00006496 // Identify common expressions, which are wrongly used as the size argument
6497 // to strncat and may lead to buffer overflows.
6498 unsigned PatternType = 0;
6499 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
6500 // - sizeof(dst)
6501 if (referToTheSameDecl(SizeOfArg, DstArg))
6502 PatternType = 1;
6503 // - sizeof(src)
6504 else if (referToTheSameDecl(SizeOfArg, SrcArg))
6505 PatternType = 2;
6506 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
6507 if (BE->getOpcode() == BO_Sub) {
6508 const Expr *L = BE->getLHS()->IgnoreParenCasts();
6509 const Expr *R = BE->getRHS()->IgnoreParenCasts();
6510 // - sizeof(dst) - strlen(dst)
6511 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
6512 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
6513 PatternType = 1;
6514 // - sizeof(src) - (anything)
6515 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
6516 PatternType = 2;
6517 }
6518 }
6519
6520 if (PatternType == 0)
6521 return;
6522
Anna Zaks5069aa32012-02-03 01:27:37 +00006523 // Generate the diagnostic.
6524 SourceLocation SL = LenArg->getLocStart();
6525 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006526 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00006527
6528 // If the function is defined as a builtin macro, do not show macro expansion.
6529 if (SM.isMacroArgExpansion(SL)) {
6530 SL = SM.getSpellingLoc(SL);
6531 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
6532 SM.getSpellingLoc(SR.getEnd()));
6533 }
6534
Anna Zaks13b08572012-08-08 21:42:23 +00006535 // Check if the destination is an array (rather than a pointer to an array).
6536 QualType DstTy = DstArg->getType();
6537 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
6538 Context);
6539 if (!isKnownSizeArray) {
6540 if (PatternType == 1)
6541 Diag(SL, diag::warn_strncat_wrong_size) << SR;
6542 else
6543 Diag(SL, diag::warn_strncat_src_size) << SR;
6544 return;
6545 }
6546
Anna Zaks314cd092012-02-01 19:08:57 +00006547 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00006548 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006549 else
Anna Zaks5069aa32012-02-03 01:27:37 +00006550 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006551
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006552 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00006553 llvm::raw_svector_ostream OS(sizeString);
6554 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006555 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006556 OS << ") - ";
6557 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006558 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006559 OS << ") - 1";
6560
Anna Zaks5069aa32012-02-03 01:27:37 +00006561 Diag(SL, diag::note_strncat_wrong_size)
6562 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00006563}
6564
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006565//===--- CHECK: Return Address of Stack Variable --------------------------===//
6566
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006567static const Expr *EvalVal(const Expr *E,
6568 SmallVectorImpl<const DeclRefExpr *> &refVars,
6569 const Decl *ParentDecl);
6570static const Expr *EvalAddr(const Expr *E,
6571 SmallVectorImpl<const DeclRefExpr *> &refVars,
6572 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006573
6574/// CheckReturnStackAddr - Check if a return statement returns the address
6575/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006576static void
6577CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
6578 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00006579
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006580 const Expr *stackE = nullptr;
6581 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006582
6583 // Perform checking for returned stack addresses, local blocks,
6584 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00006585 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006586 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006587 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00006588 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006589 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006590 }
6591
Craig Topperc3ec1492014-05-26 06:22:03 +00006592 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006593 return; // Nothing suspicious was found.
6594
Richard Trieu81b6c562016-08-05 23:24:47 +00006595 // Parameters are initalized in the calling scope, so taking the address
6596 // of a parameter reference doesn't need a warning.
6597 for (auto *DRE : refVars)
6598 if (isa<ParmVarDecl>(DRE->getDecl()))
6599 return;
6600
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006601 SourceLocation diagLoc;
6602 SourceRange diagRange;
6603 if (refVars.empty()) {
6604 diagLoc = stackE->getLocStart();
6605 diagRange = stackE->getSourceRange();
6606 } else {
6607 // We followed through a reference variable. 'stackE' contains the
6608 // problematic expression but we will warn at the return statement pointing
6609 // at the reference variable. We will later display the "trail" of
6610 // reference variables using notes.
6611 diagLoc = refVars[0]->getLocStart();
6612 diagRange = refVars[0]->getSourceRange();
6613 }
6614
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006615 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
6616 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00006617 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006618 << DR->getDecl()->getDeclName() << diagRange;
6619 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006620 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006621 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006622 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006623 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00006624 // If there is an LValue->RValue conversion, then the value of the
6625 // reference type is used, not the reference.
6626 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
6627 if (ICE->getCastKind() == CK_LValueToRValue) {
6628 return;
6629 }
6630 }
Craig Topperda7b27f2015-11-17 05:40:09 +00006631 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
6632 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006633 }
6634
6635 // Display the "trail" of reference variables that we followed until we
6636 // found the problematic expression using notes.
6637 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006638 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006639 // If this var binds to another reference var, show the range of the next
6640 // var, otherwise the var binds to the problematic expression, in which case
6641 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006642 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
6643 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006644 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
6645 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006646 }
6647}
6648
6649/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
6650/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006651/// to a location on the stack, a local block, an address of a label, or a
6652/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006653/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006654/// encounter a subexpression that (1) clearly does not lead to one of the
6655/// above problematic expressions (2) is something we cannot determine leads to
6656/// a problematic expression based on such local checking.
6657///
6658/// Both EvalAddr and EvalVal follow through reference variables to evaluate
6659/// the expression that they point to. Such variables are added to the
6660/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006661///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00006662/// EvalAddr processes expressions that are pointers that are used as
6663/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006664/// At the base case of the recursion is a check for the above problematic
6665/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006666///
6667/// This implementation handles:
6668///
6669/// * pointer-to-pointer casts
6670/// * implicit conversions from array references to pointers
6671/// * taking the address of fields
6672/// * arbitrary interplay between "&" and "*" operators
6673/// * pointer arithmetic from an address of a stack variable
6674/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006675static const Expr *EvalAddr(const Expr *E,
6676 SmallVectorImpl<const DeclRefExpr *> &refVars,
6677 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006678 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00006679 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006680
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006681 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00006682 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00006683 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006684 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00006685 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00006686
Peter Collingbourne91147592011-04-15 00:35:48 +00006687 E = E->IgnoreParens();
6688
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006689 // Our "symbolic interpreter" is just a dispatch off the currently
6690 // viewed AST node. We then recursively traverse the AST by calling
6691 // EvalAddr and EvalVal appropriately.
6692 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006693 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006694 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006695
Richard Smith40f08eb2014-01-30 22:05:38 +00006696 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00006697 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00006698 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00006699
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006700 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006701 // If this is a reference variable, follow through to the expression that
6702 // it points to.
6703 if (V->hasLocalStorage() &&
6704 V->getType()->isReferenceType() && V->hasInit()) {
6705 // Add the reference variable to the "trail".
6706 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006707 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006708 }
6709
Craig Topperc3ec1492014-05-26 06:22:03 +00006710 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006711 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006712
Chris Lattner934edb22007-12-28 05:31:15 +00006713 case Stmt::UnaryOperatorClass: {
6714 // The only unary operator that make sense to handle here
6715 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006716 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006717
John McCalle3027922010-08-25 11:45:40 +00006718 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006719 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006720 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006721 }
Mike Stump11289f42009-09-09 15:08:12 +00006722
Chris Lattner934edb22007-12-28 05:31:15 +00006723 case Stmt::BinaryOperatorClass: {
6724 // Handle pointer arithmetic. All other binary operators are not valid
6725 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006726 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00006727 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00006728
John McCalle3027922010-08-25 11:45:40 +00006729 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00006730 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006731
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006732 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00006733
6734 // Determine which argument is the real pointer base. It could be
6735 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006736 if (!Base->getType()->isPointerType())
6737 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00006738
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006739 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006740 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006741 }
Steve Naroff2752a172008-09-10 19:17:48 +00006742
Chris Lattner934edb22007-12-28 05:31:15 +00006743 // For conditional operators we need to see if either the LHS or RHS are
6744 // valid DeclRefExpr*s. If one of them is valid, we return it.
6745 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006746 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006747
Chris Lattner934edb22007-12-28 05:31:15 +00006748 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006749 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006750 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006751 // In C++, we can have a throw-expression, which has 'void' type.
6752 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006753 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006754 return LHS;
6755 }
Chris Lattner934edb22007-12-28 05:31:15 +00006756
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006757 // In C++, we can have a throw-expression, which has 'void' type.
6758 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00006759 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006760
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006761 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006762 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006763
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006764 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00006765 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006766 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00006767 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006768
6769 case Stmt::AddrLabelExprClass:
6770 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00006771
John McCall28fc7092011-11-10 05:35:25 +00006772 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006773 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6774 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00006775
Ted Kremenekc3b4c522008-08-07 00:49:01 +00006776 // For casts, we need to handle conversions from arrays to
6777 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00006778 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00006779 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00006780 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00006781 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00006782 case Stmt::CXXStaticCastExprClass:
6783 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00006784 case Stmt::CXXConstCastExprClass:
6785 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006786 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00006787 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00006788 case CK_LValueToRValue:
6789 case CK_NoOp:
6790 case CK_BaseToDerived:
6791 case CK_DerivedToBase:
6792 case CK_UncheckedDerivedToBase:
6793 case CK_Dynamic:
6794 case CK_CPointerToObjCPointerCast:
6795 case CK_BlockPointerToObjCPointerCast:
6796 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006797 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006798
6799 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006800 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006801
Richard Trieudadefde2014-07-02 04:39:38 +00006802 case CK_BitCast:
6803 if (SubExpr->getType()->isAnyPointerType() ||
6804 SubExpr->getType()->isBlockPointerType() ||
6805 SubExpr->getType()->isObjCQualifiedIdType())
6806 return EvalAddr(SubExpr, refVars, ParentDecl);
6807 else
6808 return nullptr;
6809
Eli Friedman8195ad72012-02-23 23:04:32 +00006810 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006811 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00006812 }
Chris Lattner934edb22007-12-28 05:31:15 +00006813 }
Mike Stump11289f42009-09-09 15:08:12 +00006814
Douglas Gregorfe314812011-06-21 17:03:29 +00006815 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006816 if (const Expr *Result =
6817 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6818 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00006819 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00006820 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006821
Chris Lattner934edb22007-12-28 05:31:15 +00006822 // Everything else: we simply don't reason about them.
6823 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006824 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00006825 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006826}
Mike Stump11289f42009-09-09 15:08:12 +00006827
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006828/// EvalVal - This function is complements EvalAddr in the mutual recursion.
6829/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006830static const Expr *EvalVal(const Expr *E,
6831 SmallVectorImpl<const DeclRefExpr *> &refVars,
6832 const Decl *ParentDecl) {
6833 do {
6834 // We should only be called for evaluating non-pointer expressions, or
6835 // expressions with a pointer type that are not used as references but
6836 // instead
6837 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00006838
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006839 // Our "symbolic interpreter" is just a dispatch off the currently
6840 // viewed AST node. We then recursively traverse the AST by calling
6841 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00006842
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006843 E = E->IgnoreParens();
6844 switch (E->getStmtClass()) {
6845 case Stmt::ImplicitCastExprClass: {
6846 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
6847 if (IE->getValueKind() == VK_LValue) {
6848 E = IE->getSubExpr();
6849 continue;
6850 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006851 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006852 }
Richard Smith40f08eb2014-01-30 22:05:38 +00006853
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006854 case Stmt::ExprWithCleanupsClass:
6855 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6856 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006857
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006858 case Stmt::DeclRefExprClass: {
6859 // When we hit a DeclRefExpr we are looking at code that refers to a
6860 // variable's name. If it's not a reference variable we check if it has
6861 // local storage within the function, and if so, return the expression.
6862 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6863
6864 // If we leave the immediate function, the lifetime isn't about to end.
6865 if (DR->refersToEnclosingVariableOrCapture())
6866 return nullptr;
6867
6868 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
6869 // Check if it refers to itself, e.g. "int& i = i;".
6870 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006871 return DR;
6872
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006873 if (V->hasLocalStorage()) {
6874 if (!V->getType()->isReferenceType())
6875 return DR;
6876
6877 // Reference variable, follow through to the expression that
6878 // it points to.
6879 if (V->hasInit()) {
6880 // Add the reference variable to the "trail".
6881 refVars.push_back(DR);
6882 return EvalVal(V->getInit(), refVars, V);
6883 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006884 }
6885 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006886
6887 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006888 }
Mike Stump11289f42009-09-09 15:08:12 +00006889
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006890 case Stmt::UnaryOperatorClass: {
6891 // The only unary operator that make sense to handle here
6892 // is Deref. All others don't resolve to a "name." This includes
6893 // handling all sorts of rvalues passed to a unary operator.
6894 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006895
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006896 if (U->getOpcode() == UO_Deref)
6897 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006898
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006899 return nullptr;
6900 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006901
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006902 case Stmt::ArraySubscriptExprClass: {
6903 // Array subscripts are potential references to data on the stack. We
6904 // retrieve the DeclRefExpr* for the array variable if it indeed
6905 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00006906 const auto *ASE = cast<ArraySubscriptExpr>(E);
6907 if (ASE->isTypeDependent())
6908 return nullptr;
6909 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006910 }
Mike Stump11289f42009-09-09 15:08:12 +00006911
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006912 case Stmt::OMPArraySectionExprClass: {
6913 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
6914 ParentDecl);
6915 }
Mike Stump11289f42009-09-09 15:08:12 +00006916
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006917 case Stmt::ConditionalOperatorClass: {
6918 // For conditional operators we need to see if either the LHS or RHS are
6919 // non-NULL Expr's. If one is non-NULL, we return it.
6920 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006921
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006922 // Handle the GNU extension for missing LHS.
6923 if (const Expr *LHSExpr = C->getLHS()) {
6924 // In C++, we can have a throw-expression, which has 'void' type.
6925 if (!LHSExpr->getType()->isVoidType())
6926 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
6927 return LHS;
6928 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006929
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006930 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006931 if (C->getRHS()->getType()->isVoidType())
6932 return nullptr;
6933
6934 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006935 }
6936
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006937 // Accesses to members are potential references to data on the stack.
6938 case Stmt::MemberExprClass: {
6939 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00006940
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006941 // Check for indirect access. We only want direct field accesses.
6942 if (M->isArrow())
6943 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006944
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006945 // Check whether the member type is itself a reference, in which case
6946 // we're not going to refer to the member, but to what the member refers
6947 // to.
6948 if (M->getMemberDecl()->getType()->isReferenceType())
6949 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006950
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006951 return EvalVal(M->getBase(), refVars, ParentDecl);
6952 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00006953
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006954 case Stmt::MaterializeTemporaryExprClass:
6955 if (const Expr *Result =
6956 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6957 refVars, ParentDecl))
6958 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006959 return E;
6960
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006961 default:
6962 // Check that we don't return or take the address of a reference to a
6963 // temporary. This is only useful in C++.
6964 if (!E->isTypeDependent() && E->isRValue())
6965 return E;
6966
6967 // Everything else: we simply don't reason about them.
6968 return nullptr;
6969 }
6970 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006971}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006972
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006973void
6974Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
6975 SourceLocation ReturnLoc,
6976 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00006977 const AttrVec *Attrs,
6978 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006979 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
6980
6981 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00006982 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6983 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00006984 CheckNonNullExpr(*this, RetValExp))
6985 Diag(ReturnLoc, diag::warn_null_ret)
6986 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00006987
6988 // C++11 [basic.stc.dynamic.allocation]p4:
6989 // If an allocation function declared with a non-throwing
6990 // exception-specification fails to allocate storage, it shall return
6991 // a null pointer. Any other allocation function that fails to allocate
6992 // storage shall indicate failure only by throwing an exception [...]
6993 if (FD) {
6994 OverloadedOperatorKind Op = FD->getOverloadedOperator();
6995 if (Op == OO_New || Op == OO_Array_New) {
6996 const FunctionProtoType *Proto
6997 = FD->getType()->castAs<FunctionProtoType>();
6998 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6999 CheckNonNullExpr(*this, RetValExp))
7000 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7001 << FD << getLangOpts().CPlusPlus11;
7002 }
7003 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007004}
7005
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007006//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7007
7008/// Check for comparisons of floating point operands using != and ==.
7009/// Issue a warning if these are no self-comparisons, as they are not likely
7010/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00007011void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00007012 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7013 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007014
7015 // Special case: check for x == x (which is OK).
7016 // Do not emit warnings for such cases.
7017 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7018 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7019 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00007020 return;
Mike Stump11289f42009-09-09 15:08:12 +00007021
Ted Kremenekeda40e22007-11-29 00:59:04 +00007022 // Special case: check for comparisons against literals that can be exactly
7023 // represented by APFloat. In such cases, do not emit a warning. This
7024 // is a heuristic: often comparison against such literals are used to
7025 // detect if a value in a variable has not changed. This clearly can
7026 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00007027 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7028 if (FLL->isExact())
7029 return;
7030 } else
7031 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7032 if (FLR->isExact())
7033 return;
Mike Stump11289f42009-09-09 15:08:12 +00007034
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007035 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00007036 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007037 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007038 return;
Mike Stump11289f42009-09-09 15:08:12 +00007039
David Blaikie1f4ff152012-07-16 20:47:22 +00007040 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007041 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007042 return;
Mike Stump11289f42009-09-09 15:08:12 +00007043
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007044 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00007045 Diag(Loc, diag::warn_floatingpoint_eq)
7046 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007047}
John McCallca01b222010-01-04 23:21:16 +00007048
John McCall70aa5392010-01-06 05:24:50 +00007049//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7050//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00007051
John McCall70aa5392010-01-06 05:24:50 +00007052namespace {
John McCallca01b222010-01-04 23:21:16 +00007053
John McCall70aa5392010-01-06 05:24:50 +00007054/// Structure recording the 'active' range of an integer-valued
7055/// expression.
7056struct IntRange {
7057 /// The number of bits active in the int.
7058 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00007059
John McCall70aa5392010-01-06 05:24:50 +00007060 /// True if the int is known not to have negative values.
7061 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00007062
John McCall70aa5392010-01-06 05:24:50 +00007063 IntRange(unsigned Width, bool NonNegative)
7064 : Width(Width), NonNegative(NonNegative)
7065 {}
John McCallca01b222010-01-04 23:21:16 +00007066
John McCall817d4af2010-11-10 23:38:19 +00007067 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00007068 static IntRange forBoolType() {
7069 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00007070 }
7071
John McCall817d4af2010-11-10 23:38:19 +00007072 /// Returns the range of an opaque value of the given integral type.
7073 static IntRange forValueOfType(ASTContext &C, QualType T) {
7074 return forValueOfCanonicalType(C,
7075 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00007076 }
7077
John McCall817d4af2010-11-10 23:38:19 +00007078 /// Returns the range of an opaque value of a canonical integral type.
7079 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00007080 assert(T->isCanonicalUnqualified());
7081
7082 if (const VectorType *VT = dyn_cast<VectorType>(T))
7083 T = VT->getElementType().getTypePtr();
7084 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7085 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007086 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7087 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00007088
David Majnemer6a426652013-06-07 22:07:20 +00007089 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00007090 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00007091 EnumDecl *Enum = ET->getDecl();
7092 if (!Enum->isCompleteDefinition())
7093 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00007094
David Majnemer6a426652013-06-07 22:07:20 +00007095 unsigned NumPositive = Enum->getNumPositiveBits();
7096 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00007097
David Majnemer6a426652013-06-07 22:07:20 +00007098 if (NumNegative == 0)
7099 return IntRange(NumPositive, true/*NonNegative*/);
7100 else
7101 return IntRange(std::max(NumPositive + 1, NumNegative),
7102 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00007103 }
John McCall70aa5392010-01-06 05:24:50 +00007104
7105 const BuiltinType *BT = cast<BuiltinType>(T);
7106 assert(BT->isInteger());
7107
7108 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7109 }
7110
John McCall817d4af2010-11-10 23:38:19 +00007111 /// Returns the "target" range of a canonical integral type, i.e.
7112 /// the range of values expressible in the type.
7113 ///
7114 /// This matches forValueOfCanonicalType except that enums have the
7115 /// full range of their type, not the range of their enumerators.
7116 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7117 assert(T->isCanonicalUnqualified());
7118
7119 if (const VectorType *VT = dyn_cast<VectorType>(T))
7120 T = VT->getElementType().getTypePtr();
7121 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7122 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007123 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7124 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007125 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00007126 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007127
7128 const BuiltinType *BT = cast<BuiltinType>(T);
7129 assert(BT->isInteger());
7130
7131 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7132 }
7133
7134 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00007135 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00007136 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00007137 L.NonNegative && R.NonNegative);
7138 }
7139
John McCall817d4af2010-11-10 23:38:19 +00007140 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00007141 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00007142 return IntRange(std::min(L.Width, R.Width),
7143 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00007144 }
7145};
7146
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007147IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007148 if (value.isSigned() && value.isNegative())
7149 return IntRange(value.getMinSignedBits(), false);
7150
7151 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00007152 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007153
7154 // isNonNegative() just checks the sign bit without considering
7155 // signedness.
7156 return IntRange(value.getActiveBits(), true);
7157}
7158
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007159IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7160 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007161 if (result.isInt())
7162 return GetValueRange(C, result.getInt(), MaxWidth);
7163
7164 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00007165 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7166 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7167 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7168 R = IntRange::join(R, El);
7169 }
John McCall70aa5392010-01-06 05:24:50 +00007170 return R;
7171 }
7172
7173 if (result.isComplexInt()) {
7174 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7175 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7176 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00007177 }
7178
7179 // This can happen with lossless casts to intptr_t of "based" lvalues.
7180 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00007181 // FIXME: The only reason we need to pass the type in here is to get
7182 // the sign right on this one case. It would be nice if APValue
7183 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007184 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00007185 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00007186}
John McCall70aa5392010-01-06 05:24:50 +00007187
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007188QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007189 QualType Ty = E->getType();
7190 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7191 Ty = AtomicRHS->getValueType();
7192 return Ty;
7193}
7194
John McCall70aa5392010-01-06 05:24:50 +00007195/// Pseudo-evaluate the given integer expression, estimating the
7196/// range of values it might take.
7197///
7198/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007199IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007200 E = E->IgnoreParens();
7201
7202 // Try a full evaluation first.
7203 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007204 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00007205 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007206
7207 // I think we only want to look through implicit casts here; if the
7208 // user has an explicit widening cast, we should treat the value as
7209 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007210 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00007211 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00007212 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7213
Eli Friedmane6d33952013-07-08 20:20:06 +00007214 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00007215
George Burgess IVdf1ed002016-01-13 01:52:39 +00007216 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7217 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00007218
John McCall70aa5392010-01-06 05:24:50 +00007219 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00007220 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00007221 return OutputTypeRange;
7222
7223 IntRange SubRange
7224 = GetExprRange(C, CE->getSubExpr(),
7225 std::min(MaxWidth, OutputTypeRange.Width));
7226
7227 // Bail out if the subexpr's range is as wide as the cast type.
7228 if (SubRange.Width >= OutputTypeRange.Width)
7229 return OutputTypeRange;
7230
7231 // Otherwise, we take the smaller width, and we're non-negative if
7232 // either the output type or the subexpr is.
7233 return IntRange(SubRange.Width,
7234 SubRange.NonNegative || OutputTypeRange.NonNegative);
7235 }
7236
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007237 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007238 // If we can fold the condition, just take that operand.
7239 bool CondResult;
7240 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7241 return GetExprRange(C, CondResult ? CO->getTrueExpr()
7242 : CO->getFalseExpr(),
7243 MaxWidth);
7244
7245 // Otherwise, conservatively merge.
7246 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7247 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7248 return IntRange::join(L, R);
7249 }
7250
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007251 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007252 switch (BO->getOpcode()) {
7253
7254 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00007255 case BO_LAnd:
7256 case BO_LOr:
7257 case BO_LT:
7258 case BO_GT:
7259 case BO_LE:
7260 case BO_GE:
7261 case BO_EQ:
7262 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00007263 return IntRange::forBoolType();
7264
John McCallc3688382011-07-13 06:35:24 +00007265 // The type of the assignments is the type of the LHS, so the RHS
7266 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00007267 case BO_MulAssign:
7268 case BO_DivAssign:
7269 case BO_RemAssign:
7270 case BO_AddAssign:
7271 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00007272 case BO_XorAssign:
7273 case BO_OrAssign:
7274 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00007275 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00007276
John McCallc3688382011-07-13 06:35:24 +00007277 // Simple assignments just pass through the RHS, which will have
7278 // been coerced to the LHS type.
7279 case BO_Assign:
7280 // TODO: bitfields?
7281 return GetExprRange(C, BO->getRHS(), MaxWidth);
7282
John McCall70aa5392010-01-06 05:24:50 +00007283 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00007284 case BO_PtrMemD:
7285 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00007286 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007287
John McCall2ce81ad2010-01-06 22:07:33 +00007288 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00007289 case BO_And:
7290 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00007291 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
7292 GetExprRange(C, BO->getRHS(), MaxWidth));
7293
John McCall70aa5392010-01-06 05:24:50 +00007294 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00007295 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00007296 // ...except that we want to treat '1 << (blah)' as logically
7297 // positive. It's an important idiom.
7298 if (IntegerLiteral *I
7299 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
7300 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007301 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00007302 return IntRange(R.Width, /*NonNegative*/ true);
7303 }
7304 }
7305 // fallthrough
7306
John McCalle3027922010-08-25 11:45:40 +00007307 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00007308 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007309
John McCall2ce81ad2010-01-06 22:07:33 +00007310 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00007311 case BO_Shr:
7312 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00007313 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7314
7315 // If the shift amount is a positive constant, drop the width by
7316 // that much.
7317 llvm::APSInt shift;
7318 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
7319 shift.isNonNegative()) {
7320 unsigned zext = shift.getZExtValue();
7321 if (zext >= L.Width)
7322 L.Width = (L.NonNegative ? 0 : 1);
7323 else
7324 L.Width -= zext;
7325 }
7326
7327 return L;
7328 }
7329
7330 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00007331 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00007332 return GetExprRange(C, BO->getRHS(), MaxWidth);
7333
John McCall2ce81ad2010-01-06 22:07:33 +00007334 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00007335 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00007336 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00007337 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007338 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007339
John McCall51431812011-07-14 22:39:48 +00007340 // The width of a division result is mostly determined by the size
7341 // of the LHS.
7342 case BO_Div: {
7343 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00007344 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007345 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7346
7347 // If the divisor is constant, use that.
7348 llvm::APSInt divisor;
7349 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
7350 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
7351 if (log2 >= L.Width)
7352 L.Width = (L.NonNegative ? 0 : 1);
7353 else
7354 L.Width = std::min(L.Width - log2, MaxWidth);
7355 return L;
7356 }
7357
7358 // Otherwise, just use the LHS's width.
7359 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7360 return IntRange(L.Width, L.NonNegative && R.NonNegative);
7361 }
7362
7363 // The result of a remainder can't be larger than the result of
7364 // either side.
7365 case BO_Rem: {
7366 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00007367 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007368 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7369 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7370
7371 IntRange meet = IntRange::meet(L, R);
7372 meet.Width = std::min(meet.Width, MaxWidth);
7373 return meet;
7374 }
7375
7376 // The default behavior is okay for these.
7377 case BO_Mul:
7378 case BO_Add:
7379 case BO_Xor:
7380 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00007381 break;
7382 }
7383
John McCall51431812011-07-14 22:39:48 +00007384 // The default case is to treat the operation as if it were closed
7385 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00007386 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7387 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
7388 return IntRange::join(L, R);
7389 }
7390
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007391 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007392 switch (UO->getOpcode()) {
7393 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00007394 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00007395 return IntRange::forBoolType();
7396
7397 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00007398 case UO_Deref:
7399 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00007400 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007401
7402 default:
7403 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
7404 }
7405 }
7406
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007407 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00007408 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
7409
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007410 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00007411 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00007412 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00007413
Eli Friedmane6d33952013-07-08 20:20:06 +00007414 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007415}
John McCall263a48b2010-01-04 23:31:57 +00007416
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007417IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007418 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00007419}
7420
John McCall263a48b2010-01-04 23:31:57 +00007421/// Checks whether the given value, which currently has the given
7422/// source semantics, has the same value when coerced through the
7423/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007424bool IsSameFloatAfterCast(const llvm::APFloat &value,
7425 const llvm::fltSemantics &Src,
7426 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00007427 llvm::APFloat truncated = value;
7428
7429 bool ignored;
7430 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
7431 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
7432
7433 return truncated.bitwiseIsEqual(value);
7434}
7435
7436/// Checks whether the given value, which currently has the given
7437/// source semantics, has the same value when coerced through the
7438/// target semantics.
7439///
7440/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007441bool IsSameFloatAfterCast(const APValue &value,
7442 const llvm::fltSemantics &Src,
7443 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00007444 if (value.isFloat())
7445 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
7446
7447 if (value.isVector()) {
7448 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
7449 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
7450 return false;
7451 return true;
7452 }
7453
7454 assert(value.isComplexFloat());
7455 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
7456 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
7457}
7458
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007459void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007460
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007461bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00007462 // Suppress cases where we are comparing against an enum constant.
7463 if (const DeclRefExpr *DR =
7464 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
7465 if (isa<EnumConstantDecl>(DR->getDecl()))
7466 return false;
7467
7468 // Suppress cases where the '0' value is expanded from a macro.
7469 if (E->getLocStart().isMacroID())
7470 return false;
7471
John McCallcc7e5bf2010-05-06 08:58:33 +00007472 llvm::APSInt Value;
7473 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
7474}
7475
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007476bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00007477 // Strip off implicit integral promotions.
7478 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00007479 if (ICE->getCastKind() != CK_IntegralCast &&
7480 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00007481 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00007482 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00007483 }
7484
7485 return E->getType()->isEnumeralType();
7486}
7487
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007488void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00007489 // Disable warning in template instantiations.
7490 if (!S.ActiveTemplateInstantiations.empty())
7491 return;
7492
John McCalle3027922010-08-25 11:45:40 +00007493 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00007494 if (E->isValueDependent())
7495 return;
7496
John McCalle3027922010-08-25 11:45:40 +00007497 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007498 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007499 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007500 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007501 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007502 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007503 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007504 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007505 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007506 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007507 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007508 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007509 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007510 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007511 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007512 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7513 }
7514}
7515
Benjamin Kramer7320b992016-06-15 14:20:56 +00007516void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
7517 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007518 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00007519 // Disable warning in template instantiations.
7520 if (!S.ActiveTemplateInstantiations.empty())
7521 return;
7522
Richard Trieu0f097742014-04-04 04:13:47 +00007523 // TODO: Investigate using GetExprRange() to get tighter bounds
7524 // on the bit ranges.
7525 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00007526 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00007527 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00007528 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
7529 unsigned OtherWidth = OtherRange.Width;
7530
7531 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
7532
Richard Trieu560910c2012-11-14 22:50:24 +00007533 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00007534 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00007535 return;
7536
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007537 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00007538 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007539
Richard Trieu0f097742014-04-04 04:13:47 +00007540 // Used for diagnostic printout.
7541 enum {
7542 LiteralConstant = 0,
7543 CXXBoolLiteralTrue,
7544 CXXBoolLiteralFalse
7545 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007546
Richard Trieu0f097742014-04-04 04:13:47 +00007547 if (!OtherIsBooleanType) {
7548 QualType ConstantT = Constant->getType();
7549 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00007550
Richard Trieu0f097742014-04-04 04:13:47 +00007551 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
7552 return;
7553 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
7554 "comparison with non-integer type");
7555
7556 bool ConstantSigned = ConstantT->isSignedIntegerType();
7557 bool CommonSigned = CommonT->isSignedIntegerType();
7558
7559 bool EqualityOnly = false;
7560
7561 if (CommonSigned) {
7562 // The common type is signed, therefore no signed to unsigned conversion.
7563 if (!OtherRange.NonNegative) {
7564 // Check that the constant is representable in type OtherT.
7565 if (ConstantSigned) {
7566 if (OtherWidth >= Value.getMinSignedBits())
7567 return;
7568 } else { // !ConstantSigned
7569 if (OtherWidth >= Value.getActiveBits() + 1)
7570 return;
7571 }
7572 } else { // !OtherSigned
7573 // Check that the constant is representable in type OtherT.
7574 // Negative values are out of range.
7575 if (ConstantSigned) {
7576 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
7577 return;
7578 } else { // !ConstantSigned
7579 if (OtherWidth >= Value.getActiveBits())
7580 return;
7581 }
Richard Trieu560910c2012-11-14 22:50:24 +00007582 }
Richard Trieu0f097742014-04-04 04:13:47 +00007583 } else { // !CommonSigned
7584 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00007585 if (OtherWidth >= Value.getActiveBits())
7586 return;
Craig Toppercf360162014-06-18 05:13:11 +00007587 } else { // OtherSigned
7588 assert(!ConstantSigned &&
7589 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00007590 // Check to see if the constant is representable in OtherT.
7591 if (OtherWidth > Value.getActiveBits())
7592 return;
7593 // Check to see if the constant is equivalent to a negative value
7594 // cast to CommonT.
7595 if (S.Context.getIntWidth(ConstantT) ==
7596 S.Context.getIntWidth(CommonT) &&
7597 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
7598 return;
7599 // The constant value rests between values that OtherT can represent
7600 // after conversion. Relational comparison still works, but equality
7601 // comparisons will be tautological.
7602 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007603 }
7604 }
Richard Trieu0f097742014-04-04 04:13:47 +00007605
7606 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
7607
7608 if (op == BO_EQ || op == BO_NE) {
7609 IsTrue = op == BO_NE;
7610 } else if (EqualityOnly) {
7611 return;
7612 } else if (RhsConstant) {
7613 if (op == BO_GT || op == BO_GE)
7614 IsTrue = !PositiveConstant;
7615 else // op == BO_LT || op == BO_LE
7616 IsTrue = PositiveConstant;
7617 } else {
7618 if (op == BO_LT || op == BO_LE)
7619 IsTrue = !PositiveConstant;
7620 else // op == BO_GT || op == BO_GE
7621 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007622 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007623 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00007624 // Other isKnownToHaveBooleanValue
7625 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
7626 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
7627 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
7628
7629 static const struct LinkedConditions {
7630 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
7631 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
7632 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
7633 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
7634 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
7635 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
7636
7637 } TruthTable = {
7638 // Constant on LHS. | Constant on RHS. |
7639 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
7640 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
7641 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
7642 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
7643 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
7644 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
7645 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
7646 };
7647
7648 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
7649
7650 enum ConstantValue ConstVal = Zero;
7651 if (Value.isUnsigned() || Value.isNonNegative()) {
7652 if (Value == 0) {
7653 LiteralOrBoolConstant =
7654 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
7655 ConstVal = Zero;
7656 } else if (Value == 1) {
7657 LiteralOrBoolConstant =
7658 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
7659 ConstVal = One;
7660 } else {
7661 LiteralOrBoolConstant = LiteralConstant;
7662 ConstVal = GT_One;
7663 }
7664 } else {
7665 ConstVal = LT_Zero;
7666 }
7667
7668 CompareBoolWithConstantResult CmpRes;
7669
7670 switch (op) {
7671 case BO_LT:
7672 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
7673 break;
7674 case BO_GT:
7675 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
7676 break;
7677 case BO_LE:
7678 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
7679 break;
7680 case BO_GE:
7681 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
7682 break;
7683 case BO_EQ:
7684 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
7685 break;
7686 case BO_NE:
7687 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
7688 break;
7689 default:
7690 CmpRes = Unkwn;
7691 break;
7692 }
7693
7694 if (CmpRes == AFals) {
7695 IsTrue = false;
7696 } else if (CmpRes == ATrue) {
7697 IsTrue = true;
7698 } else {
7699 return;
7700 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007701 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007702
7703 // If this is a comparison to an enum constant, include that
7704 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00007705 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007706 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
7707 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
7708
7709 SmallString<64> PrettySourceValue;
7710 llvm::raw_svector_ostream OS(PrettySourceValue);
7711 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00007712 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007713 else
7714 OS << Value;
7715
Richard Trieu0f097742014-04-04 04:13:47 +00007716 S.DiagRuntimeBehavior(
7717 E->getOperatorLoc(), E,
7718 S.PDiag(diag::warn_out_of_range_compare)
7719 << OS.str() << LiteralOrBoolConstant
7720 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
7721 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007722}
7723
John McCallcc7e5bf2010-05-06 08:58:33 +00007724/// Analyze the operands of the given comparison. Implements the
7725/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007726void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00007727 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7728 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007729}
John McCall263a48b2010-01-04 23:31:57 +00007730
John McCallca01b222010-01-04 23:21:16 +00007731/// \brief Implements -Wsign-compare.
7732///
Richard Trieu82402a02011-09-15 21:56:47 +00007733/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007734void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007735 // The type the comparison is being performed in.
7736 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00007737
7738 // Only analyze comparison operators where both sides have been converted to
7739 // the same type.
7740 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
7741 return AnalyzeImpConvsInComparison(S, E);
7742
7743 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00007744 if (E->isValueDependent())
7745 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007746
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007747 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
7748 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007749
7750 bool IsComparisonConstant = false;
7751
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007752 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007753 // of 'true' or 'false'.
7754 if (T->isIntegralType(S.Context)) {
7755 llvm::APSInt RHSValue;
7756 bool IsRHSIntegralLiteral =
7757 RHS->isIntegerConstantExpr(RHSValue, S.Context);
7758 llvm::APSInt LHSValue;
7759 bool IsLHSIntegralLiteral =
7760 LHS->isIntegerConstantExpr(LHSValue, S.Context);
7761 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
7762 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
7763 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
7764 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
7765 else
7766 IsComparisonConstant =
7767 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007768 } else if (!T->hasUnsignedIntegerRepresentation())
7769 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007770
John McCallcc7e5bf2010-05-06 08:58:33 +00007771 // We don't do anything special if this isn't an unsigned integral
7772 // comparison: we're only interested in integral comparisons, and
7773 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00007774 //
7775 // We also don't care about value-dependent expressions or expressions
7776 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007777 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00007778 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007779
John McCallcc7e5bf2010-05-06 08:58:33 +00007780 // Check to see if one of the (unmodified) operands is of different
7781 // signedness.
7782 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00007783 if (LHS->getType()->hasSignedIntegerRepresentation()) {
7784 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00007785 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00007786 signedOperand = LHS;
7787 unsignedOperand = RHS;
7788 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
7789 signedOperand = RHS;
7790 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00007791 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00007792 CheckTrivialUnsignedComparison(S, E);
7793 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007794 }
7795
John McCallcc7e5bf2010-05-06 08:58:33 +00007796 // Otherwise, calculate the effective range of the signed operand.
7797 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00007798
John McCallcc7e5bf2010-05-06 08:58:33 +00007799 // Go ahead and analyze implicit conversions in the operands. Note
7800 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00007801 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
7802 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00007803
John McCallcc7e5bf2010-05-06 08:58:33 +00007804 // If the signed range is non-negative, -Wsign-compare won't fire,
7805 // but we should still check for comparisons which are always true
7806 // or false.
7807 if (signedRange.NonNegative)
7808 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007809
7810 // For (in)equality comparisons, if the unsigned operand is a
7811 // constant which cannot collide with a overflowed signed operand,
7812 // then reinterpreting the signed operand as unsigned will not
7813 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00007814 if (E->isEqualityOp()) {
7815 unsigned comparisonWidth = S.Context.getIntWidth(T);
7816 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00007817
John McCallcc7e5bf2010-05-06 08:58:33 +00007818 // We should never be unable to prove that the unsigned operand is
7819 // non-negative.
7820 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
7821
7822 if (unsignedRange.Width < comparisonWidth)
7823 return;
7824 }
7825
Douglas Gregorbfb4a212012-05-01 01:53:49 +00007826 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
7827 S.PDiag(diag::warn_mixed_sign_comparison)
7828 << LHS->getType() << RHS->getType()
7829 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00007830}
7831
John McCall1f425642010-11-11 03:21:53 +00007832/// Analyzes an attempt to assign the given value to a bitfield.
7833///
7834/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007835bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
7836 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00007837 assert(Bitfield->isBitField());
7838 if (Bitfield->isInvalidDecl())
7839 return false;
7840
John McCalldeebbcf2010-11-11 05:33:51 +00007841 // White-list bool bitfields.
7842 if (Bitfield->getType()->isBooleanType())
7843 return false;
7844
Douglas Gregor789adec2011-02-04 13:09:01 +00007845 // Ignore value- or type-dependent expressions.
7846 if (Bitfield->getBitWidth()->isValueDependent() ||
7847 Bitfield->getBitWidth()->isTypeDependent() ||
7848 Init->isValueDependent() ||
7849 Init->isTypeDependent())
7850 return false;
7851
John McCall1f425642010-11-11 03:21:53 +00007852 Expr *OriginalInit = Init->IgnoreParenImpCasts();
7853
Richard Smith5fab0c92011-12-28 19:48:30 +00007854 llvm::APSInt Value;
7855 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00007856 return false;
7857
John McCall1f425642010-11-11 03:21:53 +00007858 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00007859 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00007860
Richard Trieu7561ed02016-08-05 02:39:30 +00007861 if (Value.isSigned() && Value.isNegative())
7862 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
7863 if (UO->getOpcode() == UO_Minus)
7864 if (isa<IntegerLiteral>(UO->getSubExpr()))
7865 OriginalWidth = Value.getMinSignedBits();
7866
John McCall1f425642010-11-11 03:21:53 +00007867 if (OriginalWidth <= FieldWidth)
7868 return false;
7869
Eli Friedmanc267a322012-01-26 23:11:39 +00007870 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007871 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00007872 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00007873
Eli Friedmanc267a322012-01-26 23:11:39 +00007874 // Check whether the stored value is equal to the original value.
7875 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00007876 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00007877 return false;
7878
Eli Friedmanc267a322012-01-26 23:11:39 +00007879 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00007880 // therefore don't strictly fit into a signed bitfield of width 1.
7881 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00007882 return false;
7883
John McCall1f425642010-11-11 03:21:53 +00007884 std::string PrettyValue = Value.toString(10);
7885 std::string PrettyTrunc = TruncatedValue.toString(10);
7886
7887 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
7888 << PrettyValue << PrettyTrunc << OriginalInit->getType()
7889 << Init->getSourceRange();
7890
7891 return true;
7892}
7893
John McCalld2a53122010-11-09 23:24:47 +00007894/// Analyze the given simple or compound assignment for warning-worthy
7895/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007896void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00007897 // Just recurse on the LHS.
7898 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7899
7900 // We want to recurse on the RHS as normal unless we're assigning to
7901 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00007902 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007903 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00007904 E->getOperatorLoc())) {
7905 // Recurse, ignoring any implicit conversions on the RHS.
7906 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
7907 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00007908 }
7909 }
7910
7911 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
7912}
7913
John McCall263a48b2010-01-04 23:31:57 +00007914/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007915void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
7916 SourceLocation CContext, unsigned diag,
7917 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007918 if (pruneControlFlow) {
7919 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7920 S.PDiag(diag)
7921 << SourceType << T << E->getSourceRange()
7922 << SourceRange(CContext));
7923 return;
7924 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00007925 S.Diag(E->getExprLoc(), diag)
7926 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
7927}
7928
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007929/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007930void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
7931 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007932 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007933}
7934
Richard Trieube234c32016-04-21 21:04:55 +00007935
7936/// Diagnose an implicit cast from a floating point value to an integer value.
7937void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
7938
7939 SourceLocation CContext) {
7940 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
7941 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
7942
7943 Expr *InnerE = E->IgnoreParenImpCasts();
7944 // We also want to warn on, e.g., "int i = -1.234"
7945 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7946 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7947 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7948
7949 const bool IsLiteral =
7950 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
7951
7952 llvm::APFloat Value(0.0);
7953 bool IsConstant =
7954 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
7955 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00007956 return DiagnoseImpCast(S, E, T, CContext,
7957 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00007958 }
7959
Chandler Carruth016ef402011-04-10 08:36:24 +00007960 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00007961
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00007962 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
7963 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00007964 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
7965 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00007966 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00007967 if (IsLiteral) return;
7968 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
7969 PruneWarnings);
7970 }
7971
7972 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00007973 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00007974 // Warn on floating point literal to integer.
7975 DiagID = diag::warn_impcast_literal_float_to_integer;
7976 } else if (IntegerValue == 0) {
7977 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
7978 return DiagnoseImpCast(S, E, T, CContext,
7979 diag::warn_impcast_float_integer, PruneWarnings);
7980 }
7981 // Warn on non-zero to zero conversion.
7982 DiagID = diag::warn_impcast_float_to_integer_zero;
7983 } else {
7984 if (IntegerValue.isUnsigned()) {
7985 if (!IntegerValue.isMaxValue()) {
7986 return DiagnoseImpCast(S, E, T, CContext,
7987 diag::warn_impcast_float_integer, PruneWarnings);
7988 }
7989 } else { // IntegerValue.isSigned()
7990 if (!IntegerValue.isMaxSignedValue() &&
7991 !IntegerValue.isMinSignedValue()) {
7992 return DiagnoseImpCast(S, E, T, CContext,
7993 diag::warn_impcast_float_integer, PruneWarnings);
7994 }
7995 }
7996 // Warn on evaluatable floating point expression to integer conversion.
7997 DiagID = diag::warn_impcast_float_to_integer;
7998 }
Chandler Carruth016ef402011-04-10 08:36:24 +00007999
Eli Friedman07185912013-08-29 23:44:43 +00008000 // FIXME: Force the precision of the source value down so we don't print
8001 // digits which are usually useless (we don't really care here if we
8002 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
8003 // would automatically print the shortest representation, but it's a bit
8004 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00008005 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00008006 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
8007 precision = (precision * 59 + 195) / 196;
8008 Value.toString(PrettySourceValue, precision);
8009
David Blaikie9b88cc02012-05-15 17:18:27 +00008010 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00008011 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00008012 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00008013 else
David Blaikie9b88cc02012-05-15 17:18:27 +00008014 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00008015
Richard Trieube234c32016-04-21 21:04:55 +00008016 if (PruneWarnings) {
8017 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8018 S.PDiag(DiagID)
8019 << E->getType() << T.getUnqualifiedType()
8020 << PrettySourceValue << PrettyTargetValue
8021 << E->getSourceRange() << SourceRange(CContext));
8022 } else {
8023 S.Diag(E->getExprLoc(), DiagID)
8024 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8025 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8026 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008027}
8028
John McCall18a2c2c2010-11-09 22:22:12 +00008029std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8030 if (!Range.Width) return "0";
8031
8032 llvm::APSInt ValueInRange = Value;
8033 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00008034 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00008035 return ValueInRange.toString(10);
8036}
8037
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008038bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008039 if (!isa<ImplicitCastExpr>(Ex))
8040 return false;
8041
8042 Expr *InnerE = Ex->IgnoreParenImpCasts();
8043 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8044 const Type *Source =
8045 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8046 if (Target->isDependentType())
8047 return false;
8048
8049 const BuiltinType *FloatCandidateBT =
8050 dyn_cast<BuiltinType>(ToBool ? Source : Target);
8051 const Type *BoolCandidateType = ToBool ? Target : Source;
8052
8053 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8054 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8055}
8056
8057void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8058 SourceLocation CC) {
8059 unsigned NumArgs = TheCall->getNumArgs();
8060 for (unsigned i = 0; i < NumArgs; ++i) {
8061 Expr *CurrA = TheCall->getArg(i);
8062 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8063 continue;
8064
8065 bool IsSwapped = ((i > 0) &&
8066 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8067 IsSwapped |= ((i < (NumArgs - 1)) &&
8068 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8069 if (IsSwapped) {
8070 // Warn on this floating-point to bool conversion.
8071 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8072 CurrA->getType(), CC,
8073 diag::warn_impcast_floating_point_to_bool);
8074 }
8075 }
8076}
8077
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008078void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00008079 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
8080 E->getExprLoc()))
8081 return;
8082
Richard Trieu09d6b802016-01-08 23:35:06 +00008083 // Don't warn on functions which have return type nullptr_t.
8084 if (isa<CallExpr>(E))
8085 return;
8086
Richard Trieu5b993502014-10-15 03:42:06 +00008087 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
8088 const Expr::NullPointerConstantKind NullKind =
8089 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
8090 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
8091 return;
8092
8093 // Return if target type is a safe conversion.
8094 if (T->isAnyPointerType() || T->isBlockPointerType() ||
8095 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8096 return;
8097
8098 SourceLocation Loc = E->getSourceRange().getBegin();
8099
Richard Trieu0a5e1662016-02-13 00:58:53 +00008100 // Venture through the macro stacks to get to the source of macro arguments.
8101 // The new location is a better location than the complete location that was
8102 // passed in.
8103 while (S.SourceMgr.isMacroArgExpansion(Loc))
8104 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8105
8106 while (S.SourceMgr.isMacroArgExpansion(CC))
8107 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8108
Richard Trieu5b993502014-10-15 03:42:06 +00008109 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00008110 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8111 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8112 Loc, S.SourceMgr, S.getLangOpts());
8113 if (MacroName == "NULL")
8114 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00008115 }
8116
8117 // Only warn if the null and context location are in the same macro expansion.
8118 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8119 return;
8120
8121 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8122 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8123 << FixItHint::CreateReplacement(Loc,
8124 S.getFixItZeroLiteralForType(T, Loc));
8125}
8126
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008127void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8128 ObjCArrayLiteral *ArrayLiteral);
8129void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8130 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00008131
8132/// Check a single element within a collection literal against the
8133/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008134void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8135 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008136 // Skip a bitcast to 'id' or qualified 'id'.
8137 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8138 if (ICE->getCastKind() == CK_BitCast &&
8139 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8140 Element = ICE->getSubExpr();
8141 }
8142
8143 QualType ElementType = Element->getType();
8144 ExprResult ElementResult(Element);
8145 if (ElementType->getAs<ObjCObjectPointerType>() &&
8146 S.CheckSingleAssignmentConstraints(TargetElementType,
8147 ElementResult,
8148 false, false)
8149 != Sema::Compatible) {
8150 S.Diag(Element->getLocStart(),
8151 diag::warn_objc_collection_literal_element)
8152 << ElementType << ElementKind << TargetElementType
8153 << Element->getSourceRange();
8154 }
8155
8156 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8157 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8158 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8159 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8160}
8161
8162/// Check an Objective-C array literal being converted to the given
8163/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008164void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8165 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008166 if (!S.NSArrayDecl)
8167 return;
8168
8169 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8170 if (!TargetObjCPtr)
8171 return;
8172
8173 if (TargetObjCPtr->isUnspecialized() ||
8174 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8175 != S.NSArrayDecl->getCanonicalDecl())
8176 return;
8177
8178 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8179 if (TypeArgs.size() != 1)
8180 return;
8181
8182 QualType TargetElementType = TypeArgs[0];
8183 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8184 checkObjCCollectionLiteralElement(S, TargetElementType,
8185 ArrayLiteral->getElement(I),
8186 0);
8187 }
8188}
8189
8190/// Check an Objective-C dictionary literal being converted to the given
8191/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008192void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8193 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008194 if (!S.NSDictionaryDecl)
8195 return;
8196
8197 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8198 if (!TargetObjCPtr)
8199 return;
8200
8201 if (TargetObjCPtr->isUnspecialized() ||
8202 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8203 != S.NSDictionaryDecl->getCanonicalDecl())
8204 return;
8205
8206 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8207 if (TypeArgs.size() != 2)
8208 return;
8209
8210 QualType TargetKeyType = TypeArgs[0];
8211 QualType TargetObjectType = TypeArgs[1];
8212 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8213 auto Element = DictionaryLiteral->getKeyValueElement(I);
8214 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8215 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8216 }
8217}
8218
Richard Trieufc404c72016-02-05 23:02:38 +00008219// Helper function to filter out cases for constant width constant conversion.
8220// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008221bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8222 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00008223 // If initializing from a constant, and the constant starts with '0',
8224 // then it is a binary, octal, or hexadecimal. Allow these constants
8225 // to fill all the bits, even if there is a sign change.
8226 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8227 const char FirstLiteralCharacter =
8228 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8229 if (FirstLiteralCharacter == '0')
8230 return false;
8231 }
8232
8233 // If the CC location points to a '{', and the type is char, then assume
8234 // assume it is an array initialization.
8235 if (CC.isValid() && T->isCharType()) {
8236 const char FirstContextCharacter =
8237 S.getSourceManager().getCharacterData(CC)[0];
8238 if (FirstContextCharacter == '{')
8239 return false;
8240 }
8241
8242 return true;
8243}
8244
John McCallcc7e5bf2010-05-06 08:58:33 +00008245void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00008246 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008247 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00008248
John McCallcc7e5bf2010-05-06 08:58:33 +00008249 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
8250 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
8251 if (Source == Target) return;
8252 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00008253
Chandler Carruthc22845a2011-07-26 05:40:03 +00008254 // If the conversion context location is invalid don't complain. We also
8255 // don't want to emit a warning if the issue occurs from the expansion of
8256 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
8257 // delay this check as long as possible. Once we detect we are in that
8258 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008259 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00008260 return;
8261
Richard Trieu021baa32011-09-23 20:10:00 +00008262 // Diagnose implicit casts to bool.
8263 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
8264 if (isa<StringLiteral>(E))
8265 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00008266 // and expressions, for instance, assert(0 && "error here"), are
8267 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00008268 return DiagnoseImpCast(S, E, T, CC,
8269 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00008270 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
8271 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
8272 // This covers the literal expressions that evaluate to Objective-C
8273 // objects.
8274 return DiagnoseImpCast(S, E, T, CC,
8275 diag::warn_impcast_objective_c_literal_to_bool);
8276 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008277 if (Source->isPointerType() || Source->canDecayToPointerType()) {
8278 // Warn on pointer to bool conversion that is always true.
8279 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
8280 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00008281 }
Richard Trieu021baa32011-09-23 20:10:00 +00008282 }
John McCall263a48b2010-01-04 23:31:57 +00008283
Douglas Gregor5054cb02015-07-07 03:58:22 +00008284 // Check implicit casts from Objective-C collection literals to specialized
8285 // collection types, e.g., NSArray<NSString *> *.
8286 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
8287 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
8288 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
8289 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
8290
John McCall263a48b2010-01-04 23:31:57 +00008291 // Strip vector types.
8292 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008293 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008294 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008295 return;
John McCallacf0ee52010-10-08 02:01:28 +00008296 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008297 }
Chris Lattneree7286f2011-06-14 04:51:15 +00008298
8299 // If the vector cast is cast between two vectors of the same size, it is
8300 // a bitcast, not a conversion.
8301 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
8302 return;
John McCall263a48b2010-01-04 23:31:57 +00008303
8304 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
8305 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
8306 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00008307 if (auto VecTy = dyn_cast<VectorType>(Target))
8308 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00008309
8310 // Strip complex types.
8311 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008312 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008313 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008314 return;
8315
John McCallacf0ee52010-10-08 02:01:28 +00008316 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008317 }
John McCall263a48b2010-01-04 23:31:57 +00008318
8319 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
8320 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
8321 }
8322
8323 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
8324 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
8325
8326 // If the source is floating point...
8327 if (SourceBT && SourceBT->isFloatingPoint()) {
8328 // ...and the target is floating point...
8329 if (TargetBT && TargetBT->isFloatingPoint()) {
8330 // ...then warn if we're dropping FP rank.
8331
8332 // Builtin FP kinds are ordered by increasing FP rank.
8333 if (SourceBT->getKind() > TargetBT->getKind()) {
8334 // Don't warn about float constants that are precisely
8335 // representable in the target type.
8336 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008337 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00008338 // Value might be a float, a float vector, or a float complex.
8339 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00008340 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
8341 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00008342 return;
8343 }
8344
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008345 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008346 return;
8347
John McCallacf0ee52010-10-08 02:01:28 +00008348 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00008349 }
8350 // ... or possibly if we're increasing rank, too
8351 else if (TargetBT->getKind() > SourceBT->getKind()) {
8352 if (S.SourceMgr.isInSystemMacro(CC))
8353 return;
8354
8355 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00008356 }
8357 return;
8358 }
8359
Richard Trieube234c32016-04-21 21:04:55 +00008360 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00008361 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008362 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008363 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00008364
Richard Trieube234c32016-04-21 21:04:55 +00008365 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00008366 }
John McCall263a48b2010-01-04 23:31:57 +00008367
Richard Smith54894fd2015-12-30 01:06:52 +00008368 // Detect the case where a call result is converted from floating-point to
8369 // to bool, and the final argument to the call is converted from bool, to
8370 // discover this typo:
8371 //
8372 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
8373 //
8374 // FIXME: This is an incredibly special case; is there some more general
8375 // way to detect this class of misplaced-parentheses bug?
8376 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008377 // Check last argument of function call to see if it is an
8378 // implicit cast from a type matching the type the result
8379 // is being cast to.
8380 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00008381 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008382 Expr *LastA = CEx->getArg(NumArgs - 1);
8383 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00008384 if (isa<ImplicitCastExpr>(LastA) &&
8385 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008386 // Warn on this floating-point to bool conversion
8387 DiagnoseImpCast(S, E, T, CC,
8388 diag::warn_impcast_floating_point_to_bool);
8389 }
8390 }
8391 }
John McCall263a48b2010-01-04 23:31:57 +00008392 return;
8393 }
8394
Richard Trieu5b993502014-10-15 03:42:06 +00008395 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00008396
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00008397 S.DiscardMisalignedMemberAddress(Target, E);
8398
David Blaikie9366d2b2012-06-19 21:19:06 +00008399 if (!Source->isIntegerType() || !Target->isIntegerType())
8400 return;
8401
David Blaikie7555b6a2012-05-15 16:56:36 +00008402 // TODO: remove this early return once the false positives for constant->bool
8403 // in templates, macros, etc, are reduced or removed.
8404 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
8405 return;
8406
John McCallcc7e5bf2010-05-06 08:58:33 +00008407 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00008408 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00008409
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008410 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00008411 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008412 // TODO: this should happen for bitfield stores, too.
8413 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00008414 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008415 if (S.SourceMgr.isInSystemMacro(CC))
8416 return;
8417
John McCall18a2c2c2010-11-09 22:22:12 +00008418 std::string PrettySourceValue = Value.toString(10);
8419 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008420
Ted Kremenek33ba9952011-10-22 02:37:33 +00008421 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8422 S.PDiag(diag::warn_impcast_integer_precision_constant)
8423 << PrettySourceValue << PrettyTargetValue
8424 << E->getType() << T << E->getSourceRange()
8425 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00008426 return;
8427 }
8428
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008429 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
8430 if (S.SourceMgr.isInSystemMacro(CC))
8431 return;
8432
David Blaikie9455da02012-04-12 22:40:54 +00008433 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00008434 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
8435 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00008436 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00008437 }
8438
Richard Trieudcb55572016-01-29 23:51:16 +00008439 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
8440 SourceRange.NonNegative && Source->isSignedIntegerType()) {
8441 // Warn when doing a signed to signed conversion, warn if the positive
8442 // source value is exactly the width of the target type, which will
8443 // cause a negative value to be stored.
8444
8445 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00008446 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
8447 !S.SourceMgr.isInSystemMacro(CC)) {
8448 if (isSameWidthConstantConversion(S, E, T, CC)) {
8449 std::string PrettySourceValue = Value.toString(10);
8450 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00008451
Richard Trieufc404c72016-02-05 23:02:38 +00008452 S.DiagRuntimeBehavior(
8453 E->getExprLoc(), E,
8454 S.PDiag(diag::warn_impcast_integer_precision_constant)
8455 << PrettySourceValue << PrettyTargetValue << E->getType() << T
8456 << E->getSourceRange() << clang::SourceRange(CC));
8457 return;
Richard Trieudcb55572016-01-29 23:51:16 +00008458 }
8459 }
Richard Trieufc404c72016-02-05 23:02:38 +00008460
Richard Trieudcb55572016-01-29 23:51:16 +00008461 // Fall through for non-constants to give a sign conversion warning.
8462 }
8463
John McCallcc7e5bf2010-05-06 08:58:33 +00008464 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
8465 (!TargetRange.NonNegative && SourceRange.NonNegative &&
8466 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008467 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008468 return;
8469
John McCallcc7e5bf2010-05-06 08:58:33 +00008470 unsigned DiagID = diag::warn_impcast_integer_sign;
8471
8472 // Traditionally, gcc has warned about this under -Wsign-compare.
8473 // We also want to warn about it in -Wconversion.
8474 // So if -Wconversion is off, use a completely identical diagnostic
8475 // in the sign-compare group.
8476 // The conditional-checking code will
8477 if (ICContext) {
8478 DiagID = diag::warn_impcast_integer_sign_conditional;
8479 *ICContext = true;
8480 }
8481
John McCallacf0ee52010-10-08 02:01:28 +00008482 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00008483 }
8484
Douglas Gregora78f1932011-02-22 02:45:07 +00008485 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00008486 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
8487 // type, to give us better diagnostics.
8488 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00008489 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00008490 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8491 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
8492 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
8493 SourceType = S.Context.getTypeDeclType(Enum);
8494 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
8495 }
8496 }
8497
Douglas Gregora78f1932011-02-22 02:45:07 +00008498 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
8499 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00008500 if (SourceEnum->getDecl()->hasNameForLinkage() &&
8501 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008502 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008503 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008504 return;
8505
Douglas Gregor364f7db2011-03-12 00:14:31 +00008506 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00008507 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008508 }
John McCall263a48b2010-01-04 23:31:57 +00008509}
8510
David Blaikie18e9ac72012-05-15 21:57:38 +00008511void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8512 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008513
8514void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00008515 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008516 E = E->IgnoreParenImpCasts();
8517
8518 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00008519 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008520
John McCallacf0ee52010-10-08 02:01:28 +00008521 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008522 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00008523 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00008524}
8525
David Blaikie18e9ac72012-05-15 21:57:38 +00008526void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8527 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00008528 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008529
8530 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00008531 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
8532 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00008533
8534 // If -Wconversion would have warned about either of the candidates
8535 // for a signedness conversion to the context type...
8536 if (!Suspicious) return;
8537
8538 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008539 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00008540 return;
8541
John McCallcc7e5bf2010-05-06 08:58:33 +00008542 // ...then check whether it would have warned about either of the
8543 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00008544 if (E->getType() == T) return;
8545
8546 Suspicious = false;
8547 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
8548 E->getType(), CC, &Suspicious);
8549 if (!Suspicious)
8550 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00008551 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00008552}
8553
Richard Trieu65724892014-11-15 06:37:39 +00008554/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8555/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008556void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00008557 if (S.getLangOpts().Bool)
8558 return;
8559 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
8560}
8561
John McCallcc7e5bf2010-05-06 08:58:33 +00008562/// AnalyzeImplicitConversions - Find and report any interesting
8563/// implicit conversions in the given expression. There are a couple
8564/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008565void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00008566 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00008567 Expr *E = OrigE->IgnoreParenImpCasts();
8568
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00008569 if (E->isTypeDependent() || E->isValueDependent())
8570 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00008571
John McCallcc7e5bf2010-05-06 08:58:33 +00008572 // For conditional operators, we analyze the arguments as if they
8573 // were being fed directly into the output.
8574 if (isa<ConditionalOperator>(E)) {
8575 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00008576 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008577 return;
8578 }
8579
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008580 // Check implicit argument conversions for function calls.
8581 if (CallExpr *Call = dyn_cast<CallExpr>(E))
8582 CheckImplicitArgumentConversions(S, Call, CC);
8583
John McCallcc7e5bf2010-05-06 08:58:33 +00008584 // Go ahead and check any implicit conversions we might have skipped.
8585 // The non-canonical typecheck is just an optimization;
8586 // CheckImplicitConversion will filter out dead implicit conversions.
8587 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00008588 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008589
8590 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00008591
8592 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
8593 // The bound subexpressions in a PseudoObjectExpr are not reachable
8594 // as transitive children.
8595 // FIXME: Use a more uniform representation for this.
8596 for (auto *SE : POE->semantics())
8597 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
8598 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00008599 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00008600
John McCallcc7e5bf2010-05-06 08:58:33 +00008601 // Skip past explicit casts.
8602 if (isa<ExplicitCastExpr>(E)) {
8603 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00008604 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008605 }
8606
John McCalld2a53122010-11-09 23:24:47 +00008607 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8608 // Do a somewhat different check with comparison operators.
8609 if (BO->isComparisonOp())
8610 return AnalyzeComparison(S, BO);
8611
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008612 // And with simple assignments.
8613 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00008614 return AnalyzeAssignment(S, BO);
8615 }
John McCallcc7e5bf2010-05-06 08:58:33 +00008616
8617 // These break the otherwise-useful invariant below. Fortunately,
8618 // we don't really need to recurse into them, because any internal
8619 // expressions should have been analyzed already when they were
8620 // built into statements.
8621 if (isa<StmtExpr>(E)) return;
8622
8623 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00008624 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00008625
8626 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00008627 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00008628 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00008629 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00008630 for (Stmt *SubStmt : E->children()) {
8631 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00008632 if (!ChildExpr)
8633 continue;
8634
Richard Trieu955231d2014-01-25 01:10:35 +00008635 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00008636 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00008637 // Ignore checking string literals that are in logical and operators.
8638 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00008639 continue;
8640 AnalyzeImplicitConversions(S, ChildExpr, CC);
8641 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008642
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008643 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00008644 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
8645 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008646 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00008647
8648 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
8649 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008650 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008651 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008652
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008653 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
8654 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00008655 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008656}
8657
8658} // end anonymous namespace
8659
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00008660static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
8661 unsigned Start, unsigned End) {
8662 bool IllegalParams = false;
8663 for (unsigned I = Start; I <= End; ++I) {
8664 QualType Ty = TheCall->getArg(I)->getType();
8665 // Taking into account implicit conversions,
8666 // allow any integer within 32 bits range
8667 if (!Ty->isIntegerType() ||
8668 S.Context.getTypeSizeInChars(Ty).getQuantity() > 4) {
8669 S.Diag(TheCall->getArg(I)->getLocStart(),
8670 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
8671 IllegalParams = true;
8672 }
8673 // Potentially emit standard warnings for implicit conversions if enabled
8674 // using -Wconversion.
8675 CheckImplicitConversion(S, TheCall->getArg(I), S.Context.UnsignedIntTy,
8676 TheCall->getArg(I)->getLocStart());
8677 }
8678 return IllegalParams;
8679}
8680
Richard Trieuc1888e02014-06-28 23:25:37 +00008681// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
8682// Returns true when emitting a warning about taking the address of a reference.
8683static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00008684 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00008685 E = E->IgnoreParenImpCasts();
8686
8687 const FunctionDecl *FD = nullptr;
8688
8689 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8690 if (!DRE->getDecl()->getType()->isReferenceType())
8691 return false;
8692 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8693 if (!M->getMemberDecl()->getType()->isReferenceType())
8694 return false;
8695 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00008696 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00008697 return false;
8698 FD = Call->getDirectCallee();
8699 } else {
8700 return false;
8701 }
8702
8703 SemaRef.Diag(E->getExprLoc(), PD);
8704
8705 // If possible, point to location of function.
8706 if (FD) {
8707 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
8708 }
8709
8710 return true;
8711}
8712
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008713// Returns true if the SourceLocation is expanded from any macro body.
8714// Returns false if the SourceLocation is invalid, is from not in a macro
8715// expansion, or is from expanded from a top-level macro argument.
8716static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
8717 if (Loc.isInvalid())
8718 return false;
8719
8720 while (Loc.isMacroID()) {
8721 if (SM.isMacroBodyExpansion(Loc))
8722 return true;
8723 Loc = SM.getImmediateMacroCallerLoc(Loc);
8724 }
8725
8726 return false;
8727}
8728
Richard Trieu3bb8b562014-02-26 02:36:06 +00008729/// \brief Diagnose pointers that are always non-null.
8730/// \param E the expression containing the pointer
8731/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
8732/// compared to a null pointer
8733/// \param IsEqual True when the comparison is equal to a null pointer
8734/// \param Range Extra SourceRange to highlight in the diagnostic
8735void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
8736 Expr::NullPointerConstantKind NullKind,
8737 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00008738 if (!E)
8739 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008740
8741 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008742 if (E->getExprLoc().isMacroID()) {
8743 const SourceManager &SM = getSourceManager();
8744 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
8745 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00008746 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008747 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008748 E = E->IgnoreImpCasts();
8749
8750 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
8751
Richard Trieuf7432752014-06-06 21:39:26 +00008752 if (isa<CXXThisExpr>(E)) {
8753 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
8754 : diag::warn_this_bool_conversion;
8755 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
8756 return;
8757 }
8758
Richard Trieu3bb8b562014-02-26 02:36:06 +00008759 bool IsAddressOf = false;
8760
8761 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8762 if (UO->getOpcode() != UO_AddrOf)
8763 return;
8764 IsAddressOf = true;
8765 E = UO->getSubExpr();
8766 }
8767
Richard Trieuc1888e02014-06-28 23:25:37 +00008768 if (IsAddressOf) {
8769 unsigned DiagID = IsCompare
8770 ? diag::warn_address_of_reference_null_compare
8771 : diag::warn_address_of_reference_bool_conversion;
8772 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
8773 << IsEqual;
8774 if (CheckForReference(*this, E, PD)) {
8775 return;
8776 }
8777 }
8778
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008779 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
8780 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00008781 std::string Str;
8782 llvm::raw_string_ostream S(Str);
8783 E->printPretty(S, nullptr, getPrintingPolicy());
8784 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
8785 : diag::warn_cast_nonnull_to_bool;
8786 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
8787 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008788 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00008789 };
8790
8791 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
8792 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
8793 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008794 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
8795 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00008796 return;
8797 }
8798 }
8799 }
8800
Richard Trieu3bb8b562014-02-26 02:36:06 +00008801 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00008802 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008803 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
8804 D = R->getDecl();
8805 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8806 D = M->getMemberDecl();
8807 }
8808
8809 // Weak Decls can be null.
8810 if (!D || D->isWeak())
8811 return;
George Burgess IV850269a2015-12-08 22:02:00 +00008812
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008813 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00008814 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
8815 if (getCurFunction() &&
8816 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008817 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
8818 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00008819 return;
8820 }
8821
8822 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +00008823 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +00008824 assert(ParamIter != FD->param_end());
8825 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
8826
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008827 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
8828 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008829 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +00008830 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008831 }
George Burgess IV850269a2015-12-08 22:02:00 +00008832
8833 for (unsigned ArgNo : NonNull->args()) {
8834 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008835 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008836 return;
8837 }
George Burgess IV850269a2015-12-08 22:02:00 +00008838 }
8839 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008840 }
8841 }
George Burgess IV850269a2015-12-08 22:02:00 +00008842 }
8843
Richard Trieu3bb8b562014-02-26 02:36:06 +00008844 QualType T = D->getType();
8845 const bool IsArray = T->isArrayType();
8846 const bool IsFunction = T->isFunctionType();
8847
Richard Trieuc1888e02014-06-28 23:25:37 +00008848 // Address of function is used to silence the function warning.
8849 if (IsAddressOf && IsFunction) {
8850 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008851 }
8852
8853 // Found nothing.
8854 if (!IsAddressOf && !IsFunction && !IsArray)
8855 return;
8856
8857 // Pretty print the expression for the diagnostic.
8858 std::string Str;
8859 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00008860 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00008861
8862 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
8863 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00008864 enum {
8865 AddressOf,
8866 FunctionPointer,
8867 ArrayPointer
8868 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008869 if (IsAddressOf)
8870 DiagType = AddressOf;
8871 else if (IsFunction)
8872 DiagType = FunctionPointer;
8873 else if (IsArray)
8874 DiagType = ArrayPointer;
8875 else
8876 llvm_unreachable("Could not determine diagnostic.");
8877 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
8878 << Range << IsEqual;
8879
8880 if (!IsFunction)
8881 return;
8882
8883 // Suggest '&' to silence the function warning.
8884 Diag(E->getExprLoc(), diag::note_function_warning_silence)
8885 << FixItHint::CreateInsertion(E->getLocStart(), "&");
8886
8887 // Check to see if '()' fixit should be emitted.
8888 QualType ReturnType;
8889 UnresolvedSet<4> NonTemplateOverloads;
8890 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
8891 if (ReturnType.isNull())
8892 return;
8893
8894 if (IsCompare) {
8895 // There are two cases here. If there is null constant, the only suggest
8896 // for a pointer return type. If the null is 0, then suggest if the return
8897 // type is a pointer or an integer type.
8898 if (!ReturnType->isPointerType()) {
8899 if (NullKind == Expr::NPCK_ZeroExpression ||
8900 NullKind == Expr::NPCK_ZeroLiteral) {
8901 if (!ReturnType->isIntegerType())
8902 return;
8903 } else {
8904 return;
8905 }
8906 }
8907 } else { // !IsCompare
8908 // For function to bool, only suggest if the function pointer has bool
8909 // return type.
8910 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
8911 return;
8912 }
8913 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00008914 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00008915}
8916
John McCallcc7e5bf2010-05-06 08:58:33 +00008917/// Diagnoses "dangerous" implicit conversions within the given
8918/// expression (which is a full expression). Implements -Wconversion
8919/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008920///
8921/// \param CC the "context" location of the implicit conversion, i.e.
8922/// the most location of the syntactic entity requiring the implicit
8923/// conversion
8924void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008925 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00008926 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00008927 return;
8928
8929 // Don't diagnose for value- or type-dependent expressions.
8930 if (E->isTypeDependent() || E->isValueDependent())
8931 return;
8932
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008933 // Check for array bounds violations in cases where the check isn't triggered
8934 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
8935 // ArraySubscriptExpr is on the RHS of a variable initialization.
8936 CheckArrayAccess(E);
8937
John McCallacf0ee52010-10-08 02:01:28 +00008938 // This is not the right CC for (e.g.) a variable initialization.
8939 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008940}
8941
Richard Trieu65724892014-11-15 06:37:39 +00008942/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8943/// Input argument E is a logical expression.
8944void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
8945 ::CheckBoolLikeConversion(*this, E, CC);
8946}
8947
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008948/// Diagnose when expression is an integer constant expression and its evaluation
8949/// results in integer overflow
8950void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00008951 // Use a work list to deal with nested struct initializers.
8952 SmallVector<Expr *, 2> Exprs(1, E);
8953
8954 do {
8955 Expr *E = Exprs.pop_back_val();
8956
8957 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
8958 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
8959 continue;
8960 }
8961
8962 if (auto InitList = dyn_cast<InitListExpr>(E))
8963 Exprs.append(InitList->inits().begin(), InitList->inits().end());
8964 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008965}
8966
Richard Smithc406cb72013-01-17 01:17:56 +00008967namespace {
8968/// \brief Visitor for expressions which looks for unsequenced operations on the
8969/// same object.
8970class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008971 typedef EvaluatedExprVisitor<SequenceChecker> Base;
8972
Richard Smithc406cb72013-01-17 01:17:56 +00008973 /// \brief A tree of sequenced regions within an expression. Two regions are
8974 /// unsequenced if one is an ancestor or a descendent of the other. When we
8975 /// finish processing an expression with sequencing, such as a comma
8976 /// expression, we fold its tree nodes into its parent, since they are
8977 /// unsequenced with respect to nodes we will visit later.
8978 class SequenceTree {
8979 struct Value {
8980 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
8981 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +00008982 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +00008983 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008984 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00008985
8986 public:
8987 /// \brief A region within an expression which may be sequenced with respect
8988 /// to some other region.
8989 class Seq {
8990 explicit Seq(unsigned N) : Index(N) {}
8991 unsigned Index;
8992 friend class SequenceTree;
8993 public:
8994 Seq() : Index(0) {}
8995 };
8996
8997 SequenceTree() { Values.push_back(Value(0)); }
8998 Seq root() const { return Seq(0); }
8999
9000 /// \brief Create a new sequence of operations, which is an unsequenced
9001 /// subset of \p Parent. This sequence of operations is sequenced with
9002 /// respect to other children of \p Parent.
9003 Seq allocate(Seq Parent) {
9004 Values.push_back(Value(Parent.Index));
9005 return Seq(Values.size() - 1);
9006 }
9007
9008 /// \brief Merge a sequence of operations into its parent.
9009 void merge(Seq S) {
9010 Values[S.Index].Merged = true;
9011 }
9012
9013 /// \brief Determine whether two operations are unsequenced. This operation
9014 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9015 /// should have been merged into its parent as appropriate.
9016 bool isUnsequenced(Seq Cur, Seq Old) {
9017 unsigned C = representative(Cur.Index);
9018 unsigned Target = representative(Old.Index);
9019 while (C >= Target) {
9020 if (C == Target)
9021 return true;
9022 C = Values[C].Parent;
9023 }
9024 return false;
9025 }
9026
9027 private:
9028 /// \brief Pick a representative for a sequence.
9029 unsigned representative(unsigned K) {
9030 if (Values[K].Merged)
9031 // Perform path compression as we go.
9032 return Values[K].Parent = representative(Values[K].Parent);
9033 return K;
9034 }
9035 };
9036
9037 /// An object for which we can track unsequenced uses.
9038 typedef NamedDecl *Object;
9039
9040 /// Different flavors of object usage which we track. We only track the
9041 /// least-sequenced usage of each kind.
9042 enum UsageKind {
9043 /// A read of an object. Multiple unsequenced reads are OK.
9044 UK_Use,
9045 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00009046 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00009047 UK_ModAsValue,
9048 /// A modification of an object which is not sequenced before the value
9049 /// computation of the expression, such as n++.
9050 UK_ModAsSideEffect,
9051
9052 UK_Count = UK_ModAsSideEffect + 1
9053 };
9054
9055 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00009056 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00009057 Expr *Use;
9058 SequenceTree::Seq Seq;
9059 };
9060
9061 struct UsageInfo {
9062 UsageInfo() : Diagnosed(false) {}
9063 Usage Uses[UK_Count];
9064 /// Have we issued a diagnostic for this variable already?
9065 bool Diagnosed;
9066 };
9067 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9068
9069 Sema &SemaRef;
9070 /// Sequenced regions within the expression.
9071 SequenceTree Tree;
9072 /// Declaration modifications and references which we have seen.
9073 UsageInfoMap UsageMap;
9074 /// The region we are currently within.
9075 SequenceTree::Seq Region;
9076 /// Filled in with declarations which were modified as a side-effect
9077 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009078 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00009079 /// Expressions to check later. We defer checking these to reduce
9080 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009081 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00009082
9083 /// RAII object wrapping the visitation of a sequenced subexpression of an
9084 /// expression. At the end of this process, the side-effects of the evaluation
9085 /// become sequenced with respect to the value computation of the result, so
9086 /// we downgrade any UK_ModAsSideEffect within the evaluation to
9087 /// UK_ModAsValue.
9088 struct SequencedSubexpression {
9089 SequencedSubexpression(SequenceChecker &Self)
9090 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9091 Self.ModAsSideEffect = &ModAsSideEffect;
9092 }
9093 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +00009094 for (auto &M : llvm::reverse(ModAsSideEffect)) {
9095 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +00009096 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +00009097 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9098 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +00009099 }
9100 Self.ModAsSideEffect = OldModAsSideEffect;
9101 }
9102
9103 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009104 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9105 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00009106 };
9107
Richard Smith40238f02013-06-20 22:21:56 +00009108 /// RAII object wrapping the visitation of a subexpression which we might
9109 /// choose to evaluate as a constant. If any subexpression is evaluated and
9110 /// found to be non-constant, this allows us to suppress the evaluation of
9111 /// the outer expression.
9112 class EvaluationTracker {
9113 public:
9114 EvaluationTracker(SequenceChecker &Self)
9115 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9116 Self.EvalTracker = this;
9117 }
9118 ~EvaluationTracker() {
9119 Self.EvalTracker = Prev;
9120 if (Prev)
9121 Prev->EvalOK &= EvalOK;
9122 }
9123
9124 bool evaluate(const Expr *E, bool &Result) {
9125 if (!EvalOK || E->isValueDependent())
9126 return false;
9127 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9128 return EvalOK;
9129 }
9130
9131 private:
9132 SequenceChecker &Self;
9133 EvaluationTracker *Prev;
9134 bool EvalOK;
9135 } *EvalTracker;
9136
Richard Smithc406cb72013-01-17 01:17:56 +00009137 /// \brief Find the object which is produced by the specified expression,
9138 /// if any.
9139 Object getObject(Expr *E, bool Mod) const {
9140 E = E->IgnoreParenCasts();
9141 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9142 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9143 return getObject(UO->getSubExpr(), Mod);
9144 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9145 if (BO->getOpcode() == BO_Comma)
9146 return getObject(BO->getRHS(), Mod);
9147 if (Mod && BO->isAssignmentOp())
9148 return getObject(BO->getLHS(), Mod);
9149 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9150 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9151 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9152 return ME->getMemberDecl();
9153 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9154 // FIXME: If this is a reference, map through to its value.
9155 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00009156 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00009157 }
9158
9159 /// \brief Note that an object was modified or used by an expression.
9160 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9161 Usage &U = UI.Uses[UK];
9162 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9163 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9164 ModAsSideEffect->push_back(std::make_pair(O, U));
9165 U.Use = Ref;
9166 U.Seq = Region;
9167 }
9168 }
9169 /// \brief Check whether a modification or use conflicts with a prior usage.
9170 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9171 bool IsModMod) {
9172 if (UI.Diagnosed)
9173 return;
9174
9175 const Usage &U = UI.Uses[OtherKind];
9176 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9177 return;
9178
9179 Expr *Mod = U.Use;
9180 Expr *ModOrUse = Ref;
9181 if (OtherKind == UK_Use)
9182 std::swap(Mod, ModOrUse);
9183
9184 SemaRef.Diag(Mod->getExprLoc(),
9185 IsModMod ? diag::warn_unsequenced_mod_mod
9186 : diag::warn_unsequenced_mod_use)
9187 << O << SourceRange(ModOrUse->getExprLoc());
9188 UI.Diagnosed = true;
9189 }
9190
9191 void notePreUse(Object O, Expr *Use) {
9192 UsageInfo &U = UsageMap[O];
9193 // Uses conflict with other modifications.
9194 checkUsage(O, U, Use, UK_ModAsValue, false);
9195 }
9196 void notePostUse(Object O, Expr *Use) {
9197 UsageInfo &U = UsageMap[O];
9198 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9199 addUsage(U, O, Use, UK_Use);
9200 }
9201
9202 void notePreMod(Object O, Expr *Mod) {
9203 UsageInfo &U = UsageMap[O];
9204 // Modifications conflict with other modifications and with uses.
9205 checkUsage(O, U, Mod, UK_ModAsValue, true);
9206 checkUsage(O, U, Mod, UK_Use, false);
9207 }
9208 void notePostMod(Object O, Expr *Use, UsageKind UK) {
9209 UsageInfo &U = UsageMap[O];
9210 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9211 addUsage(U, O, Use, UK);
9212 }
9213
9214public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009215 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00009216 : Base(S.Context), SemaRef(S), Region(Tree.root()),
9217 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009218 Visit(E);
9219 }
9220
9221 void VisitStmt(Stmt *S) {
9222 // Skip all statements which aren't expressions for now.
9223 }
9224
9225 void VisitExpr(Expr *E) {
9226 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00009227 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00009228 }
9229
9230 void VisitCastExpr(CastExpr *E) {
9231 Object O = Object();
9232 if (E->getCastKind() == CK_LValueToRValue)
9233 O = getObject(E->getSubExpr(), false);
9234
9235 if (O)
9236 notePreUse(O, E);
9237 VisitExpr(E);
9238 if (O)
9239 notePostUse(O, E);
9240 }
9241
9242 void VisitBinComma(BinaryOperator *BO) {
9243 // C++11 [expr.comma]p1:
9244 // Every value computation and side effect associated with the left
9245 // expression is sequenced before every value computation and side
9246 // effect associated with the right expression.
9247 SequenceTree::Seq LHS = Tree.allocate(Region);
9248 SequenceTree::Seq RHS = Tree.allocate(Region);
9249 SequenceTree::Seq OldRegion = Region;
9250
9251 {
9252 SequencedSubexpression SeqLHS(*this);
9253 Region = LHS;
9254 Visit(BO->getLHS());
9255 }
9256
9257 Region = RHS;
9258 Visit(BO->getRHS());
9259
9260 Region = OldRegion;
9261
9262 // Forget that LHS and RHS are sequenced. They are both unsequenced
9263 // with respect to other stuff.
9264 Tree.merge(LHS);
9265 Tree.merge(RHS);
9266 }
9267
9268 void VisitBinAssign(BinaryOperator *BO) {
9269 // The modification is sequenced after the value computation of the LHS
9270 // and RHS, so check it before inspecting the operands and update the
9271 // map afterwards.
9272 Object O = getObject(BO->getLHS(), true);
9273 if (!O)
9274 return VisitExpr(BO);
9275
9276 notePreMod(O, BO);
9277
9278 // C++11 [expr.ass]p7:
9279 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
9280 // only once.
9281 //
9282 // Therefore, for a compound assignment operator, O is considered used
9283 // everywhere except within the evaluation of E1 itself.
9284 if (isa<CompoundAssignOperator>(BO))
9285 notePreUse(O, BO);
9286
9287 Visit(BO->getLHS());
9288
9289 if (isa<CompoundAssignOperator>(BO))
9290 notePostUse(O, BO);
9291
9292 Visit(BO->getRHS());
9293
Richard Smith83e37bee2013-06-26 23:16:51 +00009294 // C++11 [expr.ass]p1:
9295 // the assignment is sequenced [...] before the value computation of the
9296 // assignment expression.
9297 // C11 6.5.16/3 has no such rule.
9298 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9299 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00009300 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009301
Richard Smithc406cb72013-01-17 01:17:56 +00009302 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
9303 VisitBinAssign(CAO);
9304 }
9305
9306 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9307 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9308 void VisitUnaryPreIncDec(UnaryOperator *UO) {
9309 Object O = getObject(UO->getSubExpr(), true);
9310 if (!O)
9311 return VisitExpr(UO);
9312
9313 notePreMod(O, UO);
9314 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00009315 // C++11 [expr.pre.incr]p1:
9316 // the expression ++x is equivalent to x+=1
9317 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9318 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00009319 }
9320
9321 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9322 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9323 void VisitUnaryPostIncDec(UnaryOperator *UO) {
9324 Object O = getObject(UO->getSubExpr(), true);
9325 if (!O)
9326 return VisitExpr(UO);
9327
9328 notePreMod(O, UO);
9329 Visit(UO->getSubExpr());
9330 notePostMod(O, UO, UK_ModAsSideEffect);
9331 }
9332
9333 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
9334 void VisitBinLOr(BinaryOperator *BO) {
9335 // The side-effects of the LHS of an '&&' are sequenced before the
9336 // value computation of the RHS, and hence before the value computation
9337 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
9338 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00009339 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00009340 {
9341 SequencedSubexpression Sequenced(*this);
9342 Visit(BO->getLHS());
9343 }
9344
9345 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009346 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00009347 if (!Result)
9348 Visit(BO->getRHS());
9349 } else {
9350 // Check for unsequenced operations in the RHS, treating it as an
9351 // entirely separate evaluation.
9352 //
9353 // FIXME: If there are operations in the RHS which are unsequenced
9354 // with respect to operations outside the RHS, and those operations
9355 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00009356 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00009357 }
Richard Smithc406cb72013-01-17 01:17:56 +00009358 }
9359 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00009360 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00009361 {
9362 SequencedSubexpression Sequenced(*this);
9363 Visit(BO->getLHS());
9364 }
9365
9366 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009367 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00009368 if (Result)
9369 Visit(BO->getRHS());
9370 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00009371 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00009372 }
Richard Smithc406cb72013-01-17 01:17:56 +00009373 }
9374
9375 // Only visit the condition, unless we can be sure which subexpression will
9376 // be chosen.
9377 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00009378 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00009379 {
9380 SequencedSubexpression Sequenced(*this);
9381 Visit(CO->getCond());
9382 }
Richard Smithc406cb72013-01-17 01:17:56 +00009383
9384 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009385 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00009386 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00009387 else {
Richard Smithd33f5202013-01-17 23:18:09 +00009388 WorkList.push_back(CO->getTrueExpr());
9389 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00009390 }
Richard Smithc406cb72013-01-17 01:17:56 +00009391 }
9392
Richard Smithe3dbfe02013-06-30 10:40:20 +00009393 void VisitCallExpr(CallExpr *CE) {
9394 // C++11 [intro.execution]p15:
9395 // When calling a function [...], every value computation and side effect
9396 // associated with any argument expression, or with the postfix expression
9397 // designating the called function, is sequenced before execution of every
9398 // expression or statement in the body of the function [and thus before
9399 // the value computation of its result].
9400 SequencedSubexpression Sequenced(*this);
9401 Base::VisitCallExpr(CE);
9402
9403 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
9404 }
9405
Richard Smithc406cb72013-01-17 01:17:56 +00009406 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009407 // This is a call, so all subexpressions are sequenced before the result.
9408 SequencedSubexpression Sequenced(*this);
9409
Richard Smithc406cb72013-01-17 01:17:56 +00009410 if (!CCE->isListInitialization())
9411 return VisitExpr(CCE);
9412
9413 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009414 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00009415 SequenceTree::Seq Parent = Region;
9416 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
9417 E = CCE->arg_end();
9418 I != E; ++I) {
9419 Region = Tree.allocate(Parent);
9420 Elts.push_back(Region);
9421 Visit(*I);
9422 }
9423
9424 // Forget that the initializers are sequenced.
9425 Region = Parent;
9426 for (unsigned I = 0; I < Elts.size(); ++I)
9427 Tree.merge(Elts[I]);
9428 }
9429
9430 void VisitInitListExpr(InitListExpr *ILE) {
9431 if (!SemaRef.getLangOpts().CPlusPlus11)
9432 return VisitExpr(ILE);
9433
9434 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009435 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00009436 SequenceTree::Seq Parent = Region;
9437 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
9438 Expr *E = ILE->getInit(I);
9439 if (!E) continue;
9440 Region = Tree.allocate(Parent);
9441 Elts.push_back(Region);
9442 Visit(E);
9443 }
9444
9445 // Forget that the initializers are sequenced.
9446 Region = Parent;
9447 for (unsigned I = 0; I < Elts.size(); ++I)
9448 Tree.merge(Elts[I]);
9449 }
9450};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009451} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +00009452
9453void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009454 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00009455 WorkList.push_back(E);
9456 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00009457 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00009458 SequenceChecker(*this, Item, WorkList);
9459 }
Richard Smithc406cb72013-01-17 01:17:56 +00009460}
9461
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009462void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
9463 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009464 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +00009465 if (!E->isInstantiationDependent())
9466 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009467 if (!IsConstexpr && !E->isValueDependent())
9468 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009469 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +00009470}
9471
John McCall1f425642010-11-11 03:21:53 +00009472void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
9473 FieldDecl *BitField,
9474 Expr *Init) {
9475 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
9476}
9477
David Majnemer61a5bbf2015-04-07 22:08:51 +00009478static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
9479 SourceLocation Loc) {
9480 if (!PType->isVariablyModifiedType())
9481 return;
9482 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
9483 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
9484 return;
9485 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00009486 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
9487 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
9488 return;
9489 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00009490 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
9491 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
9492 return;
9493 }
9494
9495 const ArrayType *AT = S.Context.getAsArrayType(PType);
9496 if (!AT)
9497 return;
9498
9499 if (AT->getSizeModifier() != ArrayType::Star) {
9500 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
9501 return;
9502 }
9503
9504 S.Diag(Loc, diag::err_array_star_in_function_definition);
9505}
9506
Mike Stump0c2ec772010-01-21 03:59:47 +00009507/// CheckParmsForFunctionDef - Check that the parameters of the given
9508/// function are appropriate for the definition of a function. This
9509/// takes care of any checks that cannot be performed on the
9510/// declaration itself, e.g., that the types of each of the function
9511/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +00009512bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +00009513 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009514 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +00009515 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009516 // C99 6.7.5.3p4: the parameters in a parameter type list in a
9517 // function declarator that is part of a function definition of
9518 // that function shall not have incomplete type.
9519 //
9520 // This is also C++ [dcl.fct]p6.
9521 if (!Param->isInvalidDecl() &&
9522 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009523 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009524 Param->setInvalidDecl();
9525 HasInvalidParm = true;
9526 }
9527
9528 // C99 6.9.1p5: If the declarator includes a parameter type list, the
9529 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00009530 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00009531 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00009532 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00009533 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00009534 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00009535
9536 // C99 6.7.5.3p12:
9537 // If the function declarator is not part of a definition of that
9538 // function, parameters may have incomplete type and may use the [*]
9539 // notation in their sequences of declarator specifiers to specify
9540 // variable length array types.
9541 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00009542 // FIXME: This diagnostic should point the '[*]' if source-location
9543 // information is added for it.
9544 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00009545
9546 // MSVC destroys objects passed by value in the callee. Therefore a
9547 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00009548 // object's destructor. However, we don't perform any direct access check
9549 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00009550 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
9551 .getCXXABI()
9552 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00009553 if (!Param->isInvalidDecl()) {
9554 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
9555 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
9556 if (!ClassDecl->isInvalidDecl() &&
9557 !ClassDecl->hasIrrelevantDestructor() &&
9558 !ClassDecl->isDependentContext()) {
9559 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9560 MarkFunctionReferenced(Param->getLocation(), Destructor);
9561 DiagnoseUseOfDecl(Destructor, Param->getLocation());
9562 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00009563 }
9564 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00009565 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009566
9567 // Parameters with the pass_object_size attribute only need to be marked
9568 // constant at function definitions. Because we lack information about
9569 // whether we're on a declaration or definition when we're instantiating the
9570 // attribute, we need to check for constness here.
9571 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
9572 if (!Param->getType().isConstQualified())
9573 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
9574 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +00009575 }
9576
9577 return HasInvalidParm;
9578}
John McCall2b5c1b22010-08-12 21:44:57 +00009579
9580/// CheckCastAlign - Implements -Wcast-align, which warns when a
9581/// pointer cast increases the alignment requirements.
9582void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
9583 // This is actually a lot of work to potentially be doing on every
9584 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009585 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00009586 return;
9587
9588 // Ignore dependent types.
9589 if (T->isDependentType() || Op->getType()->isDependentType())
9590 return;
9591
9592 // Require that the destination be a pointer type.
9593 const PointerType *DestPtr = T->getAs<PointerType>();
9594 if (!DestPtr) return;
9595
9596 // If the destination has alignment 1, we're done.
9597 QualType DestPointee = DestPtr->getPointeeType();
9598 if (DestPointee->isIncompleteType()) return;
9599 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
9600 if (DestAlign.isOne()) return;
9601
9602 // Require that the source be a pointer type.
9603 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
9604 if (!SrcPtr) return;
9605 QualType SrcPointee = SrcPtr->getPointeeType();
9606
9607 // Whitelist casts from cv void*. We already implicitly
9608 // whitelisted casts to cv void*, since they have alignment 1.
9609 // Also whitelist casts involving incomplete types, which implicitly
9610 // includes 'void'.
9611 if (SrcPointee->isIncompleteType()) return;
9612
9613 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
9614 if (SrcAlign >= DestAlign) return;
9615
9616 Diag(TRange.getBegin(), diag::warn_cast_align)
9617 << Op->getType() << T
9618 << static_cast<unsigned>(SrcAlign.getQuantity())
9619 << static_cast<unsigned>(DestAlign.getQuantity())
9620 << TRange << Op->getSourceRange();
9621}
9622
Chandler Carruth28389f02011-08-05 09:10:50 +00009623/// \brief Check whether this array fits the idiom of a size-one tail padded
9624/// array member of a struct.
9625///
9626/// We avoid emitting out-of-bounds access warnings for such arrays as they are
9627/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +00009628static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +00009629 const NamedDecl *ND) {
9630 if (Size != 1 || !ND) return false;
9631
9632 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
9633 if (!FD) return false;
9634
9635 // Don't consider sizes resulting from macro expansions or template argument
9636 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00009637
9638 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009639 while (TInfo) {
9640 TypeLoc TL = TInfo->getTypeLoc();
9641 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00009642 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
9643 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009644 TInfo = TDL->getTypeSourceInfo();
9645 continue;
9646 }
David Blaikie6adc78e2013-02-18 22:06:02 +00009647 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
9648 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00009649 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
9650 return false;
9651 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009652 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00009653 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009654
9655 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00009656 if (!RD) return false;
9657 if (RD->isUnion()) return false;
9658 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9659 if (!CRD->isStandardLayout()) return false;
9660 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009661
Benjamin Kramer8c543672011-08-06 03:04:42 +00009662 // See if this is the last field decl in the record.
9663 const Decl *D = FD;
9664 while ((D = D->getNextDeclInContext()))
9665 if (isa<FieldDecl>(D))
9666 return false;
9667 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00009668}
9669
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009670void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009671 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00009672 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009673 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009674 if (IndexExpr->isValueDependent())
9675 return;
9676
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009677 const Type *EffectiveType =
9678 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009679 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009680 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009681 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009682 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00009683 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00009684
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009685 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +00009686 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +00009687 return;
Richard Smith13f67182011-12-16 19:31:14 +00009688 if (IndexNegated)
9689 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00009690
Craig Topperc3ec1492014-05-26 06:22:03 +00009691 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00009692 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9693 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00009694 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00009695 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00009696
Ted Kremeneke4b316c2011-02-23 23:06:04 +00009697 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009698 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00009699 if (!size.isStrictlyPositive())
9700 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009701
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009702 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +00009703 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009704 // Make sure we're comparing apples to apples when comparing index to size
9705 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
9706 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00009707 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00009708 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009709 if (ptrarith_typesize != array_typesize) {
9710 // There's a cast to a different size type involved
9711 uint64_t ratio = array_typesize / ptrarith_typesize;
9712 // TODO: Be smarter about handling cases where array_typesize is not a
9713 // multiple of ptrarith_typesize
9714 if (ptrarith_typesize * ratio == array_typesize)
9715 size *= llvm::APInt(size.getBitWidth(), ratio);
9716 }
9717 }
9718
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009719 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009720 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009721 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009722 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009723
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009724 // For array subscripting the index must be less than size, but for pointer
9725 // arithmetic also allow the index (offset) to be equal to size since
9726 // computing the next address after the end of the array is legal and
9727 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009728 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00009729 return;
9730
9731 // Also don't warn for arrays of size 1 which are members of some
9732 // structure. These are often used to approximate flexible arrays in C89
9733 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009734 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00009735 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009736
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009737 // Suppress the warning if the subscript expression (as identified by the
9738 // ']' location) and the index expression are both from macro expansions
9739 // within a system header.
9740 if (ASE) {
9741 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
9742 ASE->getRBracketLoc());
9743 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
9744 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
9745 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00009746 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009747 return;
9748 }
9749 }
9750
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009751 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009752 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009753 DiagID = diag::warn_array_index_exceeds_bounds;
9754
9755 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9756 PDiag(DiagID) << index.toString(10, true)
9757 << size.toString(10, true)
9758 << (unsigned)size.getLimitedValue(~0U)
9759 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009760 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009761 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009762 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009763 DiagID = diag::warn_ptr_arith_precedes_bounds;
9764 if (index.isNegative()) index = -index;
9765 }
9766
9767 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9768 PDiag(DiagID) << index.toString(10, true)
9769 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00009770 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00009771
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00009772 if (!ND) {
9773 // Try harder to find a NamedDecl to point at in the note.
9774 while (const ArraySubscriptExpr *ASE =
9775 dyn_cast<ArraySubscriptExpr>(BaseExpr))
9776 BaseExpr = ASE->getBase()->IgnoreParenCasts();
9777 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9778 ND = dyn_cast<NamedDecl>(DRE->getDecl());
9779 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9780 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9781 }
9782
Chandler Carruth1af88f12011-02-17 21:10:52 +00009783 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009784 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
9785 PDiag(diag::note_array_index_out_of_bounds)
9786 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00009787}
9788
Ted Kremenekdf26df72011-03-01 18:41:00 +00009789void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009790 int AllowOnePastEnd = 0;
9791 while (expr) {
9792 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00009793 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009794 case Stmt::ArraySubscriptExprClass: {
9795 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009796 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009797 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00009798 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009799 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009800 case Stmt::OMPArraySectionExprClass: {
9801 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
9802 if (ASE->getLowerBound())
9803 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
9804 /*ASE=*/nullptr, AllowOnePastEnd > 0);
9805 return;
9806 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009807 case Stmt::UnaryOperatorClass: {
9808 // Only unwrap the * and & unary operators
9809 const UnaryOperator *UO = cast<UnaryOperator>(expr);
9810 expr = UO->getSubExpr();
9811 switch (UO->getOpcode()) {
9812 case UO_AddrOf:
9813 AllowOnePastEnd++;
9814 break;
9815 case UO_Deref:
9816 AllowOnePastEnd--;
9817 break;
9818 default:
9819 return;
9820 }
9821 break;
9822 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009823 case Stmt::ConditionalOperatorClass: {
9824 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
9825 if (const Expr *lhs = cond->getLHS())
9826 CheckArrayAccess(lhs);
9827 if (const Expr *rhs = cond->getRHS())
9828 CheckArrayAccess(rhs);
9829 return;
9830 }
9831 default:
9832 return;
9833 }
Peter Collingbourne91147592011-04-15 00:35:48 +00009834 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009835}
John McCall31168b02011-06-15 23:02:42 +00009836
9837//===--- CHECK: Objective-C retain cycles ----------------------------------//
9838
9839namespace {
9840 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00009841 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00009842 VarDecl *Variable;
9843 SourceRange Range;
9844 SourceLocation Loc;
9845 bool Indirect;
9846
9847 void setLocsFrom(Expr *e) {
9848 Loc = e->getExprLoc();
9849 Range = e->getSourceRange();
9850 }
9851 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009852} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009853
9854/// Consider whether capturing the given variable can possibly lead to
9855/// a retain cycle.
9856static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00009857 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00009858 // lifetime. In MRR, it's captured strongly if the variable is
9859 // __block and has an appropriate type.
9860 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9861 return false;
9862
9863 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009864 if (ref)
9865 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00009866 return true;
9867}
9868
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009869static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00009870 while (true) {
9871 e = e->IgnoreParens();
9872 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
9873 switch (cast->getCastKind()) {
9874 case CK_BitCast:
9875 case CK_LValueBitCast:
9876 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00009877 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00009878 e = cast->getSubExpr();
9879 continue;
9880
John McCall31168b02011-06-15 23:02:42 +00009881 default:
9882 return false;
9883 }
9884 }
9885
9886 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
9887 ObjCIvarDecl *ivar = ref->getDecl();
9888 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9889 return false;
9890
9891 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009892 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00009893 return false;
9894
9895 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
9896 owner.Indirect = true;
9897 return true;
9898 }
9899
9900 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9901 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
9902 if (!var) return false;
9903 return considerVariable(var, ref, owner);
9904 }
9905
John McCall31168b02011-06-15 23:02:42 +00009906 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
9907 if (member->isArrow()) return false;
9908
9909 // Don't count this as an indirect ownership.
9910 e = member->getBase();
9911 continue;
9912 }
9913
John McCallfe96e0b2011-11-06 09:01:30 +00009914 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
9915 // Only pay attention to pseudo-objects on property references.
9916 ObjCPropertyRefExpr *pre
9917 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
9918 ->IgnoreParens());
9919 if (!pre) return false;
9920 if (pre->isImplicitProperty()) return false;
9921 ObjCPropertyDecl *property = pre->getExplicitProperty();
9922 if (!property->isRetaining() &&
9923 !(property->getPropertyIvarDecl() &&
9924 property->getPropertyIvarDecl()->getType()
9925 .getObjCLifetime() == Qualifiers::OCL_Strong))
9926 return false;
9927
9928 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009929 if (pre->isSuperReceiver()) {
9930 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
9931 if (!owner.Variable)
9932 return false;
9933 owner.Loc = pre->getLocation();
9934 owner.Range = pre->getSourceRange();
9935 return true;
9936 }
John McCallfe96e0b2011-11-06 09:01:30 +00009937 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
9938 ->getSourceExpr());
9939 continue;
9940 }
9941
John McCall31168b02011-06-15 23:02:42 +00009942 // Array ivars?
9943
9944 return false;
9945 }
9946}
9947
9948namespace {
9949 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
9950 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
9951 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009952 Context(Context), Variable(variable), Capturer(nullptr),
9953 VarWillBeReased(false) {}
9954 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00009955 VarDecl *Variable;
9956 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009957 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00009958
9959 void VisitDeclRefExpr(DeclRefExpr *ref) {
9960 if (ref->getDecl() == Variable && !Capturer)
9961 Capturer = ref;
9962 }
9963
John McCall31168b02011-06-15 23:02:42 +00009964 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
9965 if (Capturer) return;
9966 Visit(ref->getBase());
9967 if (Capturer && ref->isFreeIvar())
9968 Capturer = ref;
9969 }
9970
9971 void VisitBlockExpr(BlockExpr *block) {
9972 // Look inside nested blocks
9973 if (block->getBlockDecl()->capturesVariable(Variable))
9974 Visit(block->getBlockDecl()->getBody());
9975 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00009976
9977 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
9978 if (Capturer) return;
9979 if (OVE->getSourceExpr())
9980 Visit(OVE->getSourceExpr());
9981 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009982 void VisitBinaryOperator(BinaryOperator *BinOp) {
9983 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
9984 return;
9985 Expr *LHS = BinOp->getLHS();
9986 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
9987 if (DRE->getDecl() != Variable)
9988 return;
9989 if (Expr *RHS = BinOp->getRHS()) {
9990 RHS = RHS->IgnoreParenCasts();
9991 llvm::APSInt Value;
9992 VarWillBeReased =
9993 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
9994 }
9995 }
9996 }
John McCall31168b02011-06-15 23:02:42 +00009997 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009998} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009999
10000/// Check whether the given argument is a block which captures a
10001/// variable.
10002static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
10003 assert(owner.Variable && owner.Loc.isValid());
10004
10005 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000010006
10007 // Look through [^{...} copy] and Block_copy(^{...}).
10008 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
10009 Selector Cmd = ME->getSelector();
10010 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
10011 e = ME->getInstanceReceiver();
10012 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000010013 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000010014 e = e->IgnoreParenCasts();
10015 }
10016 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
10017 if (CE->getNumArgs() == 1) {
10018 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000010019 if (Fn) {
10020 const IdentifierInfo *FnI = Fn->getIdentifier();
10021 if (FnI && FnI->isStr("_Block_copy")) {
10022 e = CE->getArg(0)->IgnoreParenCasts();
10023 }
10024 }
Jordan Rose67e887c2012-09-17 17:54:30 +000010025 }
10026 }
10027
John McCall31168b02011-06-15 23:02:42 +000010028 BlockExpr *block = dyn_cast<BlockExpr>(e);
10029 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000010030 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000010031
10032 FindCaptureVisitor visitor(S.Context, owner.Variable);
10033 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010034 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000010035}
10036
10037static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10038 RetainCycleOwner &owner) {
10039 assert(capturer);
10040 assert(owner.Variable && owner.Loc.isValid());
10041
10042 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10043 << owner.Variable << capturer->getSourceRange();
10044 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10045 << owner.Indirect << owner.Range;
10046}
10047
10048/// Check for a keyword selector that starts with the word 'add' or
10049/// 'set'.
10050static bool isSetterLikeSelector(Selector sel) {
10051 if (sel.isUnarySelector()) return false;
10052
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010053 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000010054 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010055 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000010056 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010057 else if (str.startswith("add")) {
10058 // Specially whitelist 'addOperationWithBlock:'.
10059 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
10060 return false;
10061 str = str.substr(3);
10062 }
John McCall31168b02011-06-15 23:02:42 +000010063 else
10064 return false;
10065
10066 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000010067 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000010068}
10069
Benjamin Kramer3a743452015-03-09 15:03:32 +000010070static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
10071 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010072 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
10073 Message->getReceiverInterface(),
10074 NSAPI::ClassId_NSMutableArray);
10075 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010076 return None;
10077 }
10078
10079 Selector Sel = Message->getSelector();
10080
10081 Optional<NSAPI::NSArrayMethodKind> MKOpt =
10082 S.NSAPIObj->getNSArrayMethodKind(Sel);
10083 if (!MKOpt) {
10084 return None;
10085 }
10086
10087 NSAPI::NSArrayMethodKind MK = *MKOpt;
10088
10089 switch (MK) {
10090 case NSAPI::NSMutableArr_addObject:
10091 case NSAPI::NSMutableArr_insertObjectAtIndex:
10092 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
10093 return 0;
10094 case NSAPI::NSMutableArr_replaceObjectAtIndex:
10095 return 1;
10096
10097 default:
10098 return None;
10099 }
10100
10101 return None;
10102}
10103
10104static
10105Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10106 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010107 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10108 Message->getReceiverInterface(),
10109 NSAPI::ClassId_NSMutableDictionary);
10110 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010111 return None;
10112 }
10113
10114 Selector Sel = Message->getSelector();
10115
10116 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10117 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10118 if (!MKOpt) {
10119 return None;
10120 }
10121
10122 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10123
10124 switch (MK) {
10125 case NSAPI::NSMutableDict_setObjectForKey:
10126 case NSAPI::NSMutableDict_setValueForKey:
10127 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10128 return 0;
10129
10130 default:
10131 return None;
10132 }
10133
10134 return None;
10135}
10136
10137static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010138 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10139 Message->getReceiverInterface(),
10140 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000010141
Alex Denisov5dfac812015-08-06 04:51:14 +000010142 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10143 Message->getReceiverInterface(),
10144 NSAPI::ClassId_NSMutableOrderedSet);
10145 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010146 return None;
10147 }
10148
10149 Selector Sel = Message->getSelector();
10150
10151 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10152 if (!MKOpt) {
10153 return None;
10154 }
10155
10156 NSAPI::NSSetMethodKind MK = *MKOpt;
10157
10158 switch (MK) {
10159 case NSAPI::NSMutableSet_addObject:
10160 case NSAPI::NSOrderedSet_setObjectAtIndex:
10161 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10162 case NSAPI::NSOrderedSet_insertObjectAtIndex:
10163 return 0;
10164 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10165 return 1;
10166 }
10167
10168 return None;
10169}
10170
10171void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10172 if (!Message->isInstanceMessage()) {
10173 return;
10174 }
10175
10176 Optional<int> ArgOpt;
10177
10178 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10179 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10180 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10181 return;
10182 }
10183
10184 int ArgIndex = *ArgOpt;
10185
Alex Denisove1d882c2015-03-04 17:55:52 +000010186 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10187 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10188 Arg = OE->getSourceExpr()->IgnoreImpCasts();
10189 }
10190
Alex Denisov5dfac812015-08-06 04:51:14 +000010191 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010192 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010193 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010194 Diag(Message->getSourceRange().getBegin(),
10195 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000010196 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000010197 }
10198 }
Alex Denisov5dfac812015-08-06 04:51:14 +000010199 } else {
10200 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10201
10202 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10203 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10204 }
10205
10206 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10207 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10208 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10209 ValueDecl *Decl = ReceiverRE->getDecl();
10210 Diag(Message->getSourceRange().getBegin(),
10211 diag::warn_objc_circular_container)
10212 << Decl->getName() << Decl->getName();
10213 if (!ArgRE->isObjCSelfExpr()) {
10214 Diag(Decl->getLocation(),
10215 diag::note_objc_circular_container_declared_here)
10216 << Decl->getName();
10217 }
10218 }
10219 }
10220 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
10221 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
10222 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
10223 ObjCIvarDecl *Decl = IvarRE->getDecl();
10224 Diag(Message->getSourceRange().getBegin(),
10225 diag::warn_objc_circular_container)
10226 << Decl->getName() << Decl->getName();
10227 Diag(Decl->getLocation(),
10228 diag::note_objc_circular_container_declared_here)
10229 << Decl->getName();
10230 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010231 }
10232 }
10233 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010234}
10235
John McCall31168b02011-06-15 23:02:42 +000010236/// Check a message send to see if it's likely to cause a retain cycle.
10237void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
10238 // Only check instance methods whose selector looks like a setter.
10239 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
10240 return;
10241
10242 // Try to find a variable that the receiver is strongly owned by.
10243 RetainCycleOwner owner;
10244 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010245 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000010246 return;
10247 } else {
10248 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
10249 owner.Variable = getCurMethodDecl()->getSelfDecl();
10250 owner.Loc = msg->getSuperLoc();
10251 owner.Range = msg->getSuperLoc();
10252 }
10253
10254 // Check whether the receiver is captured by any of the arguments.
10255 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
10256 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
10257 return diagnoseRetainCycle(*this, capturer, owner);
10258}
10259
10260/// Check a property assign to see if it's likely to cause a retain cycle.
10261void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
10262 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010263 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000010264 return;
10265
10266 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
10267 diagnoseRetainCycle(*this, capturer, owner);
10268}
10269
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010270void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
10271 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000010272 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010273 return;
10274
10275 // Because we don't have an expression for the variable, we have to set the
10276 // location explicitly here.
10277 Owner.Loc = Var->getLocation();
10278 Owner.Range = Var->getSourceRange();
10279
10280 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
10281 diagnoseRetainCycle(*this, Capturer, Owner);
10282}
10283
Ted Kremenek9304da92012-12-21 08:04:28 +000010284static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
10285 Expr *RHS, bool isProperty) {
10286 // Check if RHS is an Objective-C object literal, which also can get
10287 // immediately zapped in a weak reference. Note that we explicitly
10288 // allow ObjCStringLiterals, since those are designed to never really die.
10289 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010290
Ted Kremenek64873352012-12-21 22:46:35 +000010291 // This enum needs to match with the 'select' in
10292 // warn_objc_arc_literal_assign (off-by-1).
10293 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
10294 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
10295 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010296
10297 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000010298 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000010299 << (isProperty ? 0 : 1)
10300 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010301
10302 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000010303}
10304
Ted Kremenekc1f014a2012-12-21 19:45:30 +000010305static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
10306 Qualifiers::ObjCLifetime LT,
10307 Expr *RHS, bool isProperty) {
10308 // Strip off any implicit cast added to get to the one ARC-specific.
10309 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
10310 if (cast->getCastKind() == CK_ARCConsumeObject) {
10311 S.Diag(Loc, diag::warn_arc_retained_assign)
10312 << (LT == Qualifiers::OCL_ExplicitNone)
10313 << (isProperty ? 0 : 1)
10314 << RHS->getSourceRange();
10315 return true;
10316 }
10317 RHS = cast->getSubExpr();
10318 }
10319
10320 if (LT == Qualifiers::OCL_Weak &&
10321 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
10322 return true;
10323
10324 return false;
10325}
10326
Ted Kremenekb36234d2012-12-21 08:04:20 +000010327bool Sema::checkUnsafeAssigns(SourceLocation Loc,
10328 QualType LHS, Expr *RHS) {
10329 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
10330
10331 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
10332 return false;
10333
10334 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
10335 return true;
10336
10337 return false;
10338}
10339
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010340void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
10341 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010342 QualType LHSType;
10343 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010344 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010345 ObjCPropertyRefExpr *PRE
10346 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
10347 if (PRE && !PRE->isImplicitProperty()) {
10348 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10349 if (PD)
10350 LHSType = PD->getType();
10351 }
10352
10353 if (LHSType.isNull())
10354 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000010355
10356 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
10357
10358 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010359 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000010360 getCurFunction()->markSafeWeakUse(LHS);
10361 }
10362
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010363 if (checkUnsafeAssigns(Loc, LHSType, RHS))
10364 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000010365
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010366 // FIXME. Check for other life times.
10367 if (LT != Qualifiers::OCL_None)
10368 return;
10369
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010370 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010371 if (PRE->isImplicitProperty())
10372 return;
10373 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10374 if (!PD)
10375 return;
10376
Bill Wendling44426052012-12-20 19:22:21 +000010377 unsigned Attributes = PD->getPropertyAttributes();
10378 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010379 // when 'assign' attribute was not explicitly specified
10380 // by user, ignore it and rely on property type itself
10381 // for lifetime info.
10382 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
10383 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
10384 LHSType->isObjCRetainableType())
10385 return;
10386
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010387 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000010388 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010389 Diag(Loc, diag::warn_arc_retained_property_assign)
10390 << RHS->getSourceRange();
10391 return;
10392 }
10393 RHS = cast->getSubExpr();
10394 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010395 }
Bill Wendling44426052012-12-20 19:22:21 +000010396 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000010397 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
10398 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000010399 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010400 }
10401}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010402
10403//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
10404
10405namespace {
10406bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
10407 SourceLocation StmtLoc,
10408 const NullStmt *Body) {
10409 // Do not warn if the body is a macro that expands to nothing, e.g:
10410 //
10411 // #define CALL(x)
10412 // if (condition)
10413 // CALL(0);
10414 //
10415 if (Body->hasLeadingEmptyMacro())
10416 return false;
10417
10418 // Get line numbers of statement and body.
10419 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000010420 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010421 &StmtLineInvalid);
10422 if (StmtLineInvalid)
10423 return false;
10424
10425 bool BodyLineInvalid;
10426 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
10427 &BodyLineInvalid);
10428 if (BodyLineInvalid)
10429 return false;
10430
10431 // Warn if null statement and body are on the same line.
10432 if (StmtLine != BodyLine)
10433 return false;
10434
10435 return true;
10436}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010437} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010438
10439void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
10440 const Stmt *Body,
10441 unsigned DiagID) {
10442 // Since this is a syntactic check, don't emit diagnostic for template
10443 // instantiations, this just adds noise.
10444 if (CurrentInstantiationScope)
10445 return;
10446
10447 // The body should be a null statement.
10448 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10449 if (!NBody)
10450 return;
10451
10452 // Do the usual checks.
10453 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10454 return;
10455
10456 Diag(NBody->getSemiLoc(), DiagID);
10457 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10458}
10459
10460void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
10461 const Stmt *PossibleBody) {
10462 assert(!CurrentInstantiationScope); // Ensured by caller
10463
10464 SourceLocation StmtLoc;
10465 const Stmt *Body;
10466 unsigned DiagID;
10467 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
10468 StmtLoc = FS->getRParenLoc();
10469 Body = FS->getBody();
10470 DiagID = diag::warn_empty_for_body;
10471 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
10472 StmtLoc = WS->getCond()->getSourceRange().getEnd();
10473 Body = WS->getBody();
10474 DiagID = diag::warn_empty_while_body;
10475 } else
10476 return; // Neither `for' nor `while'.
10477
10478 // The body should be a null statement.
10479 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10480 if (!NBody)
10481 return;
10482
10483 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010484 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010485 return;
10486
10487 // Do the usual checks.
10488 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10489 return;
10490
10491 // `for(...);' and `while(...);' are popular idioms, so in order to keep
10492 // noise level low, emit diagnostics only if for/while is followed by a
10493 // CompoundStmt, e.g.:
10494 // for (int i = 0; i < n; i++);
10495 // {
10496 // a(i);
10497 // }
10498 // or if for/while is followed by a statement with more indentation
10499 // than for/while itself:
10500 // for (int i = 0; i < n; i++);
10501 // a(i);
10502 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
10503 if (!ProbableTypo) {
10504 bool BodyColInvalid;
10505 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
10506 PossibleBody->getLocStart(),
10507 &BodyColInvalid);
10508 if (BodyColInvalid)
10509 return;
10510
10511 bool StmtColInvalid;
10512 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
10513 S->getLocStart(),
10514 &StmtColInvalid);
10515 if (StmtColInvalid)
10516 return;
10517
10518 if (BodyCol > StmtCol)
10519 ProbableTypo = true;
10520 }
10521
10522 if (ProbableTypo) {
10523 Diag(NBody->getSemiLoc(), DiagID);
10524 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10525 }
10526}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010527
Richard Trieu36d0b2b2015-01-13 02:32:02 +000010528//===--- CHECK: Warn on self move with std::move. -------------------------===//
10529
10530/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
10531void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
10532 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000010533 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
10534 return;
10535
10536 if (!ActiveTemplateInstantiations.empty())
10537 return;
10538
10539 // Strip parens and casts away.
10540 LHSExpr = LHSExpr->IgnoreParenImpCasts();
10541 RHSExpr = RHSExpr->IgnoreParenImpCasts();
10542
10543 // Check for a call expression
10544 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
10545 if (!CE || CE->getNumArgs() != 1)
10546 return;
10547
10548 // Check for a call to std::move
10549 const FunctionDecl *FD = CE->getDirectCallee();
10550 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
10551 !FD->getIdentifier()->isStr("move"))
10552 return;
10553
10554 // Get argument from std::move
10555 RHSExpr = CE->getArg(0);
10556
10557 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10558 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10559
10560 // Two DeclRefExpr's, check that the decls are the same.
10561 if (LHSDeclRef && RHSDeclRef) {
10562 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10563 return;
10564 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10565 RHSDeclRef->getDecl()->getCanonicalDecl())
10566 return;
10567
10568 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10569 << LHSExpr->getSourceRange()
10570 << RHSExpr->getSourceRange();
10571 return;
10572 }
10573
10574 // Member variables require a different approach to check for self moves.
10575 // MemberExpr's are the same if every nested MemberExpr refers to the same
10576 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
10577 // the base Expr's are CXXThisExpr's.
10578 const Expr *LHSBase = LHSExpr;
10579 const Expr *RHSBase = RHSExpr;
10580 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
10581 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
10582 if (!LHSME || !RHSME)
10583 return;
10584
10585 while (LHSME && RHSME) {
10586 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
10587 RHSME->getMemberDecl()->getCanonicalDecl())
10588 return;
10589
10590 LHSBase = LHSME->getBase();
10591 RHSBase = RHSME->getBase();
10592 LHSME = dyn_cast<MemberExpr>(LHSBase);
10593 RHSME = dyn_cast<MemberExpr>(RHSBase);
10594 }
10595
10596 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
10597 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
10598 if (LHSDeclRef && RHSDeclRef) {
10599 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10600 return;
10601 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10602 RHSDeclRef->getDecl()->getCanonicalDecl())
10603 return;
10604
10605 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10606 << LHSExpr->getSourceRange()
10607 << RHSExpr->getSourceRange();
10608 return;
10609 }
10610
10611 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
10612 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10613 << LHSExpr->getSourceRange()
10614 << RHSExpr->getSourceRange();
10615}
10616
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010617//===--- Layout compatibility ----------------------------------------------//
10618
10619namespace {
10620
10621bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
10622
10623/// \brief Check if two enumeration types are layout-compatible.
10624bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
10625 // C++11 [dcl.enum] p8:
10626 // Two enumeration types are layout-compatible if they have the same
10627 // underlying type.
10628 return ED1->isComplete() && ED2->isComplete() &&
10629 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
10630}
10631
10632/// \brief Check if two fields are layout-compatible.
10633bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
10634 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
10635 return false;
10636
10637 if (Field1->isBitField() != Field2->isBitField())
10638 return false;
10639
10640 if (Field1->isBitField()) {
10641 // Make sure that the bit-fields are the same length.
10642 unsigned Bits1 = Field1->getBitWidthValue(C);
10643 unsigned Bits2 = Field2->getBitWidthValue(C);
10644
10645 if (Bits1 != Bits2)
10646 return false;
10647 }
10648
10649 return true;
10650}
10651
10652/// \brief Check if two standard-layout structs are layout-compatible.
10653/// (C++11 [class.mem] p17)
10654bool isLayoutCompatibleStruct(ASTContext &C,
10655 RecordDecl *RD1,
10656 RecordDecl *RD2) {
10657 // If both records are C++ classes, check that base classes match.
10658 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
10659 // If one of records is a CXXRecordDecl we are in C++ mode,
10660 // thus the other one is a CXXRecordDecl, too.
10661 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
10662 // Check number of base classes.
10663 if (D1CXX->getNumBases() != D2CXX->getNumBases())
10664 return false;
10665
10666 // Check the base classes.
10667 for (CXXRecordDecl::base_class_const_iterator
10668 Base1 = D1CXX->bases_begin(),
10669 BaseEnd1 = D1CXX->bases_end(),
10670 Base2 = D2CXX->bases_begin();
10671 Base1 != BaseEnd1;
10672 ++Base1, ++Base2) {
10673 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
10674 return false;
10675 }
10676 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
10677 // If only RD2 is a C++ class, it should have zero base classes.
10678 if (D2CXX->getNumBases() > 0)
10679 return false;
10680 }
10681
10682 // Check the fields.
10683 RecordDecl::field_iterator Field2 = RD2->field_begin(),
10684 Field2End = RD2->field_end(),
10685 Field1 = RD1->field_begin(),
10686 Field1End = RD1->field_end();
10687 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
10688 if (!isLayoutCompatible(C, *Field1, *Field2))
10689 return false;
10690 }
10691 if (Field1 != Field1End || Field2 != Field2End)
10692 return false;
10693
10694 return true;
10695}
10696
10697/// \brief Check if two standard-layout unions are layout-compatible.
10698/// (C++11 [class.mem] p18)
10699bool isLayoutCompatibleUnion(ASTContext &C,
10700 RecordDecl *RD1,
10701 RecordDecl *RD2) {
10702 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010703 for (auto *Field2 : RD2->fields())
10704 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010705
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010706 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010707 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
10708 I = UnmatchedFields.begin(),
10709 E = UnmatchedFields.end();
10710
10711 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010712 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010713 bool Result = UnmatchedFields.erase(*I);
10714 (void) Result;
10715 assert(Result);
10716 break;
10717 }
10718 }
10719 if (I == E)
10720 return false;
10721 }
10722
10723 return UnmatchedFields.empty();
10724}
10725
10726bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
10727 if (RD1->isUnion() != RD2->isUnion())
10728 return false;
10729
10730 if (RD1->isUnion())
10731 return isLayoutCompatibleUnion(C, RD1, RD2);
10732 else
10733 return isLayoutCompatibleStruct(C, RD1, RD2);
10734}
10735
10736/// \brief Check if two types are layout-compatible in C++11 sense.
10737bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
10738 if (T1.isNull() || T2.isNull())
10739 return false;
10740
10741 // C++11 [basic.types] p11:
10742 // If two types T1 and T2 are the same type, then T1 and T2 are
10743 // layout-compatible types.
10744 if (C.hasSameType(T1, T2))
10745 return true;
10746
10747 T1 = T1.getCanonicalType().getUnqualifiedType();
10748 T2 = T2.getCanonicalType().getUnqualifiedType();
10749
10750 const Type::TypeClass TC1 = T1->getTypeClass();
10751 const Type::TypeClass TC2 = T2->getTypeClass();
10752
10753 if (TC1 != TC2)
10754 return false;
10755
10756 if (TC1 == Type::Enum) {
10757 return isLayoutCompatible(C,
10758 cast<EnumType>(T1)->getDecl(),
10759 cast<EnumType>(T2)->getDecl());
10760 } else if (TC1 == Type::Record) {
10761 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
10762 return false;
10763
10764 return isLayoutCompatible(C,
10765 cast<RecordType>(T1)->getDecl(),
10766 cast<RecordType>(T2)->getDecl());
10767 }
10768
10769 return false;
10770}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010771} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010772
10773//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
10774
10775namespace {
10776/// \brief Given a type tag expression find the type tag itself.
10777///
10778/// \param TypeExpr Type tag expression, as it appears in user's code.
10779///
10780/// \param VD Declaration of an identifier that appears in a type tag.
10781///
10782/// \param MagicValue Type tag magic value.
10783bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
10784 const ValueDecl **VD, uint64_t *MagicValue) {
10785 while(true) {
10786 if (!TypeExpr)
10787 return false;
10788
10789 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
10790
10791 switch (TypeExpr->getStmtClass()) {
10792 case Stmt::UnaryOperatorClass: {
10793 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
10794 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
10795 TypeExpr = UO->getSubExpr();
10796 continue;
10797 }
10798 return false;
10799 }
10800
10801 case Stmt::DeclRefExprClass: {
10802 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
10803 *VD = DRE->getDecl();
10804 return true;
10805 }
10806
10807 case Stmt::IntegerLiteralClass: {
10808 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
10809 llvm::APInt MagicValueAPInt = IL->getValue();
10810 if (MagicValueAPInt.getActiveBits() <= 64) {
10811 *MagicValue = MagicValueAPInt.getZExtValue();
10812 return true;
10813 } else
10814 return false;
10815 }
10816
10817 case Stmt::BinaryConditionalOperatorClass:
10818 case Stmt::ConditionalOperatorClass: {
10819 const AbstractConditionalOperator *ACO =
10820 cast<AbstractConditionalOperator>(TypeExpr);
10821 bool Result;
10822 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
10823 if (Result)
10824 TypeExpr = ACO->getTrueExpr();
10825 else
10826 TypeExpr = ACO->getFalseExpr();
10827 continue;
10828 }
10829 return false;
10830 }
10831
10832 case Stmt::BinaryOperatorClass: {
10833 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
10834 if (BO->getOpcode() == BO_Comma) {
10835 TypeExpr = BO->getRHS();
10836 continue;
10837 }
10838 return false;
10839 }
10840
10841 default:
10842 return false;
10843 }
10844 }
10845}
10846
10847/// \brief Retrieve the C type corresponding to type tag TypeExpr.
10848///
10849/// \param TypeExpr Expression that specifies a type tag.
10850///
10851/// \param MagicValues Registered magic values.
10852///
10853/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
10854/// kind.
10855///
10856/// \param TypeInfo Information about the corresponding C type.
10857///
10858/// \returns true if the corresponding C type was found.
10859bool GetMatchingCType(
10860 const IdentifierInfo *ArgumentKind,
10861 const Expr *TypeExpr, const ASTContext &Ctx,
10862 const llvm::DenseMap<Sema::TypeTagMagicValue,
10863 Sema::TypeTagData> *MagicValues,
10864 bool &FoundWrongKind,
10865 Sema::TypeTagData &TypeInfo) {
10866 FoundWrongKind = false;
10867
10868 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000010869 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010870
10871 uint64_t MagicValue;
10872
10873 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
10874 return false;
10875
10876 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000010877 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010878 if (I->getArgumentKind() != ArgumentKind) {
10879 FoundWrongKind = true;
10880 return false;
10881 }
10882 TypeInfo.Type = I->getMatchingCType();
10883 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
10884 TypeInfo.MustBeNull = I->getMustBeNull();
10885 return true;
10886 }
10887 return false;
10888 }
10889
10890 if (!MagicValues)
10891 return false;
10892
10893 llvm::DenseMap<Sema::TypeTagMagicValue,
10894 Sema::TypeTagData>::const_iterator I =
10895 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
10896 if (I == MagicValues->end())
10897 return false;
10898
10899 TypeInfo = I->second;
10900 return true;
10901}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010902} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010903
10904void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10905 uint64_t MagicValue, QualType Type,
10906 bool LayoutCompatible,
10907 bool MustBeNull) {
10908 if (!TypeTagForDatatypeMagicValues)
10909 TypeTagForDatatypeMagicValues.reset(
10910 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
10911
10912 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
10913 (*TypeTagForDatatypeMagicValues)[Magic] =
10914 TypeTagData(Type, LayoutCompatible, MustBeNull);
10915}
10916
10917namespace {
10918bool IsSameCharType(QualType T1, QualType T2) {
10919 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
10920 if (!BT1)
10921 return false;
10922
10923 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
10924 if (!BT2)
10925 return false;
10926
10927 BuiltinType::Kind T1Kind = BT1->getKind();
10928 BuiltinType::Kind T2Kind = BT2->getKind();
10929
10930 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
10931 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
10932 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
10933 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
10934}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010935} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010936
10937void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10938 const Expr * const *ExprArgs) {
10939 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
10940 bool IsPointerAttr = Attr->getIsPointer();
10941
10942 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
10943 bool FoundWrongKind;
10944 TypeTagData TypeInfo;
10945 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
10946 TypeTagForDatatypeMagicValues.get(),
10947 FoundWrongKind, TypeInfo)) {
10948 if (FoundWrongKind)
10949 Diag(TypeTagExpr->getExprLoc(),
10950 diag::warn_type_tag_for_datatype_wrong_kind)
10951 << TypeTagExpr->getSourceRange();
10952 return;
10953 }
10954
10955 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
10956 if (IsPointerAttr) {
10957 // Skip implicit cast of pointer to `void *' (as a function argument).
10958 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000010959 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000010960 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010961 ArgumentExpr = ICE->getSubExpr();
10962 }
10963 QualType ArgumentType = ArgumentExpr->getType();
10964
10965 // Passing a `void*' pointer shouldn't trigger a warning.
10966 if (IsPointerAttr && ArgumentType->isVoidPointerType())
10967 return;
10968
10969 if (TypeInfo.MustBeNull) {
10970 // Type tag with matching void type requires a null pointer.
10971 if (!ArgumentExpr->isNullPointerConstant(Context,
10972 Expr::NPC_ValueDependentIsNotNull)) {
10973 Diag(ArgumentExpr->getExprLoc(),
10974 diag::warn_type_safety_null_pointer_required)
10975 << ArgumentKind->getName()
10976 << ArgumentExpr->getSourceRange()
10977 << TypeTagExpr->getSourceRange();
10978 }
10979 return;
10980 }
10981
10982 QualType RequiredType = TypeInfo.Type;
10983 if (IsPointerAttr)
10984 RequiredType = Context.getPointerType(RequiredType);
10985
10986 bool mismatch = false;
10987 if (!TypeInfo.LayoutCompatible) {
10988 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
10989
10990 // C++11 [basic.fundamental] p1:
10991 // Plain char, signed char, and unsigned char are three distinct types.
10992 //
10993 // But we treat plain `char' as equivalent to `signed char' or `unsigned
10994 // char' depending on the current char signedness mode.
10995 if (mismatch)
10996 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
10997 RequiredType->getPointeeType())) ||
10998 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
10999 mismatch = false;
11000 } else
11001 if (IsPointerAttr)
11002 mismatch = !isLayoutCompatible(Context,
11003 ArgumentType->getPointeeType(),
11004 RequiredType->getPointeeType());
11005 else
11006 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
11007
11008 if (mismatch)
11009 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000011010 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011011 << TypeInfo.LayoutCompatible << RequiredType
11012 << ArgumentExpr->getSourceRange()
11013 << TypeTagExpr->getSourceRange();
11014}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011015
11016void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11017 CharUnits Alignment) {
11018 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
11019}
11020
11021void Sema::DiagnoseMisalignedMembers() {
11022 for (MisalignedMember &m : MisalignedMembers) {
11023 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
11024 << m.MD << m.RD << m.E->getSourceRange();
11025 }
11026 MisalignedMembers.clear();
11027}
11028
11029void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
11030 if (!T->isPointerType())
11031 return;
11032 if (isa<UnaryOperator>(E) &&
11033 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
11034 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11035 if (isa<MemberExpr>(Op)) {
11036 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
11037 MisalignedMember(Op));
11038 if (MA != MisalignedMembers.end() &&
11039 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)
11040 MisalignedMembers.erase(MA);
11041 }
11042 }
11043}
11044
11045void Sema::RefersToMemberWithReducedAlignment(
11046 Expr *E,
11047 std::function<void(Expr *, RecordDecl *, ValueDecl *, CharUnits)> Action) {
11048 const auto *ME = dyn_cast<MemberExpr>(E);
11049 while (ME && isa<FieldDecl>(ME->getMemberDecl())) {
11050 QualType BaseType = ME->getBase()->getType();
11051 if (ME->isArrow())
11052 BaseType = BaseType->getPointeeType();
11053 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
11054
11055 ValueDecl *MD = ME->getMemberDecl();
11056 bool ByteAligned = Context.getTypeAlignInChars(MD->getType()).isOne();
11057 if (ByteAligned) // Attribute packed does not have any effect.
11058 break;
11059
11060 if (!ByteAligned &&
11061 (RD->hasAttr<PackedAttr>() || (MD->hasAttr<PackedAttr>()))) {
11062 CharUnits Alignment = std::min(Context.getTypeAlignInChars(MD->getType()),
11063 Context.getTypeAlignInChars(BaseType));
11064 // Notify that this expression designates a member with reduced alignment
11065 Action(E, RD, MD, Alignment);
11066 break;
11067 }
11068 ME = dyn_cast<MemberExpr>(ME->getBase());
11069 }
11070}
11071
11072void Sema::CheckAddressOfPackedMember(Expr *rhs) {
11073 using namespace std::placeholders;
11074 RefersToMemberWithReducedAlignment(
11075 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
11076 _2, _3, _4));
11077}
11078