blob: c1db062f35dd8b8ffae8d9566c04fd8faf70cd8b [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
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000318/// Diagnose integer type and any valid implicit convertion to it.
319static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
320 const QualType &IntType);
321
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000322static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000323 unsigned Start, unsigned End) {
324 bool IllegalParams = false;
325 for (unsigned I = Start; I <= End; ++I)
326 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
327 S.Context.getSizeType());
328 return IllegalParams;
329}
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000330
331/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
332/// 'local void*' parameter of passed block.
333static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
334 Expr *BlockArg,
335 unsigned NumNonVarArgs) {
336 const BlockPointerType *BPT =
337 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
338 unsigned NumBlockParams =
339 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
340 unsigned TotalNumArgs = TheCall->getNumArgs();
341
342 // For each argument passed to the block, a corresponding uint needs to
343 // be passed to describe the size of the local memory.
344 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
345 S.Diag(TheCall->getLocStart(),
346 diag::err_opencl_enqueue_kernel_local_size_args);
347 return true;
348 }
349
350 // Check that the sizes of the local memory are specified by integers.
351 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
352 TotalNumArgs - 1);
353}
354
355/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
356/// overload formats specified in Table 6.13.17.1.
357/// int enqueue_kernel(queue_t queue,
358/// kernel_enqueue_flags_t flags,
359/// const ndrange_t ndrange,
360/// void (^block)(void))
361/// int enqueue_kernel(queue_t queue,
362/// kernel_enqueue_flags_t flags,
363/// const ndrange_t ndrange,
364/// uint num_events_in_wait_list,
365/// clk_event_t *event_wait_list,
366/// clk_event_t *event_ret,
367/// void (^block)(void))
368/// int enqueue_kernel(queue_t queue,
369/// kernel_enqueue_flags_t flags,
370/// const ndrange_t ndrange,
371/// void (^block)(local void*, ...),
372/// uint size0, ...)
373/// int enqueue_kernel(queue_t queue,
374/// kernel_enqueue_flags_t flags,
375/// const ndrange_t ndrange,
376/// uint num_events_in_wait_list,
377/// clk_event_t *event_wait_list,
378/// clk_event_t *event_ret,
379/// void (^block)(local void*, ...),
380/// uint size0, ...)
381static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
382 unsigned NumArgs = TheCall->getNumArgs();
383
384 if (NumArgs < 4) {
385 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
386 return true;
387 }
388
389 Expr *Arg0 = TheCall->getArg(0);
390 Expr *Arg1 = TheCall->getArg(1);
391 Expr *Arg2 = TheCall->getArg(2);
392 Expr *Arg3 = TheCall->getArg(3);
393
394 // First argument always needs to be a queue_t type.
395 if (!Arg0->getType()->isQueueT()) {
396 S.Diag(TheCall->getArg(0)->getLocStart(),
397 diag::err_opencl_enqueue_kernel_expected_type)
398 << S.Context.OCLQueueTy;
399 return true;
400 }
401
402 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
403 if (!Arg1->getType()->isIntegerType()) {
404 S.Diag(TheCall->getArg(1)->getLocStart(),
405 diag::err_opencl_enqueue_kernel_expected_type)
406 << "'kernel_enqueue_flags_t' (i.e. uint)";
407 return true;
408 }
409
410 // Third argument is always an ndrange_t type.
411 if (!Arg2->getType()->isNDRangeT()) {
412 S.Diag(TheCall->getArg(2)->getLocStart(),
413 diag::err_opencl_enqueue_kernel_expected_type)
414 << S.Context.OCLNDRangeTy;
415 return true;
416 }
417
418 // With four arguments, there is only one form that the function could be
419 // called in: no events and no variable arguments.
420 if (NumArgs == 4) {
421 // check that the last argument is the right block type.
422 if (!isBlockPointer(Arg3)) {
423 S.Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
424 << "block";
425 return true;
426 }
427 // we have a block type, check the prototype
428 const BlockPointerType *BPT =
429 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
430 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
431 S.Diag(Arg3->getLocStart(),
432 diag::err_opencl_enqueue_kernel_blocks_no_args);
433 return true;
434 }
435 return false;
436 }
437 // we can have block + varargs.
438 if (isBlockPointer(Arg3))
439 return (checkOpenCLBlockArgs(S, Arg3) ||
440 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
441 // last two cases with either exactly 7 args or 7 args and varargs.
442 if (NumArgs >= 7) {
443 // check common block argument.
444 Expr *Arg6 = TheCall->getArg(6);
445 if (!isBlockPointer(Arg6)) {
446 S.Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
447 << "block";
448 return true;
449 }
450 if (checkOpenCLBlockArgs(S, Arg6))
451 return true;
452
453 // Forth argument has to be any integer type.
454 if (!Arg3->getType()->isIntegerType()) {
455 S.Diag(TheCall->getArg(3)->getLocStart(),
456 diag::err_opencl_enqueue_kernel_expected_type)
457 << "integer";
458 return true;
459 }
460 // check remaining common arguments.
461 Expr *Arg4 = TheCall->getArg(4);
462 Expr *Arg5 = TheCall->getArg(5);
463
Anastasia Stulova2b461202016-11-14 15:34:01 +0000464 // Fifth argument is always passed as a pointer to clk_event_t.
465 if (!Arg4->isNullPointerConstant(S.Context,
466 Expr::NPC_ValueDependentIsNotNull) &&
467 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000468 S.Diag(TheCall->getArg(4)->getLocStart(),
469 diag::err_opencl_enqueue_kernel_expected_type)
470 << S.Context.getPointerType(S.Context.OCLClkEventTy);
471 return true;
472 }
473
Anastasia Stulova2b461202016-11-14 15:34:01 +0000474 // Sixth argument is always passed as a pointer to clk_event_t.
475 if (!Arg5->isNullPointerConstant(S.Context,
476 Expr::NPC_ValueDependentIsNotNull) &&
477 !(Arg5->getType()->isPointerType() &&
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000478 Arg5->getType()->getPointeeType()->isClkEventT())) {
479 S.Diag(TheCall->getArg(5)->getLocStart(),
480 diag::err_opencl_enqueue_kernel_expected_type)
481 << S.Context.getPointerType(S.Context.OCLClkEventTy);
482 return true;
483 }
484
485 if (NumArgs == 7)
486 return false;
487
488 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
489 }
490
491 // None of the specific case has been detected, give generic error
492 S.Diag(TheCall->getLocStart(),
493 diag::err_opencl_enqueue_kernel_incorrect_args);
494 return true;
495}
496
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000497/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000498static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000499 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000500}
501
502/// Returns true if pipe element type is different from the pointer.
503static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
504 const Expr *Arg0 = Call->getArg(0);
505 // First argument type should always be pipe.
506 if (!Arg0->getType()->isPipeType()) {
507 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000508 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000509 return true;
510 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000511 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000512 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
513 // Validates the access qualifier is compatible with the call.
514 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
515 // read_only and write_only, and assumed to be read_only if no qualifier is
516 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000517 switch (Call->getDirectCallee()->getBuiltinID()) {
518 case Builtin::BIread_pipe:
519 case Builtin::BIreserve_read_pipe:
520 case Builtin::BIcommit_read_pipe:
521 case Builtin::BIwork_group_reserve_read_pipe:
522 case Builtin::BIsub_group_reserve_read_pipe:
523 case Builtin::BIwork_group_commit_read_pipe:
524 case Builtin::BIsub_group_commit_read_pipe:
525 if (!(!AccessQual || AccessQual->isReadOnly())) {
526 S.Diag(Arg0->getLocStart(),
527 diag::err_opencl_builtin_pipe_invalid_access_modifier)
528 << "read_only" << Arg0->getSourceRange();
529 return true;
530 }
531 break;
532 case Builtin::BIwrite_pipe:
533 case Builtin::BIreserve_write_pipe:
534 case Builtin::BIcommit_write_pipe:
535 case Builtin::BIwork_group_reserve_write_pipe:
536 case Builtin::BIsub_group_reserve_write_pipe:
537 case Builtin::BIwork_group_commit_write_pipe:
538 case Builtin::BIsub_group_commit_write_pipe:
539 if (!(AccessQual && AccessQual->isWriteOnly())) {
540 S.Diag(Arg0->getLocStart(),
541 diag::err_opencl_builtin_pipe_invalid_access_modifier)
542 << "write_only" << Arg0->getSourceRange();
543 return true;
544 }
545 break;
546 default:
547 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000548 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000549 return false;
550}
551
552/// Returns true if pipe element type is different from the pointer.
553static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
554 const Expr *Arg0 = Call->getArg(0);
555 const Expr *ArgIdx = Call->getArg(Idx);
556 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000557 const QualType EltTy = PipeTy->getElementType();
558 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000559 // The Idx argument should be a pointer and the type of the pointer and
560 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000561 if (!ArgTy ||
562 !S.Context.hasSameType(
563 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000564 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000565 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000566 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000567 return true;
568 }
569 return false;
570}
571
572// \brief Performs semantic analysis for the read/write_pipe call.
573// \param S Reference to the semantic analyzer.
574// \param Call A pointer to the builtin call.
575// \return True if a semantic error has been found, false otherwise.
576static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000577 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
578 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000579 switch (Call->getNumArgs()) {
580 case 2: {
581 if (checkOpenCLPipeArg(S, Call))
582 return true;
583 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000584 // read/write_pipe(pipe T, T*).
585 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000586 if (checkOpenCLPipePacketType(S, Call, 1))
587 return true;
588 } break;
589
590 case 4: {
591 if (checkOpenCLPipeArg(S, Call))
592 return true;
593 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000594 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
595 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000596 if (!Call->getArg(1)->getType()->isReserveIDT()) {
597 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000598 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000599 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000600 return true;
601 }
602
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000603 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000604 const Expr *Arg2 = Call->getArg(2);
605 if (!Arg2->getType()->isIntegerType() &&
606 !Arg2->getType()->isUnsignedIntegerType()) {
607 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000608 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000609 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000610 return true;
611 }
612
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000613 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000614 if (checkOpenCLPipePacketType(S, Call, 3))
615 return true;
616 } break;
617 default:
618 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000619 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000620 return true;
621 }
622
623 return false;
624}
625
626// \brief Performs a semantic analysis on the {work_group_/sub_group_
627// /_}reserve_{read/write}_pipe
628// \param S Reference to the semantic analyzer.
629// \param Call The call to the builtin function to be analyzed.
630// \return True if a semantic error was found, false otherwise.
631static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
632 if (checkArgCount(S, Call, 2))
633 return true;
634
635 if (checkOpenCLPipeArg(S, Call))
636 return true;
637
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000638 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000639 if (!Call->getArg(1)->getType()->isIntegerType() &&
640 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
641 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000642 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000643 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000644 return true;
645 }
646
647 return false;
648}
649
650// \brief Performs a semantic analysis on {work_group_/sub_group_
651// /_}commit_{read/write}_pipe
652// \param S Reference to the semantic analyzer.
653// \param Call The call to the builtin function to be analyzed.
654// \return True if a semantic error was found, false otherwise.
655static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
656 if (checkArgCount(S, Call, 2))
657 return true;
658
659 if (checkOpenCLPipeArg(S, Call))
660 return true;
661
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000662 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000663 if (!Call->getArg(1)->getType()->isReserveIDT()) {
664 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000665 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000666 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000667 return true;
668 }
669
670 return false;
671}
672
673// \brief Performs a semantic analysis on the call to built-in Pipe
674// Query Functions.
675// \param S Reference to the semantic analyzer.
676// \param Call The call to the builtin function to be analyzed.
677// \return True if a semantic error was found, false otherwise.
678static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
679 if (checkArgCount(S, Call, 1))
680 return true;
681
682 if (!Call->getArg(0)->getType()->isPipeType()) {
683 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000684 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000685 return true;
686 }
687
688 return false;
689}
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +0000690// \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
Yaxun Liuf7449a12016-05-20 19:54:38 +0000691// \brief Performs semantic analysis for the to_global/local/private call.
692// \param S Reference to the semantic analyzer.
693// \param BuiltinID ID of the builtin function.
694// \param Call A pointer to the builtin call.
695// \return True if a semantic error has been found, false otherwise.
696static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
697 CallExpr *Call) {
Yaxun Liuf7449a12016-05-20 19:54:38 +0000698 if (Call->getNumArgs() != 1) {
699 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
700 << Call->getDirectCallee() << Call->getSourceRange();
701 return true;
702 }
703
704 auto RT = Call->getArg(0)->getType();
705 if (!RT->isPointerType() || RT->getPointeeType()
706 .getAddressSpace() == LangAS::opencl_constant) {
707 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
708 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
709 return true;
710 }
711
712 RT = RT->getPointeeType();
713 auto Qual = RT.getQualifiers();
714 switch (BuiltinID) {
715 case Builtin::BIto_global:
716 Qual.setAddressSpace(LangAS::opencl_global);
717 break;
718 case Builtin::BIto_local:
719 Qual.setAddressSpace(LangAS::opencl_local);
720 break;
721 default:
722 Qual.removeAddressSpace();
723 }
724 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
725 RT.getUnqualifiedType(), Qual)));
726
727 return false;
728}
729
John McCalldadc5752010-08-24 06:29:42 +0000730ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000731Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
732 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000733 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000734
Chris Lattner3be167f2010-10-01 23:23:24 +0000735 // Find out if any arguments are required to be integer constant expressions.
736 unsigned ICEArguments = 0;
737 ASTContext::GetBuiltinTypeError Error;
738 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
739 if (Error != ASTContext::GE_None)
740 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
741
742 // If any arguments are required to be ICE's, check and diagnose.
743 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
744 // Skip arguments not required to be ICE's.
745 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
746
747 llvm::APSInt Result;
748 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
749 return true;
750 ICEArguments &= ~(1 << ArgNo);
751 }
752
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000753 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000754 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000755 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000756 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000757 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000758 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000759 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000760 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000761 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000762 if (SemaBuiltinVAStart(TheCall))
763 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000764 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000765 case Builtin::BI__va_start: {
766 switch (Context.getTargetInfo().getTriple().getArch()) {
767 case llvm::Triple::arm:
768 case llvm::Triple::thumb:
769 if (SemaBuiltinVAStartARM(TheCall))
770 return ExprError();
771 break;
772 default:
773 if (SemaBuiltinVAStart(TheCall))
774 return ExprError();
775 break;
776 }
777 break;
778 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000779 case Builtin::BI__builtin_isgreater:
780 case Builtin::BI__builtin_isgreaterequal:
781 case Builtin::BI__builtin_isless:
782 case Builtin::BI__builtin_islessequal:
783 case Builtin::BI__builtin_islessgreater:
784 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000785 if (SemaBuiltinUnorderedCompare(TheCall))
786 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000787 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000788 case Builtin::BI__builtin_fpclassify:
789 if (SemaBuiltinFPClassification(TheCall, 6))
790 return ExprError();
791 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000792 case Builtin::BI__builtin_isfinite:
793 case Builtin::BI__builtin_isinf:
794 case Builtin::BI__builtin_isinf_sign:
795 case Builtin::BI__builtin_isnan:
796 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000797 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000798 return ExprError();
799 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000800 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000801 return SemaBuiltinShuffleVector(TheCall);
802 // TheCall will be freed by the smart pointer here, but that's fine, since
803 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000804 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000805 if (SemaBuiltinPrefetch(TheCall))
806 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000807 break;
David Majnemer51169932016-10-31 05:37:48 +0000808 case Builtin::BI__builtin_alloca_with_align:
809 if (SemaBuiltinAllocaWithAlign(TheCall))
810 return ExprError();
811 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000812 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000813 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000814 if (SemaBuiltinAssume(TheCall))
815 return ExprError();
816 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000817 case Builtin::BI__builtin_assume_aligned:
818 if (SemaBuiltinAssumeAligned(TheCall))
819 return ExprError();
820 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000821 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000822 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000823 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000824 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000825 case Builtin::BI__builtin_longjmp:
826 if (SemaBuiltinLongjmp(TheCall))
827 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000828 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000829 case Builtin::BI__builtin_setjmp:
830 if (SemaBuiltinSetjmp(TheCall))
831 return ExprError();
832 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000833 case Builtin::BI_setjmp:
834 case Builtin::BI_setjmpex:
835 if (checkArgCount(*this, TheCall, 1))
836 return true;
837 break;
John McCallbebede42011-02-26 05:39:39 +0000838
839 case Builtin::BI__builtin_classify_type:
840 if (checkArgCount(*this, TheCall, 1)) return true;
841 TheCall->setType(Context.IntTy);
842 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000843 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000844 if (checkArgCount(*this, TheCall, 1)) return true;
845 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000846 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000847 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000848 case Builtin::BI__sync_fetch_and_add_1:
849 case Builtin::BI__sync_fetch_and_add_2:
850 case Builtin::BI__sync_fetch_and_add_4:
851 case Builtin::BI__sync_fetch_and_add_8:
852 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000853 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000854 case Builtin::BI__sync_fetch_and_sub_1:
855 case Builtin::BI__sync_fetch_and_sub_2:
856 case Builtin::BI__sync_fetch_and_sub_4:
857 case Builtin::BI__sync_fetch_and_sub_8:
858 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000859 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000860 case Builtin::BI__sync_fetch_and_or_1:
861 case Builtin::BI__sync_fetch_and_or_2:
862 case Builtin::BI__sync_fetch_and_or_4:
863 case Builtin::BI__sync_fetch_and_or_8:
864 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000865 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000866 case Builtin::BI__sync_fetch_and_and_1:
867 case Builtin::BI__sync_fetch_and_and_2:
868 case Builtin::BI__sync_fetch_and_and_4:
869 case Builtin::BI__sync_fetch_and_and_8:
870 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000871 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000872 case Builtin::BI__sync_fetch_and_xor_1:
873 case Builtin::BI__sync_fetch_and_xor_2:
874 case Builtin::BI__sync_fetch_and_xor_4:
875 case Builtin::BI__sync_fetch_and_xor_8:
876 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000877 case Builtin::BI__sync_fetch_and_nand:
878 case Builtin::BI__sync_fetch_and_nand_1:
879 case Builtin::BI__sync_fetch_and_nand_2:
880 case Builtin::BI__sync_fetch_and_nand_4:
881 case Builtin::BI__sync_fetch_and_nand_8:
882 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000883 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000884 case Builtin::BI__sync_add_and_fetch_1:
885 case Builtin::BI__sync_add_and_fetch_2:
886 case Builtin::BI__sync_add_and_fetch_4:
887 case Builtin::BI__sync_add_and_fetch_8:
888 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000889 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000890 case Builtin::BI__sync_sub_and_fetch_1:
891 case Builtin::BI__sync_sub_and_fetch_2:
892 case Builtin::BI__sync_sub_and_fetch_4:
893 case Builtin::BI__sync_sub_and_fetch_8:
894 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000895 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000896 case Builtin::BI__sync_and_and_fetch_1:
897 case Builtin::BI__sync_and_and_fetch_2:
898 case Builtin::BI__sync_and_and_fetch_4:
899 case Builtin::BI__sync_and_and_fetch_8:
900 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000901 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000902 case Builtin::BI__sync_or_and_fetch_1:
903 case Builtin::BI__sync_or_and_fetch_2:
904 case Builtin::BI__sync_or_and_fetch_4:
905 case Builtin::BI__sync_or_and_fetch_8:
906 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000907 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000908 case Builtin::BI__sync_xor_and_fetch_1:
909 case Builtin::BI__sync_xor_and_fetch_2:
910 case Builtin::BI__sync_xor_and_fetch_4:
911 case Builtin::BI__sync_xor_and_fetch_8:
912 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000913 case Builtin::BI__sync_nand_and_fetch:
914 case Builtin::BI__sync_nand_and_fetch_1:
915 case Builtin::BI__sync_nand_and_fetch_2:
916 case Builtin::BI__sync_nand_and_fetch_4:
917 case Builtin::BI__sync_nand_and_fetch_8:
918 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000919 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000920 case Builtin::BI__sync_val_compare_and_swap_1:
921 case Builtin::BI__sync_val_compare_and_swap_2:
922 case Builtin::BI__sync_val_compare_and_swap_4:
923 case Builtin::BI__sync_val_compare_and_swap_8:
924 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000925 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000926 case Builtin::BI__sync_bool_compare_and_swap_1:
927 case Builtin::BI__sync_bool_compare_and_swap_2:
928 case Builtin::BI__sync_bool_compare_and_swap_4:
929 case Builtin::BI__sync_bool_compare_and_swap_8:
930 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000931 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000932 case Builtin::BI__sync_lock_test_and_set_1:
933 case Builtin::BI__sync_lock_test_and_set_2:
934 case Builtin::BI__sync_lock_test_and_set_4:
935 case Builtin::BI__sync_lock_test_and_set_8:
936 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000937 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000938 case Builtin::BI__sync_lock_release_1:
939 case Builtin::BI__sync_lock_release_2:
940 case Builtin::BI__sync_lock_release_4:
941 case Builtin::BI__sync_lock_release_8:
942 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000943 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000944 case Builtin::BI__sync_swap_1:
945 case Builtin::BI__sync_swap_2:
946 case Builtin::BI__sync_swap_4:
947 case Builtin::BI__sync_swap_8:
948 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000949 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000950 case Builtin::BI__builtin_nontemporal_load:
951 case Builtin::BI__builtin_nontemporal_store:
952 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000953#define BUILTIN(ID, TYPE, ATTRS)
954#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
955 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000956 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000957#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000958 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000959 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000960 return ExprError();
961 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000962 case Builtin::BI__builtin_addressof:
963 if (SemaBuiltinAddressof(*this, TheCall))
964 return ExprError();
965 break;
John McCall03107a42015-10-29 20:48:01 +0000966 case Builtin::BI__builtin_add_overflow:
967 case Builtin::BI__builtin_sub_overflow:
968 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +0000969 if (SemaBuiltinOverflow(*this, TheCall))
970 return ExprError();
971 break;
Richard Smith760520b2014-06-03 23:27:44 +0000972 case Builtin::BI__builtin_operator_new:
973 case Builtin::BI__builtin_operator_delete:
974 if (!getLangOpts().CPlusPlus) {
975 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
976 << (BuiltinID == Builtin::BI__builtin_operator_new
977 ? "__builtin_operator_new"
978 : "__builtin_operator_delete")
979 << "C++";
980 return ExprError();
981 }
982 // CodeGen assumes it can find the global new and delete to call,
983 // so ensure that they are declared.
984 DeclareGlobalNewDelete();
985 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000986
987 // check secure string manipulation functions where overflows
988 // are detectable at compile time
989 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000990 case Builtin::BI__builtin___memmove_chk:
991 case Builtin::BI__builtin___memset_chk:
992 case Builtin::BI__builtin___strlcat_chk:
993 case Builtin::BI__builtin___strlcpy_chk:
994 case Builtin::BI__builtin___strncat_chk:
995 case Builtin::BI__builtin___strncpy_chk:
996 case Builtin::BI__builtin___stpncpy_chk:
997 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
998 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000999 case Builtin::BI__builtin___memccpy_chk:
1000 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1001 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001002 case Builtin::BI__builtin___snprintf_chk:
1003 case Builtin::BI__builtin___vsnprintf_chk:
1004 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1005 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001006 case Builtin::BI__builtin_call_with_static_chain:
1007 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1008 return ExprError();
1009 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001010 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001011 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001012 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1013 diag::err_seh___except_block))
1014 return ExprError();
1015 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001016 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001017 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001018 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1019 diag::err_seh___except_filter))
1020 return ExprError();
1021 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001022 case Builtin::BI__GetExceptionInfo:
1023 if (checkArgCount(*this, TheCall, 1))
1024 return ExprError();
1025
1026 if (CheckCXXThrowOperand(
1027 TheCall->getLocStart(),
1028 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1029 TheCall))
1030 return ExprError();
1031
1032 TheCall->setType(Context.VoidPtrTy);
1033 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001034 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001035 case Builtin::BIread_pipe:
1036 case Builtin::BIwrite_pipe:
1037 // Since those two functions are declared with var args, we need a semantic
1038 // check for the argument.
1039 if (SemaBuiltinRWPipe(*this, TheCall))
1040 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001041 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001042 break;
1043 case Builtin::BIreserve_read_pipe:
1044 case Builtin::BIreserve_write_pipe:
1045 case Builtin::BIwork_group_reserve_read_pipe:
1046 case Builtin::BIwork_group_reserve_write_pipe:
1047 case Builtin::BIsub_group_reserve_read_pipe:
1048 case Builtin::BIsub_group_reserve_write_pipe:
1049 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1050 return ExprError();
1051 // Since return type of reserve_read/write_pipe built-in function is
1052 // reserve_id_t, which is not defined in the builtin def file , we used int
1053 // as return type and need to override the return type of these functions.
1054 TheCall->setType(Context.OCLReserveIDTy);
1055 break;
1056 case Builtin::BIcommit_read_pipe:
1057 case Builtin::BIcommit_write_pipe:
1058 case Builtin::BIwork_group_commit_read_pipe:
1059 case Builtin::BIwork_group_commit_write_pipe:
1060 case Builtin::BIsub_group_commit_read_pipe:
1061 case Builtin::BIsub_group_commit_write_pipe:
1062 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1063 return ExprError();
1064 break;
1065 case Builtin::BIget_pipe_num_packets:
1066 case Builtin::BIget_pipe_max_packets:
1067 if (SemaBuiltinPipePackets(*this, TheCall))
1068 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001069 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001070 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001071 case Builtin::BIto_global:
1072 case Builtin::BIto_local:
1073 case Builtin::BIto_private:
1074 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1075 return ExprError();
1076 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001077 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1078 case Builtin::BIenqueue_kernel:
1079 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1080 return ExprError();
1081 break;
1082 case Builtin::BIget_kernel_work_group_size:
1083 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1084 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1085 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001086 break;
1087 case Builtin::BI__builtin_os_log_format:
1088 case Builtin::BI__builtin_os_log_format_buffer_size:
1089 if (SemaBuiltinOSLogFormat(TheCall)) {
1090 return ExprError();
1091 }
1092 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001093 }
Richard Smith760520b2014-06-03 23:27:44 +00001094
Nate Begeman4904e322010-06-08 02:47:44 +00001095 // Since the target specific builtins for each arch overlap, only check those
1096 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001097 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001098 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001099 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001100 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001101 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001102 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001103 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1104 return ExprError();
1105 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001106 case llvm::Triple::aarch64:
1107 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001108 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001109 return ExprError();
1110 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001111 case llvm::Triple::mips:
1112 case llvm::Triple::mipsel:
1113 case llvm::Triple::mips64:
1114 case llvm::Triple::mips64el:
1115 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1116 return ExprError();
1117 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001118 case llvm::Triple::systemz:
1119 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1120 return ExprError();
1121 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001122 case llvm::Triple::x86:
1123 case llvm::Triple::x86_64:
1124 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1125 return ExprError();
1126 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001127 case llvm::Triple::ppc:
1128 case llvm::Triple::ppc64:
1129 case llvm::Triple::ppc64le:
1130 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1131 return ExprError();
1132 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001133 default:
1134 break;
1135 }
1136 }
1137
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001138 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001139}
1140
Nate Begeman91e1fea2010-06-14 05:21:25 +00001141// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001142static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001143 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001144 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001145 switch (Type.getEltType()) {
1146 case NeonTypeFlags::Int8:
1147 case NeonTypeFlags::Poly8:
1148 return shift ? 7 : (8 << IsQuad) - 1;
1149 case NeonTypeFlags::Int16:
1150 case NeonTypeFlags::Poly16:
1151 return shift ? 15 : (4 << IsQuad) - 1;
1152 case NeonTypeFlags::Int32:
1153 return shift ? 31 : (2 << IsQuad) - 1;
1154 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001155 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001156 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001157 case NeonTypeFlags::Poly128:
1158 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001159 case NeonTypeFlags::Float16:
1160 assert(!shift && "cannot shift float types!");
1161 return (4 << IsQuad) - 1;
1162 case NeonTypeFlags::Float32:
1163 assert(!shift && "cannot shift float types!");
1164 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001165 case NeonTypeFlags::Float64:
1166 assert(!shift && "cannot shift float types!");
1167 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001168 }
David Blaikie8a40f702012-01-17 06:56:22 +00001169 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001170}
1171
Bob Wilsone4d77232011-11-08 05:04:11 +00001172/// getNeonEltType - Return the QualType corresponding to the elements of
1173/// the vector type specified by the NeonTypeFlags. This is used to check
1174/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001175static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001176 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001177 switch (Flags.getEltType()) {
1178 case NeonTypeFlags::Int8:
1179 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1180 case NeonTypeFlags::Int16:
1181 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1182 case NeonTypeFlags::Int32:
1183 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1184 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001185 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001186 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1187 else
1188 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1189 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001190 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001191 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001192 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001193 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001194 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001195 if (IsInt64Long)
1196 return Context.UnsignedLongTy;
1197 else
1198 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001199 case NeonTypeFlags::Poly128:
1200 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001201 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001202 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001203 case NeonTypeFlags::Float32:
1204 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001205 case NeonTypeFlags::Float64:
1206 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001207 }
David Blaikie8a40f702012-01-17 06:56:22 +00001208 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001209}
1210
Tim Northover12670412014-02-19 10:37:05 +00001211bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001212 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001213 uint64_t mask = 0;
1214 unsigned TV = 0;
1215 int PtrArgNum = -1;
1216 bool HasConstPtr = false;
1217 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001218#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001219#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001220#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001221 }
1222
1223 // For NEON intrinsics which are overloaded on vector element type, validate
1224 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001225 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001226 if (mask) {
1227 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1228 return true;
1229
1230 TV = Result.getLimitedValue(64);
1231 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1232 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001233 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001234 }
1235
1236 if (PtrArgNum >= 0) {
1237 // Check that pointer arguments have the specified type.
1238 Expr *Arg = TheCall->getArg(PtrArgNum);
1239 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1240 Arg = ICE->getSubExpr();
1241 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1242 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001243
Tim Northovera2ee4332014-03-29 15:09:45 +00001244 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +00001245 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +00001246 bool IsInt64Long =
1247 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1248 QualType EltTy =
1249 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001250 if (HasConstPtr)
1251 EltTy = EltTy.withConst();
1252 QualType LHSTy = Context.getPointerType(EltTy);
1253 AssignConvertType ConvTy;
1254 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1255 if (RHS.isInvalid())
1256 return true;
1257 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1258 RHS.get(), AA_Assigning))
1259 return true;
1260 }
1261
1262 // For NEON intrinsics which take an immediate value as part of the
1263 // instruction, range check them here.
1264 unsigned i = 0, l = 0, u = 0;
1265 switch (BuiltinID) {
1266 default:
1267 return false;
Tim Northover12670412014-02-19 10:37:05 +00001268#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001269#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001270#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001271 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001272
Richard Sandiford28940af2014-04-16 08:47:51 +00001273 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001274}
1275
Tim Northovera2ee4332014-03-29 15:09:45 +00001276bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1277 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001278 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001279 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001280 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001281 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001282 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001283 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1284 BuiltinID == AArch64::BI__builtin_arm_strex ||
1285 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001286 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001287 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001288 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1289 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1290 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001291
1292 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1293
1294 // Ensure that we have the proper number of arguments.
1295 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1296 return true;
1297
1298 // Inspect the pointer argument of the atomic builtin. This should always be
1299 // a pointer type, whose element is an integral scalar or pointer type.
1300 // Because it is a pointer type, we don't have to worry about any implicit
1301 // casts here.
1302 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1303 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1304 if (PointerArgRes.isInvalid())
1305 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001306 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001307
1308 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1309 if (!pointerType) {
1310 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1311 << PointerArg->getType() << PointerArg->getSourceRange();
1312 return true;
1313 }
1314
1315 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1316 // task is to insert the appropriate casts into the AST. First work out just
1317 // what the appropriate type is.
1318 QualType ValType = pointerType->getPointeeType();
1319 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1320 if (IsLdrex)
1321 AddrType.addConst();
1322
1323 // Issue a warning if the cast is dodgy.
1324 CastKind CastNeeded = CK_NoOp;
1325 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1326 CastNeeded = CK_BitCast;
1327 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1328 << PointerArg->getType()
1329 << Context.getPointerType(AddrType)
1330 << AA_Passing << PointerArg->getSourceRange();
1331 }
1332
1333 // Finally, do the cast and replace the argument with the corrected version.
1334 AddrType = Context.getPointerType(AddrType);
1335 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1336 if (PointerArgRes.isInvalid())
1337 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001338 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001339
1340 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1341
1342 // In general, we allow ints, floats and pointers to be loaded and stored.
1343 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1344 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1345 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1346 << PointerArg->getType() << PointerArg->getSourceRange();
1347 return true;
1348 }
1349
1350 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001351 if (Context.getTypeSize(ValType) > MaxWidth) {
1352 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001353 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1354 << PointerArg->getType() << PointerArg->getSourceRange();
1355 return true;
1356 }
1357
1358 switch (ValType.getObjCLifetime()) {
1359 case Qualifiers::OCL_None:
1360 case Qualifiers::OCL_ExplicitNone:
1361 // okay
1362 break;
1363
1364 case Qualifiers::OCL_Weak:
1365 case Qualifiers::OCL_Strong:
1366 case Qualifiers::OCL_Autoreleasing:
1367 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1368 << ValType << PointerArg->getSourceRange();
1369 return true;
1370 }
1371
Tim Northover6aacd492013-07-16 09:47:53 +00001372 if (IsLdrex) {
1373 TheCall->setType(ValType);
1374 return false;
1375 }
1376
1377 // Initialize the argument to be stored.
1378 ExprResult ValArg = TheCall->getArg(0);
1379 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1380 Context, ValType, /*consume*/ false);
1381 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1382 if (ValArg.isInvalid())
1383 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001384 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001385
1386 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1387 // but the custom checker bypasses all default analysis.
1388 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001389 return false;
1390}
1391
Nate Begeman4904e322010-06-08 02:47:44 +00001392bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +00001393 llvm::APSInt Result;
1394
Tim Northover6aacd492013-07-16 09:47:53 +00001395 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001396 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1397 BuiltinID == ARM::BI__builtin_arm_strex ||
1398 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001399 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001400 }
1401
Yi Kong26d104a2014-08-13 19:18:14 +00001402 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1403 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1404 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1405 }
1406
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001407 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1408 BuiltinID == ARM::BI__builtin_arm_wsr64)
1409 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1410
1411 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1412 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1413 BuiltinID == ARM::BI__builtin_arm_wsr ||
1414 BuiltinID == ARM::BI__builtin_arm_wsrp)
1415 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1416
Tim Northover12670412014-02-19 10:37:05 +00001417 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1418 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001419
Yi Kong4efadfb2014-07-03 16:01:25 +00001420 // For intrinsics which take an immediate value as part of the instruction,
1421 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001422 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001423 switch (BuiltinID) {
1424 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001425 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1426 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001427 case ARM::BI__builtin_arm_vcvtr_f:
1428 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001429 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001430 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001431 case ARM::BI__builtin_arm_isb:
1432 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001433 }
Nate Begemand773fe62010-06-13 04:47:52 +00001434
Nate Begemanf568b072010-08-03 21:32:34 +00001435 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001436 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001437}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001438
Tim Northover573cbee2014-05-24 12:52:07 +00001439bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001440 CallExpr *TheCall) {
1441 llvm::APSInt Result;
1442
Tim Northover573cbee2014-05-24 12:52:07 +00001443 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001444 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1445 BuiltinID == AArch64::BI__builtin_arm_strex ||
1446 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001447 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1448 }
1449
Yi Konga5548432014-08-13 19:18:20 +00001450 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1451 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1452 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1453 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1454 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1455 }
1456
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001457 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1458 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001459 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001460
1461 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1462 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1463 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1464 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1465 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1466
Tim Northovera2ee4332014-03-29 15:09:45 +00001467 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1468 return true;
1469
Yi Kong19a29ac2014-07-17 10:52:06 +00001470 // For intrinsics which take an immediate value as part of the instruction,
1471 // range check them here.
1472 unsigned i = 0, l = 0, u = 0;
1473 switch (BuiltinID) {
1474 default: return false;
1475 case AArch64::BI__builtin_arm_dmb:
1476 case AArch64::BI__builtin_arm_dsb:
1477 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1478 }
1479
Yi Kong19a29ac2014-07-17 10:52:06 +00001480 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001481}
1482
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001483// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1484// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1485// ordering for DSP is unspecified. MSA is ordered by the data format used
1486// by the underlying instruction i.e., df/m, df/n and then by size.
1487//
1488// FIXME: The size tests here should instead be tablegen'd along with the
1489// definitions from include/clang/Basic/BuiltinsMips.def.
1490// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1491// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001492bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001493 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001494 switch (BuiltinID) {
1495 default: return false;
1496 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1497 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001498 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1499 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1500 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1501 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1502 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001503 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1504 // df/m field.
1505 // These intrinsics take an unsigned 3 bit immediate.
1506 case Mips::BI__builtin_msa_bclri_b:
1507 case Mips::BI__builtin_msa_bnegi_b:
1508 case Mips::BI__builtin_msa_bseti_b:
1509 case Mips::BI__builtin_msa_sat_s_b:
1510 case Mips::BI__builtin_msa_sat_u_b:
1511 case Mips::BI__builtin_msa_slli_b:
1512 case Mips::BI__builtin_msa_srai_b:
1513 case Mips::BI__builtin_msa_srari_b:
1514 case Mips::BI__builtin_msa_srli_b:
1515 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1516 case Mips::BI__builtin_msa_binsli_b:
1517 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1518 // These intrinsics take an unsigned 4 bit immediate.
1519 case Mips::BI__builtin_msa_bclri_h:
1520 case Mips::BI__builtin_msa_bnegi_h:
1521 case Mips::BI__builtin_msa_bseti_h:
1522 case Mips::BI__builtin_msa_sat_s_h:
1523 case Mips::BI__builtin_msa_sat_u_h:
1524 case Mips::BI__builtin_msa_slli_h:
1525 case Mips::BI__builtin_msa_srai_h:
1526 case Mips::BI__builtin_msa_srari_h:
1527 case Mips::BI__builtin_msa_srli_h:
1528 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1529 case Mips::BI__builtin_msa_binsli_h:
1530 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1531 // These intrinsics take an unsigned 5 bit immedate.
1532 // The first block of intrinsics actually have an unsigned 5 bit field,
1533 // not a df/n field.
1534 case Mips::BI__builtin_msa_clei_u_b:
1535 case Mips::BI__builtin_msa_clei_u_h:
1536 case Mips::BI__builtin_msa_clei_u_w:
1537 case Mips::BI__builtin_msa_clei_u_d:
1538 case Mips::BI__builtin_msa_clti_u_b:
1539 case Mips::BI__builtin_msa_clti_u_h:
1540 case Mips::BI__builtin_msa_clti_u_w:
1541 case Mips::BI__builtin_msa_clti_u_d:
1542 case Mips::BI__builtin_msa_maxi_u_b:
1543 case Mips::BI__builtin_msa_maxi_u_h:
1544 case Mips::BI__builtin_msa_maxi_u_w:
1545 case Mips::BI__builtin_msa_maxi_u_d:
1546 case Mips::BI__builtin_msa_mini_u_b:
1547 case Mips::BI__builtin_msa_mini_u_h:
1548 case Mips::BI__builtin_msa_mini_u_w:
1549 case Mips::BI__builtin_msa_mini_u_d:
1550 case Mips::BI__builtin_msa_addvi_b:
1551 case Mips::BI__builtin_msa_addvi_h:
1552 case Mips::BI__builtin_msa_addvi_w:
1553 case Mips::BI__builtin_msa_addvi_d:
1554 case Mips::BI__builtin_msa_bclri_w:
1555 case Mips::BI__builtin_msa_bnegi_w:
1556 case Mips::BI__builtin_msa_bseti_w:
1557 case Mips::BI__builtin_msa_sat_s_w:
1558 case Mips::BI__builtin_msa_sat_u_w:
1559 case Mips::BI__builtin_msa_slli_w:
1560 case Mips::BI__builtin_msa_srai_w:
1561 case Mips::BI__builtin_msa_srari_w:
1562 case Mips::BI__builtin_msa_srli_w:
1563 case Mips::BI__builtin_msa_srlri_w:
1564 case Mips::BI__builtin_msa_subvi_b:
1565 case Mips::BI__builtin_msa_subvi_h:
1566 case Mips::BI__builtin_msa_subvi_w:
1567 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1568 case Mips::BI__builtin_msa_binsli_w:
1569 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1570 // These intrinsics take an unsigned 6 bit immediate.
1571 case Mips::BI__builtin_msa_bclri_d:
1572 case Mips::BI__builtin_msa_bnegi_d:
1573 case Mips::BI__builtin_msa_bseti_d:
1574 case Mips::BI__builtin_msa_sat_s_d:
1575 case Mips::BI__builtin_msa_sat_u_d:
1576 case Mips::BI__builtin_msa_slli_d:
1577 case Mips::BI__builtin_msa_srai_d:
1578 case Mips::BI__builtin_msa_srari_d:
1579 case Mips::BI__builtin_msa_srli_d:
1580 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1581 case Mips::BI__builtin_msa_binsli_d:
1582 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1583 // These intrinsics take a signed 5 bit immediate.
1584 case Mips::BI__builtin_msa_ceqi_b:
1585 case Mips::BI__builtin_msa_ceqi_h:
1586 case Mips::BI__builtin_msa_ceqi_w:
1587 case Mips::BI__builtin_msa_ceqi_d:
1588 case Mips::BI__builtin_msa_clti_s_b:
1589 case Mips::BI__builtin_msa_clti_s_h:
1590 case Mips::BI__builtin_msa_clti_s_w:
1591 case Mips::BI__builtin_msa_clti_s_d:
1592 case Mips::BI__builtin_msa_clei_s_b:
1593 case Mips::BI__builtin_msa_clei_s_h:
1594 case Mips::BI__builtin_msa_clei_s_w:
1595 case Mips::BI__builtin_msa_clei_s_d:
1596 case Mips::BI__builtin_msa_maxi_s_b:
1597 case Mips::BI__builtin_msa_maxi_s_h:
1598 case Mips::BI__builtin_msa_maxi_s_w:
1599 case Mips::BI__builtin_msa_maxi_s_d:
1600 case Mips::BI__builtin_msa_mini_s_b:
1601 case Mips::BI__builtin_msa_mini_s_h:
1602 case Mips::BI__builtin_msa_mini_s_w:
1603 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1604 // These intrinsics take an unsigned 8 bit immediate.
1605 case Mips::BI__builtin_msa_andi_b:
1606 case Mips::BI__builtin_msa_nori_b:
1607 case Mips::BI__builtin_msa_ori_b:
1608 case Mips::BI__builtin_msa_shf_b:
1609 case Mips::BI__builtin_msa_shf_h:
1610 case Mips::BI__builtin_msa_shf_w:
1611 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1612 case Mips::BI__builtin_msa_bseli_b:
1613 case Mips::BI__builtin_msa_bmnzi_b:
1614 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1615 // df/n format
1616 // These intrinsics take an unsigned 4 bit immediate.
1617 case Mips::BI__builtin_msa_copy_s_b:
1618 case Mips::BI__builtin_msa_copy_u_b:
1619 case Mips::BI__builtin_msa_insve_b:
1620 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1621 case Mips::BI__builtin_msa_sld_b:
1622 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1623 // These intrinsics take an unsigned 3 bit immediate.
1624 case Mips::BI__builtin_msa_copy_s_h:
1625 case Mips::BI__builtin_msa_copy_u_h:
1626 case Mips::BI__builtin_msa_insve_h:
1627 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1628 case Mips::BI__builtin_msa_sld_h:
1629 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1630 // These intrinsics take an unsigned 2 bit immediate.
1631 case Mips::BI__builtin_msa_copy_s_w:
1632 case Mips::BI__builtin_msa_copy_u_w:
1633 case Mips::BI__builtin_msa_insve_w:
1634 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1635 case Mips::BI__builtin_msa_sld_w:
1636 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1637 // These intrinsics take an unsigned 1 bit immediate.
1638 case Mips::BI__builtin_msa_copy_s_d:
1639 case Mips::BI__builtin_msa_copy_u_d:
1640 case Mips::BI__builtin_msa_insve_d:
1641 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1642 case Mips::BI__builtin_msa_sld_d:
1643 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1644 // Memory offsets and immediate loads.
1645 // These intrinsics take a signed 10 bit immediate.
1646 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 127; break;
1647 case Mips::BI__builtin_msa_ldi_h:
1648 case Mips::BI__builtin_msa_ldi_w:
1649 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1650 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1651 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1652 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1653 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1654 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1655 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1656 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1657 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001658 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001659
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001660 if (!m)
1661 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1662
1663 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1664 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001665}
1666
Kit Bartone50adcb2015-03-30 19:40:59 +00001667bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1668 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001669 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1670 BuiltinID == PPC::BI__builtin_divdeu ||
1671 BuiltinID == PPC::BI__builtin_bpermd;
1672 bool IsTarget64Bit = Context.getTargetInfo()
1673 .getTypeWidth(Context
1674 .getTargetInfo()
1675 .getIntPtrType()) == 64;
1676 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1677 BuiltinID == PPC::BI__builtin_divweu ||
1678 BuiltinID == PPC::BI__builtin_divde ||
1679 BuiltinID == PPC::BI__builtin_divdeu;
1680
1681 if (Is64BitBltin && !IsTarget64Bit)
1682 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1683 << TheCall->getSourceRange();
1684
1685 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1686 (BuiltinID == PPC::BI__builtin_bpermd &&
1687 !Context.getTargetInfo().hasFeature("bpermd")))
1688 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1689 << TheCall->getSourceRange();
1690
Kit Bartone50adcb2015-03-30 19:40:59 +00001691 switch (BuiltinID) {
1692 default: return false;
1693 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1694 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1695 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1696 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1697 case PPC::BI__builtin_tbegin:
1698 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1699 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1700 case PPC::BI__builtin_tabortwc:
1701 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1702 case PPC::BI__builtin_tabortwci:
1703 case PPC::BI__builtin_tabortdci:
1704 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1705 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1706 }
1707 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1708}
1709
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001710bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1711 CallExpr *TheCall) {
1712 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1713 Expr *Arg = TheCall->getArg(0);
1714 llvm::APSInt AbortCode(32);
1715 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1716 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1717 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1718 << Arg->getSourceRange();
1719 }
1720
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001721 // For intrinsics which take an immediate value as part of the instruction,
1722 // range check them here.
1723 unsigned i = 0, l = 0, u = 0;
1724 switch (BuiltinID) {
1725 default: return false;
1726 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1727 case SystemZ::BI__builtin_s390_verimb:
1728 case SystemZ::BI__builtin_s390_verimh:
1729 case SystemZ::BI__builtin_s390_verimf:
1730 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1731 case SystemZ::BI__builtin_s390_vfaeb:
1732 case SystemZ::BI__builtin_s390_vfaeh:
1733 case SystemZ::BI__builtin_s390_vfaef:
1734 case SystemZ::BI__builtin_s390_vfaebs:
1735 case SystemZ::BI__builtin_s390_vfaehs:
1736 case SystemZ::BI__builtin_s390_vfaefs:
1737 case SystemZ::BI__builtin_s390_vfaezb:
1738 case SystemZ::BI__builtin_s390_vfaezh:
1739 case SystemZ::BI__builtin_s390_vfaezf:
1740 case SystemZ::BI__builtin_s390_vfaezbs:
1741 case SystemZ::BI__builtin_s390_vfaezhs:
1742 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1743 case SystemZ::BI__builtin_s390_vfidb:
1744 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1745 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1746 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1747 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1748 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1749 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1750 case SystemZ::BI__builtin_s390_vstrcb:
1751 case SystemZ::BI__builtin_s390_vstrch:
1752 case SystemZ::BI__builtin_s390_vstrcf:
1753 case SystemZ::BI__builtin_s390_vstrczb:
1754 case SystemZ::BI__builtin_s390_vstrczh:
1755 case SystemZ::BI__builtin_s390_vstrczf:
1756 case SystemZ::BI__builtin_s390_vstrcbs:
1757 case SystemZ::BI__builtin_s390_vstrchs:
1758 case SystemZ::BI__builtin_s390_vstrcfs:
1759 case SystemZ::BI__builtin_s390_vstrczbs:
1760 case SystemZ::BI__builtin_s390_vstrczhs:
1761 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1762 }
1763 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001764}
1765
Craig Topper5ba2c502015-11-07 08:08:31 +00001766/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1767/// This checks that the target supports __builtin_cpu_supports and
1768/// that the string argument is constant and valid.
1769static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1770 Expr *Arg = TheCall->getArg(0);
1771
1772 // Check if the argument is a string literal.
1773 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1774 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1775 << Arg->getSourceRange();
1776
1777 // Check the contents of the string.
1778 StringRef Feature =
1779 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1780 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1781 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1782 << Arg->getSourceRange();
1783 return false;
1784}
1785
Craig Toppera7e253e2016-09-23 04:48:31 +00001786// Check if the rounding mode is legal.
1787bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1788 // Indicates if this instruction has rounding control or just SAE.
1789 bool HasRC = false;
1790
1791 unsigned ArgNum = 0;
1792 switch (BuiltinID) {
1793 default:
1794 return false;
1795 case X86::BI__builtin_ia32_vcvttsd2si32:
1796 case X86::BI__builtin_ia32_vcvttsd2si64:
1797 case X86::BI__builtin_ia32_vcvttsd2usi32:
1798 case X86::BI__builtin_ia32_vcvttsd2usi64:
1799 case X86::BI__builtin_ia32_vcvttss2si32:
1800 case X86::BI__builtin_ia32_vcvttss2si64:
1801 case X86::BI__builtin_ia32_vcvttss2usi32:
1802 case X86::BI__builtin_ia32_vcvttss2usi64:
1803 ArgNum = 1;
1804 break;
1805 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1806 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1807 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1808 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1809 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1810 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1811 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1812 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1813 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1814 case X86::BI__builtin_ia32_exp2pd_mask:
1815 case X86::BI__builtin_ia32_exp2ps_mask:
1816 case X86::BI__builtin_ia32_getexppd512_mask:
1817 case X86::BI__builtin_ia32_getexpps512_mask:
1818 case X86::BI__builtin_ia32_rcp28pd_mask:
1819 case X86::BI__builtin_ia32_rcp28ps_mask:
1820 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1821 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1822 case X86::BI__builtin_ia32_vcomisd:
1823 case X86::BI__builtin_ia32_vcomiss:
1824 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1825 ArgNum = 3;
1826 break;
1827 case X86::BI__builtin_ia32_cmppd512_mask:
1828 case X86::BI__builtin_ia32_cmpps512_mask:
1829 case X86::BI__builtin_ia32_cmpsd_mask:
1830 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001831 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001832 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1833 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001834 case X86::BI__builtin_ia32_maxpd512_mask:
1835 case X86::BI__builtin_ia32_maxps512_mask:
1836 case X86::BI__builtin_ia32_maxsd_round_mask:
1837 case X86::BI__builtin_ia32_maxss_round_mask:
1838 case X86::BI__builtin_ia32_minpd512_mask:
1839 case X86::BI__builtin_ia32_minps512_mask:
1840 case X86::BI__builtin_ia32_minsd_round_mask:
1841 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001842 case X86::BI__builtin_ia32_rcp28sd_round_mask:
1843 case X86::BI__builtin_ia32_rcp28ss_round_mask:
1844 case X86::BI__builtin_ia32_reducepd512_mask:
1845 case X86::BI__builtin_ia32_reduceps512_mask:
1846 case X86::BI__builtin_ia32_rndscalepd_mask:
1847 case X86::BI__builtin_ia32_rndscaleps_mask:
1848 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1849 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1850 ArgNum = 4;
1851 break;
1852 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001853 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001854 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001855 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001856 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001857 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001858 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001859 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001860 case X86::BI__builtin_ia32_rangepd512_mask:
1861 case X86::BI__builtin_ia32_rangeps512_mask:
1862 case X86::BI__builtin_ia32_rangesd128_round_mask:
1863 case X86::BI__builtin_ia32_rangess128_round_mask:
1864 case X86::BI__builtin_ia32_reducesd_mask:
1865 case X86::BI__builtin_ia32_reducess_mask:
1866 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1867 case X86::BI__builtin_ia32_rndscaless_round_mask:
1868 ArgNum = 5;
1869 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00001870 case X86::BI__builtin_ia32_vcvtsd2si64:
1871 case X86::BI__builtin_ia32_vcvtsd2si32:
1872 case X86::BI__builtin_ia32_vcvtsd2usi32:
1873 case X86::BI__builtin_ia32_vcvtsd2usi64:
1874 case X86::BI__builtin_ia32_vcvtss2si32:
1875 case X86::BI__builtin_ia32_vcvtss2si64:
1876 case X86::BI__builtin_ia32_vcvtss2usi32:
1877 case X86::BI__builtin_ia32_vcvtss2usi64:
1878 ArgNum = 1;
1879 HasRC = true;
1880 break;
Craig Topper8e066312016-11-07 07:01:09 +00001881 case X86::BI__builtin_ia32_cvtsi2sd64:
1882 case X86::BI__builtin_ia32_cvtsi2ss32:
1883 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00001884 case X86::BI__builtin_ia32_cvtusi2sd64:
1885 case X86::BI__builtin_ia32_cvtusi2ss32:
1886 case X86::BI__builtin_ia32_cvtusi2ss64:
1887 ArgNum = 2;
1888 HasRC = true;
1889 break;
1890 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1891 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1892 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1893 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1894 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1895 case X86::BI__builtin_ia32_cvtps2qq512_mask:
1896 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1897 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1898 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1899 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1900 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001901 case X86::BI__builtin_ia32_sqrtpd512_mask:
1902 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001903 ArgNum = 3;
1904 HasRC = true;
1905 break;
1906 case X86::BI__builtin_ia32_addpd512_mask:
1907 case X86::BI__builtin_ia32_addps512_mask:
1908 case X86::BI__builtin_ia32_divpd512_mask:
1909 case X86::BI__builtin_ia32_divps512_mask:
1910 case X86::BI__builtin_ia32_mulpd512_mask:
1911 case X86::BI__builtin_ia32_mulps512_mask:
1912 case X86::BI__builtin_ia32_subpd512_mask:
1913 case X86::BI__builtin_ia32_subps512_mask:
1914 case X86::BI__builtin_ia32_addss_round_mask:
1915 case X86::BI__builtin_ia32_addsd_round_mask:
1916 case X86::BI__builtin_ia32_divss_round_mask:
1917 case X86::BI__builtin_ia32_divsd_round_mask:
1918 case X86::BI__builtin_ia32_mulss_round_mask:
1919 case X86::BI__builtin_ia32_mulsd_round_mask:
1920 case X86::BI__builtin_ia32_subss_round_mask:
1921 case X86::BI__builtin_ia32_subsd_round_mask:
1922 case X86::BI__builtin_ia32_scalefpd512_mask:
1923 case X86::BI__builtin_ia32_scalefps512_mask:
1924 case X86::BI__builtin_ia32_scalefsd_round_mask:
1925 case X86::BI__builtin_ia32_scalefss_round_mask:
1926 case X86::BI__builtin_ia32_getmantpd512_mask:
1927 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001928 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
1929 case X86::BI__builtin_ia32_sqrtsd_round_mask:
1930 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001931 case X86::BI__builtin_ia32_vfmaddpd512_mask:
1932 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1933 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1934 case X86::BI__builtin_ia32_vfmaddps512_mask:
1935 case X86::BI__builtin_ia32_vfmaddps512_mask3:
1936 case X86::BI__builtin_ia32_vfmaddps512_maskz:
1937 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1938 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1939 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1940 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1941 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1942 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1943 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1944 case X86::BI__builtin_ia32_vfmsubps512_mask3:
1945 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1946 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1947 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1948 case X86::BI__builtin_ia32_vfnmaddps512_mask:
1949 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1950 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1951 case X86::BI__builtin_ia32_vfnmsubps512_mask:
1952 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1953 case X86::BI__builtin_ia32_vfmaddsd3_mask:
1954 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1955 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1956 case X86::BI__builtin_ia32_vfmaddss3_mask:
1957 case X86::BI__builtin_ia32_vfmaddss3_maskz:
1958 case X86::BI__builtin_ia32_vfmaddss3_mask3:
1959 ArgNum = 4;
1960 HasRC = true;
1961 break;
1962 case X86::BI__builtin_ia32_getmantsd_round_mask:
1963 case X86::BI__builtin_ia32_getmantss_round_mask:
1964 ArgNum = 5;
1965 HasRC = true;
1966 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00001967 }
1968
1969 llvm::APSInt Result;
1970
1971 // We can't check the value of a dependent argument.
1972 Expr *Arg = TheCall->getArg(ArgNum);
1973 if (Arg->isTypeDependent() || Arg->isValueDependent())
1974 return false;
1975
1976 // Check constant-ness first.
1977 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1978 return true;
1979
1980 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1981 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1982 // combined with ROUND_NO_EXC.
1983 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1984 Result == 8/*ROUND_NO_EXC*/ ||
1985 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1986 return false;
1987
1988 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1989 << Arg->getSourceRange();
1990}
1991
Craig Topperf0ddc892016-09-23 04:48:27 +00001992bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1993 if (BuiltinID == X86::BI__builtin_cpu_supports)
1994 return SemaBuiltinCpuSupports(*this, TheCall);
1995
1996 if (BuiltinID == X86::BI__builtin_ms_va_start)
1997 return SemaBuiltinMSVAStart(TheCall);
1998
Craig Toppera7e253e2016-09-23 04:48:31 +00001999 // If the intrinsic has rounding or SAE make sure its valid.
2000 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2001 return true;
2002
Craig Topperf0ddc892016-09-23 04:48:27 +00002003 // For intrinsics which take an immediate value as part of the instruction,
2004 // range check them here.
2005 int i = 0, l = 0, u = 0;
2006 switch (BuiltinID) {
2007 default:
2008 return false;
Richard Trieucc3949d2016-02-18 22:34:54 +00002009 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00002010 i = 1; l = 0; u = 3;
2011 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002012 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00002013 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2014 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2015 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2016 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002017 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002018 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002019 case X86::BI__builtin_ia32_vpermil2pd:
2020 case X86::BI__builtin_ia32_vpermil2pd256:
2021 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002022 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002023 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002024 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002025 case X86::BI__builtin_ia32_cmpb128_mask:
2026 case X86::BI__builtin_ia32_cmpw128_mask:
2027 case X86::BI__builtin_ia32_cmpd128_mask:
2028 case X86::BI__builtin_ia32_cmpq128_mask:
2029 case X86::BI__builtin_ia32_cmpb256_mask:
2030 case X86::BI__builtin_ia32_cmpw256_mask:
2031 case X86::BI__builtin_ia32_cmpd256_mask:
2032 case X86::BI__builtin_ia32_cmpq256_mask:
2033 case X86::BI__builtin_ia32_cmpb512_mask:
2034 case X86::BI__builtin_ia32_cmpw512_mask:
2035 case X86::BI__builtin_ia32_cmpd512_mask:
2036 case X86::BI__builtin_ia32_cmpq512_mask:
2037 case X86::BI__builtin_ia32_ucmpb128_mask:
2038 case X86::BI__builtin_ia32_ucmpw128_mask:
2039 case X86::BI__builtin_ia32_ucmpd128_mask:
2040 case X86::BI__builtin_ia32_ucmpq128_mask:
2041 case X86::BI__builtin_ia32_ucmpb256_mask:
2042 case X86::BI__builtin_ia32_ucmpw256_mask:
2043 case X86::BI__builtin_ia32_ucmpd256_mask:
2044 case X86::BI__builtin_ia32_ucmpq256_mask:
2045 case X86::BI__builtin_ia32_ucmpb512_mask:
2046 case X86::BI__builtin_ia32_ucmpw512_mask:
2047 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002048 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002049 case X86::BI__builtin_ia32_vpcomub:
2050 case X86::BI__builtin_ia32_vpcomuw:
2051 case X86::BI__builtin_ia32_vpcomud:
2052 case X86::BI__builtin_ia32_vpcomuq:
2053 case X86::BI__builtin_ia32_vpcomb:
2054 case X86::BI__builtin_ia32_vpcomw:
2055 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002056 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00002057 i = 2; l = 0; u = 7;
2058 break;
2059 case X86::BI__builtin_ia32_roundps:
2060 case X86::BI__builtin_ia32_roundpd:
2061 case X86::BI__builtin_ia32_roundps256:
2062 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002063 i = 1; l = 0; u = 15;
2064 break;
2065 case X86::BI__builtin_ia32_roundss:
2066 case X86::BI__builtin_ia32_roundsd:
2067 case X86::BI__builtin_ia32_rangepd128_mask:
2068 case X86::BI__builtin_ia32_rangepd256_mask:
2069 case X86::BI__builtin_ia32_rangepd512_mask:
2070 case X86::BI__builtin_ia32_rangeps128_mask:
2071 case X86::BI__builtin_ia32_rangeps256_mask:
2072 case X86::BI__builtin_ia32_rangeps512_mask:
2073 case X86::BI__builtin_ia32_getmantsd_round_mask:
2074 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002075 i = 2; l = 0; u = 15;
2076 break;
2077 case X86::BI__builtin_ia32_cmpps:
2078 case X86::BI__builtin_ia32_cmpss:
2079 case X86::BI__builtin_ia32_cmppd:
2080 case X86::BI__builtin_ia32_cmpsd:
2081 case X86::BI__builtin_ia32_cmpps256:
2082 case X86::BI__builtin_ia32_cmppd256:
2083 case X86::BI__builtin_ia32_cmpps128_mask:
2084 case X86::BI__builtin_ia32_cmppd128_mask:
2085 case X86::BI__builtin_ia32_cmpps256_mask:
2086 case X86::BI__builtin_ia32_cmppd256_mask:
2087 case X86::BI__builtin_ia32_cmpps512_mask:
2088 case X86::BI__builtin_ia32_cmppd512_mask:
2089 case X86::BI__builtin_ia32_cmpsd_mask:
2090 case X86::BI__builtin_ia32_cmpss_mask:
2091 i = 2; l = 0; u = 31;
2092 break;
2093 case X86::BI__builtin_ia32_xabort:
2094 i = 0; l = -128; u = 255;
2095 break;
2096 case X86::BI__builtin_ia32_pshufw:
2097 case X86::BI__builtin_ia32_aeskeygenassist128:
2098 i = 1; l = -128; u = 255;
2099 break;
2100 case X86::BI__builtin_ia32_vcvtps2ph:
2101 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper39c87102016-05-18 03:18:12 +00002102 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2103 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2104 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2105 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2106 case X86::BI__builtin_ia32_rndscaleps_mask:
2107 case X86::BI__builtin_ia32_rndscalepd_mask:
2108 case X86::BI__builtin_ia32_reducepd128_mask:
2109 case X86::BI__builtin_ia32_reducepd256_mask:
2110 case X86::BI__builtin_ia32_reducepd512_mask:
2111 case X86::BI__builtin_ia32_reduceps128_mask:
2112 case X86::BI__builtin_ia32_reduceps256_mask:
2113 case X86::BI__builtin_ia32_reduceps512_mask:
2114 case X86::BI__builtin_ia32_prold512_mask:
2115 case X86::BI__builtin_ia32_prolq512_mask:
2116 case X86::BI__builtin_ia32_prold128_mask:
2117 case X86::BI__builtin_ia32_prold256_mask:
2118 case X86::BI__builtin_ia32_prolq128_mask:
2119 case X86::BI__builtin_ia32_prolq256_mask:
2120 case X86::BI__builtin_ia32_prord128_mask:
2121 case X86::BI__builtin_ia32_prord256_mask:
2122 case X86::BI__builtin_ia32_prorq128_mask:
2123 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002124 case X86::BI__builtin_ia32_fpclasspd128_mask:
2125 case X86::BI__builtin_ia32_fpclasspd256_mask:
2126 case X86::BI__builtin_ia32_fpclassps128_mask:
2127 case X86::BI__builtin_ia32_fpclassps256_mask:
2128 case X86::BI__builtin_ia32_fpclassps512_mask:
2129 case X86::BI__builtin_ia32_fpclasspd512_mask:
2130 case X86::BI__builtin_ia32_fpclasssd_mask:
2131 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002132 i = 1; l = 0; u = 255;
2133 break;
2134 case X86::BI__builtin_ia32_palignr:
2135 case X86::BI__builtin_ia32_insertps128:
2136 case X86::BI__builtin_ia32_dpps:
2137 case X86::BI__builtin_ia32_dppd:
2138 case X86::BI__builtin_ia32_dpps256:
2139 case X86::BI__builtin_ia32_mpsadbw128:
2140 case X86::BI__builtin_ia32_mpsadbw256:
2141 case X86::BI__builtin_ia32_pcmpistrm128:
2142 case X86::BI__builtin_ia32_pcmpistri128:
2143 case X86::BI__builtin_ia32_pcmpistria128:
2144 case X86::BI__builtin_ia32_pcmpistric128:
2145 case X86::BI__builtin_ia32_pcmpistrio128:
2146 case X86::BI__builtin_ia32_pcmpistris128:
2147 case X86::BI__builtin_ia32_pcmpistriz128:
2148 case X86::BI__builtin_ia32_pclmulqdq128:
2149 case X86::BI__builtin_ia32_vperm2f128_pd256:
2150 case X86::BI__builtin_ia32_vperm2f128_ps256:
2151 case X86::BI__builtin_ia32_vperm2f128_si256:
2152 case X86::BI__builtin_ia32_permti256:
2153 i = 2; l = -128; u = 255;
2154 break;
2155 case X86::BI__builtin_ia32_palignr128:
2156 case X86::BI__builtin_ia32_palignr256:
Craig Topper39c87102016-05-18 03:18:12 +00002157 case X86::BI__builtin_ia32_palignr512_mask:
2158 case X86::BI__builtin_ia32_alignq512_mask:
2159 case X86::BI__builtin_ia32_alignd512_mask:
2160 case X86::BI__builtin_ia32_alignd128_mask:
2161 case X86::BI__builtin_ia32_alignd256_mask:
2162 case X86::BI__builtin_ia32_alignq128_mask:
2163 case X86::BI__builtin_ia32_alignq256_mask:
2164 case X86::BI__builtin_ia32_vcomisd:
2165 case X86::BI__builtin_ia32_vcomiss:
2166 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2167 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2168 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2169 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002170 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2171 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2172 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2173 i = 2; l = 0; u = 255;
2174 break;
2175 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2176 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2177 case X86::BI__builtin_ia32_fixupimmps512_mask:
2178 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2179 case X86::BI__builtin_ia32_fixupimmsd_mask:
2180 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2181 case X86::BI__builtin_ia32_fixupimmss_mask:
2182 case X86::BI__builtin_ia32_fixupimmss_maskz:
2183 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2184 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2185 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2186 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2187 case X86::BI__builtin_ia32_fixupimmps128_mask:
2188 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2189 case X86::BI__builtin_ia32_fixupimmps256_mask:
2190 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2191 case X86::BI__builtin_ia32_pternlogd512_mask:
2192 case X86::BI__builtin_ia32_pternlogd512_maskz:
2193 case X86::BI__builtin_ia32_pternlogq512_mask:
2194 case X86::BI__builtin_ia32_pternlogq512_maskz:
2195 case X86::BI__builtin_ia32_pternlogd128_mask:
2196 case X86::BI__builtin_ia32_pternlogd128_maskz:
2197 case X86::BI__builtin_ia32_pternlogd256_mask:
2198 case X86::BI__builtin_ia32_pternlogd256_maskz:
2199 case X86::BI__builtin_ia32_pternlogq128_mask:
2200 case X86::BI__builtin_ia32_pternlogq128_maskz:
2201 case X86::BI__builtin_ia32_pternlogq256_mask:
2202 case X86::BI__builtin_ia32_pternlogq256_maskz:
2203 i = 3; l = 0; u = 255;
2204 break;
2205 case X86::BI__builtin_ia32_pcmpestrm128:
2206 case X86::BI__builtin_ia32_pcmpestri128:
2207 case X86::BI__builtin_ia32_pcmpestria128:
2208 case X86::BI__builtin_ia32_pcmpestric128:
2209 case X86::BI__builtin_ia32_pcmpestrio128:
2210 case X86::BI__builtin_ia32_pcmpestris128:
2211 case X86::BI__builtin_ia32_pcmpestriz128:
2212 i = 4; l = -128; u = 255;
2213 break;
2214 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2215 case X86::BI__builtin_ia32_rndscaless_round_mask:
2216 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002217 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002218 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002219 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002220}
2221
Richard Smith55ce3522012-06-25 20:30:08 +00002222/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2223/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2224/// Returns true when the format fits the function and the FormatStringInfo has
2225/// been populated.
2226bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2227 FormatStringInfo *FSI) {
2228 FSI->HasVAListArg = Format->getFirstArg() == 0;
2229 FSI->FormatIdx = Format->getFormatIdx() - 1;
2230 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002231
Richard Smith55ce3522012-06-25 20:30:08 +00002232 // The way the format attribute works in GCC, the implicit this argument
2233 // of member functions is counted. However, it doesn't appear in our own
2234 // lists, so decrement format_idx in that case.
2235 if (IsCXXMember) {
2236 if(FSI->FormatIdx == 0)
2237 return false;
2238 --FSI->FormatIdx;
2239 if (FSI->FirstDataArg != 0)
2240 --FSI->FirstDataArg;
2241 }
2242 return true;
2243}
Mike Stump11289f42009-09-09 15:08:12 +00002244
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002245/// Checks if a the given expression evaluates to null.
2246///
2247/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002248static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002249 // If the expression has non-null type, it doesn't evaluate to null.
2250 if (auto nullability
2251 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2252 if (*nullability == NullabilityKind::NonNull)
2253 return false;
2254 }
2255
Ted Kremeneka146db32014-01-17 06:24:47 +00002256 // As a special case, transparent unions initialized with zero are
2257 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002258 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002259 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2260 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002261 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002262 if (const InitListExpr *ILE =
2263 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002264 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002265 }
2266
2267 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002268 return (!Expr->isValueDependent() &&
2269 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2270 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002271}
2272
2273static void CheckNonNullArgument(Sema &S,
2274 const Expr *ArgExpr,
2275 SourceLocation CallSiteLoc) {
2276 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002277 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2278 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002279}
2280
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002281bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2282 FormatStringInfo FSI;
2283 if ((GetFormatStringType(Format) == FST_NSString) &&
2284 getFormatStringInfo(Format, false, &FSI)) {
2285 Idx = FSI.FormatIdx;
2286 return true;
2287 }
2288 return false;
2289}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002290/// \brief Diagnose use of %s directive in an NSString which is being passed
2291/// as formatting string to formatting method.
2292static void
2293DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2294 const NamedDecl *FDecl,
2295 Expr **Args,
2296 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002297 unsigned Idx = 0;
2298 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002299 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2300 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002301 Idx = 2;
2302 Format = true;
2303 }
2304 else
2305 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2306 if (S.GetFormatNSStringIdx(I, Idx)) {
2307 Format = true;
2308 break;
2309 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002310 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002311 if (!Format || NumArgs <= Idx)
2312 return;
2313 const Expr *FormatExpr = Args[Idx];
2314 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2315 FormatExpr = CSCE->getSubExpr();
2316 const StringLiteral *FormatString;
2317 if (const ObjCStringLiteral *OSL =
2318 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2319 FormatString = OSL->getString();
2320 else
2321 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2322 if (!FormatString)
2323 return;
2324 if (S.FormatStringHasSArg(FormatString)) {
2325 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2326 << "%s" << 1 << 1;
2327 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2328 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002329 }
2330}
2331
Douglas Gregorb4866e82015-06-19 18:13:19 +00002332/// Determine whether the given type has a non-null nullability annotation.
2333static bool isNonNullType(ASTContext &ctx, QualType type) {
2334 if (auto nullability = type->getNullability(ctx))
2335 return *nullability == NullabilityKind::NonNull;
2336
2337 return false;
2338}
2339
Ted Kremenek2bc73332014-01-17 06:24:43 +00002340static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002341 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002342 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002343 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002344 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002345 assert((FDecl || Proto) && "Need a function declaration or prototype");
2346
Ted Kremenek9aedc152014-01-17 06:24:56 +00002347 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002348 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002349 if (FDecl) {
2350 // Handle the nonnull attribute on the function/method declaration itself.
2351 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2352 if (!NonNull->args_size()) {
2353 // Easy case: all pointer arguments are nonnull.
2354 for (const auto *Arg : Args)
2355 if (S.isValidPointerAttrType(Arg->getType()))
2356 CheckNonNullArgument(S, Arg, CallSiteLoc);
2357 return;
2358 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002359
Douglas Gregorb4866e82015-06-19 18:13:19 +00002360 for (unsigned Val : NonNull->args()) {
2361 if (Val >= Args.size())
2362 continue;
2363 if (NonNullArgs.empty())
2364 NonNullArgs.resize(Args.size());
2365 NonNullArgs.set(Val);
2366 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002367 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002368 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002369
Douglas Gregorb4866e82015-06-19 18:13:19 +00002370 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2371 // Handle the nonnull attribute on the parameters of the
2372 // function/method.
2373 ArrayRef<ParmVarDecl*> parms;
2374 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2375 parms = FD->parameters();
2376 else
2377 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2378
2379 unsigned ParamIndex = 0;
2380 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2381 I != E; ++I, ++ParamIndex) {
2382 const ParmVarDecl *PVD = *I;
2383 if (PVD->hasAttr<NonNullAttr>() ||
2384 isNonNullType(S.Context, PVD->getType())) {
2385 if (NonNullArgs.empty())
2386 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002387
Douglas Gregorb4866e82015-06-19 18:13:19 +00002388 NonNullArgs.set(ParamIndex);
2389 }
2390 }
2391 } else {
2392 // If we have a non-function, non-method declaration but no
2393 // function prototype, try to dig out the function prototype.
2394 if (!Proto) {
2395 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2396 QualType type = VD->getType().getNonReferenceType();
2397 if (auto pointerType = type->getAs<PointerType>())
2398 type = pointerType->getPointeeType();
2399 else if (auto blockType = type->getAs<BlockPointerType>())
2400 type = blockType->getPointeeType();
2401 // FIXME: data member pointers?
2402
2403 // Dig out the function prototype, if there is one.
2404 Proto = type->getAs<FunctionProtoType>();
2405 }
2406 }
2407
2408 // Fill in non-null argument information from the nullability
2409 // information on the parameter types (if we have them).
2410 if (Proto) {
2411 unsigned Index = 0;
2412 for (auto paramType : Proto->getParamTypes()) {
2413 if (isNonNullType(S.Context, paramType)) {
2414 if (NonNullArgs.empty())
2415 NonNullArgs.resize(Args.size());
2416
2417 NonNullArgs.set(Index);
2418 }
2419
2420 ++Index;
2421 }
2422 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002423 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002424
Douglas Gregorb4866e82015-06-19 18:13:19 +00002425 // Check for non-null arguments.
2426 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2427 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002428 if (NonNullArgs[ArgIndex])
2429 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002430 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002431}
2432
Richard Smith55ce3522012-06-25 20:30:08 +00002433/// Handles the checks for format strings, non-POD arguments to vararg
2434/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002435void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2436 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00002437 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00002438 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002439 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002440 if (CurContext->isDependentContext())
2441 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002442
Ted Kremenekb8176da2010-09-09 04:33:05 +00002443 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002444 llvm::SmallBitVector CheckedVarArgs;
2445 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002446 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002447 // Only create vector if there are format attributes.
2448 CheckedVarArgs.resize(Args.size());
2449
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002450 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002451 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002452 }
Richard Smithd7293d72013-08-05 18:49:43 +00002453 }
Richard Smith55ce3522012-06-25 20:30:08 +00002454
2455 // Refuse POD arguments that weren't caught by the format string
2456 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00002457 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002458 unsigned NumParams = Proto ? Proto->getNumParams()
2459 : FDecl && isa<FunctionDecl>(FDecl)
2460 ? cast<FunctionDecl>(FDecl)->getNumParams()
2461 : FDecl && isa<ObjCMethodDecl>(FDecl)
2462 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2463 : 0;
2464
Alp Toker9cacbab2014-01-20 20:26:09 +00002465 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002466 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002467 if (const Expr *Arg = Args[ArgIdx]) {
2468 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2469 checkVariadicArgument(Arg, CallType);
2470 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002471 }
Richard Smithd7293d72013-08-05 18:49:43 +00002472 }
Mike Stump11289f42009-09-09 15:08:12 +00002473
Douglas Gregorb4866e82015-06-19 18:13:19 +00002474 if (FDecl || Proto) {
2475 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002476
Richard Trieu41bc0992013-06-22 00:20:41 +00002477 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002478 if (FDecl) {
2479 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2480 CheckArgumentWithTypeTag(I, Args.data());
2481 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002482 }
Richard Smith55ce3522012-06-25 20:30:08 +00002483}
2484
2485/// CheckConstructorCall - Check a constructor call for correctness and safety
2486/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002487void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2488 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002489 const FunctionProtoType *Proto,
2490 SourceLocation Loc) {
2491 VariadicCallType CallType =
2492 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002493 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
2494 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002495}
2496
2497/// CheckFunctionCall - Check a direct function call for various correctness
2498/// and safety properties not strictly enforced by the C type system.
2499bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2500 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002501 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2502 isa<CXXMethodDecl>(FDecl);
2503 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2504 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002505 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2506 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002507 Expr** Args = TheCall->getArgs();
2508 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00002509 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002510 // If this is a call to a member operator, hide the first argument
2511 // from checkCall.
2512 // FIXME: Our choice of AST representation here is less than ideal.
2513 ++Args;
2514 --NumArgs;
2515 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00002516 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002517 IsMemberFunction, TheCall->getRParenLoc(),
2518 TheCall->getCallee()->getSourceRange(), CallType);
2519
2520 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2521 // None of the checks below are needed for functions that don't have
2522 // simple names (e.g., C++ conversion functions).
2523 if (!FnInfo)
2524 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002525
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002526 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002527 if (getLangOpts().ObjC1)
2528 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002529
Anna Zaks22122702012-01-17 00:37:07 +00002530 unsigned CMId = FDecl->getMemoryFunctionKind();
2531 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002532 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002533
Anna Zaks201d4892012-01-13 21:52:01 +00002534 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002535 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002536 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002537 else if (CMId == Builtin::BIstrncat)
2538 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002539 else
Anna Zaks22122702012-01-17 00:37:07 +00002540 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002541
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002542 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002543}
2544
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002545bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002546 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002547 VariadicCallType CallType =
2548 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002549
Douglas Gregorb4866e82015-06-19 18:13:19 +00002550 checkCall(Method, nullptr, Args,
2551 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2552 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002553
2554 return false;
2555}
2556
Richard Trieu664c4c62013-06-20 21:03:13 +00002557bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2558 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002559 QualType Ty;
2560 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002561 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002562 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002563 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002564 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002565 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002566
Douglas Gregorb4866e82015-06-19 18:13:19 +00002567 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2568 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002569 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002570
Richard Trieu664c4c62013-06-20 21:03:13 +00002571 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002572 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002573 CallType = VariadicDoesNotApply;
2574 } else if (Ty->isBlockPointerType()) {
2575 CallType = VariadicBlock;
2576 } else { // Ty->isFunctionPointerType()
2577 CallType = VariadicFunction;
2578 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002579
Douglas Gregorb4866e82015-06-19 18:13:19 +00002580 checkCall(NDecl, Proto,
2581 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2582 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002583 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002584
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002585 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002586}
2587
Richard Trieu41bc0992013-06-22 00:20:41 +00002588/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2589/// such as function pointers returned from functions.
2590bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002591 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002592 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00002593 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002594 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002595 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002596 TheCall->getCallee()->getSourceRange(), CallType);
2597
2598 return false;
2599}
2600
Tim Northovere94a34c2014-03-11 10:49:14 +00002601static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002602 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002603 return false;
2604
JF Bastiendda2cb12016-04-18 18:01:49 +00002605 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002606 switch (Op) {
2607 case AtomicExpr::AO__c11_atomic_init:
2608 llvm_unreachable("There is no ordering argument for an init");
2609
2610 case AtomicExpr::AO__c11_atomic_load:
2611 case AtomicExpr::AO__atomic_load_n:
2612 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002613 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2614 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002615
2616 case AtomicExpr::AO__c11_atomic_store:
2617 case AtomicExpr::AO__atomic_store:
2618 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002619 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2620 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2621 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002622
2623 default:
2624 return true;
2625 }
2626}
2627
Richard Smithfeea8832012-04-12 05:08:17 +00002628ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2629 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002630 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2631 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002632
Richard Smithfeea8832012-04-12 05:08:17 +00002633 // All these operations take one of the following forms:
2634 enum {
2635 // C __c11_atomic_init(A *, C)
2636 Init,
2637 // C __c11_atomic_load(A *, int)
2638 Load,
2639 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002640 LoadCopy,
2641 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002642 Copy,
2643 // C __c11_atomic_add(A *, M, int)
2644 Arithmetic,
2645 // C __atomic_exchange_n(A *, CP, int)
2646 Xchg,
2647 // void __atomic_exchange(A *, C *, CP, int)
2648 GNUXchg,
2649 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2650 C11CmpXchg,
2651 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2652 GNUCmpXchg
2653 } Form = Init;
Eric Fiselier8d662442016-03-30 23:39:56 +00002654 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2655 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002656 // where:
2657 // C is an appropriate type,
2658 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2659 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2660 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2661 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002662
Gabor Horvath98bd0982015-03-16 09:59:54 +00002663 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2664 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2665 AtomicExpr::AO__atomic_load,
2666 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00002667 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2668 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2669 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2670 Op == AtomicExpr::AO__atomic_store_n ||
2671 Op == AtomicExpr::AO__atomic_exchange_n ||
2672 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2673 bool IsAddSub = false;
2674
2675 switch (Op) {
2676 case AtomicExpr::AO__c11_atomic_init:
2677 Form = Init;
2678 break;
2679
2680 case AtomicExpr::AO__c11_atomic_load:
2681 case AtomicExpr::AO__atomic_load_n:
2682 Form = Load;
2683 break;
2684
Richard Smithfeea8832012-04-12 05:08:17 +00002685 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002686 Form = LoadCopy;
2687 break;
2688
2689 case AtomicExpr::AO__c11_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002690 case AtomicExpr::AO__atomic_store:
2691 case AtomicExpr::AO__atomic_store_n:
2692 Form = Copy;
2693 break;
2694
2695 case AtomicExpr::AO__c11_atomic_fetch_add:
2696 case AtomicExpr::AO__c11_atomic_fetch_sub:
2697 case AtomicExpr::AO__atomic_fetch_add:
2698 case AtomicExpr::AO__atomic_fetch_sub:
2699 case AtomicExpr::AO__atomic_add_fetch:
2700 case AtomicExpr::AO__atomic_sub_fetch:
2701 IsAddSub = true;
2702 // Fall through.
2703 case AtomicExpr::AO__c11_atomic_fetch_and:
2704 case AtomicExpr::AO__c11_atomic_fetch_or:
2705 case AtomicExpr::AO__c11_atomic_fetch_xor:
2706 case AtomicExpr::AO__atomic_fetch_and:
2707 case AtomicExpr::AO__atomic_fetch_or:
2708 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00002709 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00002710 case AtomicExpr::AO__atomic_and_fetch:
2711 case AtomicExpr::AO__atomic_or_fetch:
2712 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00002713 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00002714 Form = Arithmetic;
2715 break;
2716
2717 case AtomicExpr::AO__c11_atomic_exchange:
2718 case AtomicExpr::AO__atomic_exchange_n:
2719 Form = Xchg;
2720 break;
2721
2722 case AtomicExpr::AO__atomic_exchange:
2723 Form = GNUXchg;
2724 break;
2725
2726 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2727 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2728 Form = C11CmpXchg;
2729 break;
2730
2731 case AtomicExpr::AO__atomic_compare_exchange:
2732 case AtomicExpr::AO__atomic_compare_exchange_n:
2733 Form = GNUCmpXchg;
2734 break;
2735 }
2736
2737 // Check we have the right number of arguments.
2738 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002739 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002740 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002741 << TheCall->getCallee()->getSourceRange();
2742 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00002743 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2744 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002745 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002746 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002747 << TheCall->getCallee()->getSourceRange();
2748 return ExprError();
2749 }
2750
Richard Smithfeea8832012-04-12 05:08:17 +00002751 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002752 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00002753 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2754 if (ConvertedPtr.isInvalid())
2755 return ExprError();
2756
2757 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002758 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2759 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00002760 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002761 << Ptr->getType() << Ptr->getSourceRange();
2762 return ExprError();
2763 }
2764
Richard Smithfeea8832012-04-12 05:08:17 +00002765 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2766 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2767 QualType ValType = AtomTy; // 'C'
2768 if (IsC11) {
2769 if (!AtomTy->isAtomicType()) {
2770 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2771 << Ptr->getType() << Ptr->getSourceRange();
2772 return ExprError();
2773 }
Richard Smithe00921a2012-09-15 06:09:58 +00002774 if (AtomTy.isConstQualified()) {
2775 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2776 << Ptr->getType() << Ptr->getSourceRange();
2777 return ExprError();
2778 }
Richard Smithfeea8832012-04-12 05:08:17 +00002779 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00002780 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002781 if (ValType.isConstQualified()) {
2782 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2783 << Ptr->getType() << Ptr->getSourceRange();
2784 return ExprError();
2785 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002786 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002787
Richard Smithfeea8832012-04-12 05:08:17 +00002788 // For an arithmetic operation, the implied arithmetic must be well-formed.
2789 if (Form == Arithmetic) {
2790 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2791 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2792 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2793 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2794 return ExprError();
2795 }
2796 if (!IsAddSub && !ValType->isIntegerType()) {
2797 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2798 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2799 return ExprError();
2800 }
David Majnemere85cff82015-01-28 05:48:06 +00002801 if (IsC11 && ValType->isPointerType() &&
2802 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2803 diag::err_incomplete_type)) {
2804 return ExprError();
2805 }
Richard Smithfeea8832012-04-12 05:08:17 +00002806 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2807 // For __atomic_*_n operations, the value type must be a scalar integral or
2808 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002809 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00002810 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2811 return ExprError();
2812 }
2813
Eli Friedmanaa769812013-09-11 03:49:34 +00002814 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2815 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00002816 // For GNU atomics, require a trivially-copyable type. This is not part of
2817 // the GNU atomics specification, but we enforce it for sanity.
2818 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002819 << Ptr->getType() << Ptr->getSourceRange();
2820 return ExprError();
2821 }
2822
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002823 switch (ValType.getObjCLifetime()) {
2824 case Qualifiers::OCL_None:
2825 case Qualifiers::OCL_ExplicitNone:
2826 // okay
2827 break;
2828
2829 case Qualifiers::OCL_Weak:
2830 case Qualifiers::OCL_Strong:
2831 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002832 // FIXME: Can this happen? By this point, ValType should be known
2833 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002834 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2835 << ValType << Ptr->getSourceRange();
2836 return ExprError();
2837 }
2838
David Majnemerc6eb6502015-06-03 00:26:35 +00002839 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2840 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00002841 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00002842 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00002843 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002844 QualType ResultType = ValType;
Eric Fiselier8d662442016-03-30 23:39:56 +00002845 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002846 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002847 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002848 ResultType = Context.BoolTy;
2849
Richard Smithfeea8832012-04-12 05:08:17 +00002850 // The type of a parameter passed 'by value'. In the GNU atomics, such
2851 // arguments are actually passed as pointers.
2852 QualType ByValType = ValType; // 'CP'
2853 if (!IsC11 && !IsN)
2854 ByValType = Ptr->getType();
2855
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002856 // The first argument --- the pointer --- has a fixed type; we
2857 // deduce the types of the rest of the arguments accordingly. Walk
2858 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002859 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002860 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002861 if (i < NumVals[Form] + 1) {
2862 switch (i) {
2863 case 1:
2864 // The second argument is the non-atomic operand. For arithmetic, this
2865 // is always passed by value, and for a compare_exchange it is always
2866 // passed by address. For the rest, GNU uses by-address and C11 uses
2867 // by-value.
2868 assert(Form != Load);
2869 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2870 Ty = ValType;
2871 else if (Form == Copy || Form == Xchg)
2872 Ty = ByValType;
2873 else if (Form == Arithmetic)
2874 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002875 else {
2876 Expr *ValArg = TheCall->getArg(i);
2877 unsigned AS = 0;
2878 // Keep address space of non-atomic pointer type.
2879 if (const PointerType *PtrTy =
2880 ValArg->getType()->getAs<PointerType>()) {
2881 AS = PtrTy->getPointeeType().getAddressSpace();
2882 }
2883 Ty = Context.getPointerType(
2884 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2885 }
Richard Smithfeea8832012-04-12 05:08:17 +00002886 break;
2887 case 2:
2888 // The third argument to compare_exchange / GNU exchange is a
2889 // (pointer to a) desired value.
2890 Ty = ByValType;
2891 break;
2892 case 3:
2893 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2894 Ty = Context.BoolTy;
2895 break;
2896 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002897 } else {
2898 // The order(s) are always converted to int.
2899 Ty = Context.IntTy;
2900 }
Richard Smithfeea8832012-04-12 05:08:17 +00002901
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002902 InitializedEntity Entity =
2903 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00002904 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002905 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2906 if (Arg.isInvalid())
2907 return true;
2908 TheCall->setArg(i, Arg.get());
2909 }
2910
Richard Smithfeea8832012-04-12 05:08:17 +00002911 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002912 SmallVector<Expr*, 5> SubExprs;
2913 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00002914 switch (Form) {
2915 case Init:
2916 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00002917 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002918 break;
2919 case Load:
2920 SubExprs.push_back(TheCall->getArg(1)); // Order
2921 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00002922 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00002923 case Copy:
2924 case Arithmetic:
2925 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002926 SubExprs.push_back(TheCall->getArg(2)); // Order
2927 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002928 break;
2929 case GNUXchg:
2930 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2931 SubExprs.push_back(TheCall->getArg(3)); // Order
2932 SubExprs.push_back(TheCall->getArg(1)); // Val1
2933 SubExprs.push_back(TheCall->getArg(2)); // Val2
2934 break;
2935 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002936 SubExprs.push_back(TheCall->getArg(3)); // Order
2937 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002938 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00002939 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00002940 break;
2941 case GNUCmpXchg:
2942 SubExprs.push_back(TheCall->getArg(4)); // Order
2943 SubExprs.push_back(TheCall->getArg(1)); // Val1
2944 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2945 SubExprs.push_back(TheCall->getArg(2)); // Val2
2946 SubExprs.push_back(TheCall->getArg(3)); // Weak
2947 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002948 }
Tim Northovere94a34c2014-03-11 10:49:14 +00002949
2950 if (SubExprs.size() >= 2 && Form != Init) {
2951 llvm::APSInt Result(32);
2952 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2953 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00002954 Diag(SubExprs[1]->getLocStart(),
2955 diag::warn_atomic_op_has_invalid_memory_order)
2956 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00002957 }
2958
Fariborz Jahanian615de762013-05-28 17:37:39 +00002959 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2960 SubExprs, ResultType, Op,
2961 TheCall->getRParenLoc());
2962
2963 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2964 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2965 Context.AtomicUsesUnsupportedLibcall(AE))
2966 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2967 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002968
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002969 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002970}
2971
John McCall29ad95b2011-08-27 01:09:30 +00002972/// checkBuiltinArgument - Given a call to a builtin function, perform
2973/// normal type-checking on the given argument, updating the call in
2974/// place. This is useful when a builtin function requires custom
2975/// type-checking for some of its arguments but not necessarily all of
2976/// them.
2977///
2978/// Returns true on error.
2979static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2980 FunctionDecl *Fn = E->getDirectCallee();
2981 assert(Fn && "builtin call without direct callee!");
2982
2983 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2984 InitializedEntity Entity =
2985 InitializedEntity::InitializeParameter(S.Context, Param);
2986
2987 ExprResult Arg = E->getArg(0);
2988 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2989 if (Arg.isInvalid())
2990 return true;
2991
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002992 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00002993 return false;
2994}
2995
Chris Lattnerdc046542009-05-08 06:58:22 +00002996/// SemaBuiltinAtomicOverloaded - We have a call to a function like
2997/// __sync_fetch_and_add, which is an overloaded function based on the pointer
2998/// type of its first argument. The main ActOnCallExpr routines have already
2999/// promoted the types of arguments because all of these calls are prototyped as
3000/// void(...).
3001///
3002/// This function goes through and does final semantic checking for these
3003/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003004ExprResult
3005Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003006 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003007 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3008 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3009
3010 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003011 if (TheCall->getNumArgs() < 1) {
3012 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3013 << 0 << 1 << TheCall->getNumArgs()
3014 << TheCall->getCallee()->getSourceRange();
3015 return ExprError();
3016 }
Mike Stump11289f42009-09-09 15:08:12 +00003017
Chris Lattnerdc046542009-05-08 06:58:22 +00003018 // Inspect the first argument of the atomic builtin. This should always be
3019 // a pointer type, whose element is an integral scalar or pointer type.
3020 // Because it is a pointer type, we don't have to worry about any implicit
3021 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003022 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003023 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003024 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3025 if (FirstArgResult.isInvalid())
3026 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003027 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003028 TheCall->setArg(0, FirstArg);
3029
John McCall31168b02011-06-15 23:02:42 +00003030 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3031 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003032 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3033 << FirstArg->getType() << FirstArg->getSourceRange();
3034 return ExprError();
3035 }
Mike Stump11289f42009-09-09 15:08:12 +00003036
John McCall31168b02011-06-15 23:02:42 +00003037 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003038 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003039 !ValType->isBlockPointerType()) {
3040 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3041 << FirstArg->getType() << FirstArg->getSourceRange();
3042 return ExprError();
3043 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003044
John McCall31168b02011-06-15 23:02:42 +00003045 switch (ValType.getObjCLifetime()) {
3046 case Qualifiers::OCL_None:
3047 case Qualifiers::OCL_ExplicitNone:
3048 // okay
3049 break;
3050
3051 case Qualifiers::OCL_Weak:
3052 case Qualifiers::OCL_Strong:
3053 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003054 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003055 << ValType << FirstArg->getSourceRange();
3056 return ExprError();
3057 }
3058
John McCallb50451a2011-10-05 07:41:44 +00003059 // Strip any qualifiers off ValType.
3060 ValType = ValType.getUnqualifiedType();
3061
Chandler Carruth3973af72010-07-18 20:54:12 +00003062 // The majority of builtins return a value, but a few have special return
3063 // types, so allow them to override appropriately below.
3064 QualType ResultType = ValType;
3065
Chris Lattnerdc046542009-05-08 06:58:22 +00003066 // We need to figure out which concrete builtin this maps onto. For example,
3067 // __sync_fetch_and_add with a 2 byte object turns into
3068 // __sync_fetch_and_add_2.
3069#define BUILTIN_ROW(x) \
3070 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3071 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003072
Chris Lattnerdc046542009-05-08 06:58:22 +00003073 static const unsigned BuiltinIndices[][5] = {
3074 BUILTIN_ROW(__sync_fetch_and_add),
3075 BUILTIN_ROW(__sync_fetch_and_sub),
3076 BUILTIN_ROW(__sync_fetch_and_or),
3077 BUILTIN_ROW(__sync_fetch_and_and),
3078 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003079 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003080
Chris Lattnerdc046542009-05-08 06:58:22 +00003081 BUILTIN_ROW(__sync_add_and_fetch),
3082 BUILTIN_ROW(__sync_sub_and_fetch),
3083 BUILTIN_ROW(__sync_and_and_fetch),
3084 BUILTIN_ROW(__sync_or_and_fetch),
3085 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003086 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003087
Chris Lattnerdc046542009-05-08 06:58:22 +00003088 BUILTIN_ROW(__sync_val_compare_and_swap),
3089 BUILTIN_ROW(__sync_bool_compare_and_swap),
3090 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003091 BUILTIN_ROW(__sync_lock_release),
3092 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003093 };
Mike Stump11289f42009-09-09 15:08:12 +00003094#undef BUILTIN_ROW
3095
Chris Lattnerdc046542009-05-08 06:58:22 +00003096 // Determine the index of the size.
3097 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003098 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003099 case 1: SizeIndex = 0; break;
3100 case 2: SizeIndex = 1; break;
3101 case 4: SizeIndex = 2; break;
3102 case 8: SizeIndex = 3; break;
3103 case 16: SizeIndex = 4; break;
3104 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003105 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3106 << FirstArg->getType() << FirstArg->getSourceRange();
3107 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003108 }
Mike Stump11289f42009-09-09 15:08:12 +00003109
Chris Lattnerdc046542009-05-08 06:58:22 +00003110 // Each of these builtins has one pointer argument, followed by some number of
3111 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3112 // that we ignore. Find out which row of BuiltinIndices to read from as well
3113 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003114 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003115 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003116 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003117 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003118 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003119 case Builtin::BI__sync_fetch_and_add:
3120 case Builtin::BI__sync_fetch_and_add_1:
3121 case Builtin::BI__sync_fetch_and_add_2:
3122 case Builtin::BI__sync_fetch_and_add_4:
3123 case Builtin::BI__sync_fetch_and_add_8:
3124 case Builtin::BI__sync_fetch_and_add_16:
3125 BuiltinIndex = 0;
3126 break;
3127
3128 case Builtin::BI__sync_fetch_and_sub:
3129 case Builtin::BI__sync_fetch_and_sub_1:
3130 case Builtin::BI__sync_fetch_and_sub_2:
3131 case Builtin::BI__sync_fetch_and_sub_4:
3132 case Builtin::BI__sync_fetch_and_sub_8:
3133 case Builtin::BI__sync_fetch_and_sub_16:
3134 BuiltinIndex = 1;
3135 break;
3136
3137 case Builtin::BI__sync_fetch_and_or:
3138 case Builtin::BI__sync_fetch_and_or_1:
3139 case Builtin::BI__sync_fetch_and_or_2:
3140 case Builtin::BI__sync_fetch_and_or_4:
3141 case Builtin::BI__sync_fetch_and_or_8:
3142 case Builtin::BI__sync_fetch_and_or_16:
3143 BuiltinIndex = 2;
3144 break;
3145
3146 case Builtin::BI__sync_fetch_and_and:
3147 case Builtin::BI__sync_fetch_and_and_1:
3148 case Builtin::BI__sync_fetch_and_and_2:
3149 case Builtin::BI__sync_fetch_and_and_4:
3150 case Builtin::BI__sync_fetch_and_and_8:
3151 case Builtin::BI__sync_fetch_and_and_16:
3152 BuiltinIndex = 3;
3153 break;
Mike Stump11289f42009-09-09 15:08:12 +00003154
Douglas Gregor73722482011-11-28 16:30:08 +00003155 case Builtin::BI__sync_fetch_and_xor:
3156 case Builtin::BI__sync_fetch_and_xor_1:
3157 case Builtin::BI__sync_fetch_and_xor_2:
3158 case Builtin::BI__sync_fetch_and_xor_4:
3159 case Builtin::BI__sync_fetch_and_xor_8:
3160 case Builtin::BI__sync_fetch_and_xor_16:
3161 BuiltinIndex = 4;
3162 break;
3163
Hal Finkeld2208b52014-10-02 20:53:50 +00003164 case Builtin::BI__sync_fetch_and_nand:
3165 case Builtin::BI__sync_fetch_and_nand_1:
3166 case Builtin::BI__sync_fetch_and_nand_2:
3167 case Builtin::BI__sync_fetch_and_nand_4:
3168 case Builtin::BI__sync_fetch_and_nand_8:
3169 case Builtin::BI__sync_fetch_and_nand_16:
3170 BuiltinIndex = 5;
3171 WarnAboutSemanticsChange = true;
3172 break;
3173
Douglas Gregor73722482011-11-28 16:30:08 +00003174 case Builtin::BI__sync_add_and_fetch:
3175 case Builtin::BI__sync_add_and_fetch_1:
3176 case Builtin::BI__sync_add_and_fetch_2:
3177 case Builtin::BI__sync_add_and_fetch_4:
3178 case Builtin::BI__sync_add_and_fetch_8:
3179 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003180 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003181 break;
3182
3183 case Builtin::BI__sync_sub_and_fetch:
3184 case Builtin::BI__sync_sub_and_fetch_1:
3185 case Builtin::BI__sync_sub_and_fetch_2:
3186 case Builtin::BI__sync_sub_and_fetch_4:
3187 case Builtin::BI__sync_sub_and_fetch_8:
3188 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003189 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003190 break;
3191
3192 case Builtin::BI__sync_and_and_fetch:
3193 case Builtin::BI__sync_and_and_fetch_1:
3194 case Builtin::BI__sync_and_and_fetch_2:
3195 case Builtin::BI__sync_and_and_fetch_4:
3196 case Builtin::BI__sync_and_and_fetch_8:
3197 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003198 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003199 break;
3200
3201 case Builtin::BI__sync_or_and_fetch:
3202 case Builtin::BI__sync_or_and_fetch_1:
3203 case Builtin::BI__sync_or_and_fetch_2:
3204 case Builtin::BI__sync_or_and_fetch_4:
3205 case Builtin::BI__sync_or_and_fetch_8:
3206 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003207 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003208 break;
3209
3210 case Builtin::BI__sync_xor_and_fetch:
3211 case Builtin::BI__sync_xor_and_fetch_1:
3212 case Builtin::BI__sync_xor_and_fetch_2:
3213 case Builtin::BI__sync_xor_and_fetch_4:
3214 case Builtin::BI__sync_xor_and_fetch_8:
3215 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003216 BuiltinIndex = 10;
3217 break;
3218
3219 case Builtin::BI__sync_nand_and_fetch:
3220 case Builtin::BI__sync_nand_and_fetch_1:
3221 case Builtin::BI__sync_nand_and_fetch_2:
3222 case Builtin::BI__sync_nand_and_fetch_4:
3223 case Builtin::BI__sync_nand_and_fetch_8:
3224 case Builtin::BI__sync_nand_and_fetch_16:
3225 BuiltinIndex = 11;
3226 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003227 break;
Mike Stump11289f42009-09-09 15:08:12 +00003228
Chris Lattnerdc046542009-05-08 06:58:22 +00003229 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003230 case Builtin::BI__sync_val_compare_and_swap_1:
3231 case Builtin::BI__sync_val_compare_and_swap_2:
3232 case Builtin::BI__sync_val_compare_and_swap_4:
3233 case Builtin::BI__sync_val_compare_and_swap_8:
3234 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003235 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003236 NumFixed = 2;
3237 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003238
Chris Lattnerdc046542009-05-08 06:58:22 +00003239 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003240 case Builtin::BI__sync_bool_compare_and_swap_1:
3241 case Builtin::BI__sync_bool_compare_and_swap_2:
3242 case Builtin::BI__sync_bool_compare_and_swap_4:
3243 case Builtin::BI__sync_bool_compare_and_swap_8:
3244 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003245 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003246 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003247 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003248 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003249
3250 case Builtin::BI__sync_lock_test_and_set:
3251 case Builtin::BI__sync_lock_test_and_set_1:
3252 case Builtin::BI__sync_lock_test_and_set_2:
3253 case Builtin::BI__sync_lock_test_and_set_4:
3254 case Builtin::BI__sync_lock_test_and_set_8:
3255 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003256 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003257 break;
3258
Chris Lattnerdc046542009-05-08 06:58:22 +00003259 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003260 case Builtin::BI__sync_lock_release_1:
3261 case Builtin::BI__sync_lock_release_2:
3262 case Builtin::BI__sync_lock_release_4:
3263 case Builtin::BI__sync_lock_release_8:
3264 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003265 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003266 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003267 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003268 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003269
3270 case Builtin::BI__sync_swap:
3271 case Builtin::BI__sync_swap_1:
3272 case Builtin::BI__sync_swap_2:
3273 case Builtin::BI__sync_swap_4:
3274 case Builtin::BI__sync_swap_8:
3275 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003276 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003277 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003278 }
Mike Stump11289f42009-09-09 15:08:12 +00003279
Chris Lattnerdc046542009-05-08 06:58:22 +00003280 // Now that we know how many fixed arguments we expect, first check that we
3281 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003282 if (TheCall->getNumArgs() < 1+NumFixed) {
3283 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3284 << 0 << 1+NumFixed << TheCall->getNumArgs()
3285 << TheCall->getCallee()->getSourceRange();
3286 return ExprError();
3287 }
Mike Stump11289f42009-09-09 15:08:12 +00003288
Hal Finkeld2208b52014-10-02 20:53:50 +00003289 if (WarnAboutSemanticsChange) {
3290 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3291 << TheCall->getCallee()->getSourceRange();
3292 }
3293
Chris Lattner5b9241b2009-05-08 15:36:58 +00003294 // Get the decl for the concrete builtin from this, we can tell what the
3295 // concrete integer type we should convert to is.
3296 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003297 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003298 FunctionDecl *NewBuiltinDecl;
3299 if (NewBuiltinID == BuiltinID)
3300 NewBuiltinDecl = FDecl;
3301 else {
3302 // Perform builtin lookup to avoid redeclaring it.
3303 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3304 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3305 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3306 assert(Res.getFoundDecl());
3307 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003308 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003309 return ExprError();
3310 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003311
John McCallcf142162010-08-07 06:22:56 +00003312 // The first argument --- the pointer --- has a fixed type; we
3313 // deduce the types of the rest of the arguments accordingly. Walk
3314 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003315 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003316 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003317
Chris Lattnerdc046542009-05-08 06:58:22 +00003318 // GCC does an implicit conversion to the pointer or integer ValType. This
3319 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003320 // Initialize the argument.
3321 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3322 ValType, /*consume*/ false);
3323 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003324 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003325 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003326
Chris Lattnerdc046542009-05-08 06:58:22 +00003327 // Okay, we have something that *can* be converted to the right type. Check
3328 // to see if there is a potentially weird extension going on here. This can
3329 // happen when you do an atomic operation on something like an char* and
3330 // pass in 42. The 42 gets converted to char. This is even more strange
3331 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003332 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003333 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003334 }
Mike Stump11289f42009-09-09 15:08:12 +00003335
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003336 ASTContext& Context = this->getASTContext();
3337
3338 // Create a new DeclRefExpr to refer to the new decl.
3339 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3340 Context,
3341 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003342 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003343 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003344 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003345 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003346 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003347 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003348
Chris Lattnerdc046542009-05-08 06:58:22 +00003349 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003350 // FIXME: This loses syntactic information.
3351 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3352 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3353 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003354 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003355
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003356 // Change the result type of the call to match the original value type. This
3357 // is arbitrary, but the codegen for these builtins ins design to handle it
3358 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003359 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003360
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003361 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003362}
3363
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003364/// SemaBuiltinNontemporalOverloaded - We have a call to
3365/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3366/// overloaded function based on the pointer type of its last argument.
3367///
3368/// This function goes through and does final semantic checking for these
3369/// builtins.
3370ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3371 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3372 DeclRefExpr *DRE =
3373 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3374 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3375 unsigned BuiltinID = FDecl->getBuiltinID();
3376 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3377 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3378 "Unexpected nontemporal load/store builtin!");
3379 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3380 unsigned numArgs = isStore ? 2 : 1;
3381
3382 // Ensure that we have the proper number of arguments.
3383 if (checkArgCount(*this, TheCall, numArgs))
3384 return ExprError();
3385
3386 // Inspect the last argument of the nontemporal builtin. This should always
3387 // be a pointer type, from which we imply the type of the memory access.
3388 // Because it is a pointer type, we don't have to worry about any implicit
3389 // casts here.
3390 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3391 ExprResult PointerArgResult =
3392 DefaultFunctionArrayLvalueConversion(PointerArg);
3393
3394 if (PointerArgResult.isInvalid())
3395 return ExprError();
3396 PointerArg = PointerArgResult.get();
3397 TheCall->setArg(numArgs - 1, PointerArg);
3398
3399 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3400 if (!pointerType) {
3401 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3402 << PointerArg->getType() << PointerArg->getSourceRange();
3403 return ExprError();
3404 }
3405
3406 QualType ValType = pointerType->getPointeeType();
3407
3408 // Strip any qualifiers off ValType.
3409 ValType = ValType.getUnqualifiedType();
3410 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3411 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3412 !ValType->isVectorType()) {
3413 Diag(DRE->getLocStart(),
3414 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3415 << PointerArg->getType() << PointerArg->getSourceRange();
3416 return ExprError();
3417 }
3418
3419 if (!isStore) {
3420 TheCall->setType(ValType);
3421 return TheCallResult;
3422 }
3423
3424 ExprResult ValArg = TheCall->getArg(0);
3425 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3426 Context, ValType, /*consume*/ false);
3427 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3428 if (ValArg.isInvalid())
3429 return ExprError();
3430
3431 TheCall->setArg(0, ValArg.get());
3432 TheCall->setType(Context.VoidTy);
3433 return TheCallResult;
3434}
3435
Chris Lattner6436fb62009-02-18 06:01:06 +00003436/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003437/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003438/// Note: It might also make sense to do the UTF-16 conversion here (would
3439/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003440bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003441 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003442 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3443
Douglas Gregorfb65e592011-07-27 05:40:30 +00003444 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003445 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3446 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003447 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003448 }
Mike Stump11289f42009-09-09 15:08:12 +00003449
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003450 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003451 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003452 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00003453 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3454 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3455 llvm::UTF16 *ToPtr = &ToBuf[0];
3456
3457 llvm::ConversionResult Result =
3458 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3459 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003460 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00003461 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003462 Diag(Arg->getLocStart(),
3463 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3464 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003465 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003466}
3467
Mehdi Amini06d367c2016-10-24 20:39:34 +00003468/// CheckObjCString - Checks that the format string argument to the os_log()
3469/// and os_trace() functions is correct, and converts it to const char *.
3470ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3471 Arg = Arg->IgnoreParenCasts();
3472 auto *Literal = dyn_cast<StringLiteral>(Arg);
3473 if (!Literal) {
3474 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3475 Literal = ObjcLiteral->getString();
3476 }
3477 }
3478
3479 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3480 return ExprError(
3481 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3482 << Arg->getSourceRange());
3483 }
3484
3485 ExprResult Result(Literal);
3486 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3487 InitializedEntity Entity =
3488 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3489 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3490 return Result;
3491}
3492
Charles Davisc7d5c942015-09-17 20:55:33 +00003493/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3494/// for validity. Emit an error and return true on failure; return false
3495/// on success.
3496bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003497 Expr *Fn = TheCall->getCallee();
3498 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003499 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003500 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003501 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3502 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003503 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003504 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003505 return true;
3506 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003507
3508 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003509 return Diag(TheCall->getLocEnd(),
3510 diag::err_typecheck_call_too_few_args_at_least)
3511 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003512 }
3513
John McCall29ad95b2011-08-27 01:09:30 +00003514 // Type-check the first argument normally.
3515 if (checkBuiltinArgument(*this, TheCall, 0))
3516 return true;
3517
Chris Lattnere202e6a2007-12-20 00:05:45 +00003518 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00003519 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00003520 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00003521 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00003522 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00003523 else if (FunctionDecl *FD = getCurFunctionDecl())
3524 isVariadic = FD->isVariadic();
3525 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00003526 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00003527
Chris Lattnere202e6a2007-12-20 00:05:45 +00003528 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003529 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3530 return true;
3531 }
Mike Stump11289f42009-09-09 15:08:12 +00003532
Chris Lattner43be2e62007-12-19 23:59:04 +00003533 // Verify that the second argument to the builtin is the last argument of the
3534 // current function or method.
3535 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003536 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003537
Nico Weber9eea7642013-05-24 23:31:57 +00003538 // These are valid if SecondArgIsLastNamedArgument is false after the next
3539 // block.
3540 QualType Type;
3541 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003542 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003543
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003544 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3545 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003546 // FIXME: This isn't correct for methods (results in bogus warning).
3547 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003548 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00003549 if (CurBlock)
David Majnemera3debed2016-06-24 05:33:44 +00003550 LastArg = CurBlock->TheDecl->parameters().back();
Steve Naroff439a3e42009-04-15 19:33:47 +00003551 else if (FunctionDecl *FD = getCurFunctionDecl())
David Majnemera3debed2016-06-24 05:33:44 +00003552 LastArg = FD->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003553 else
David Majnemera3debed2016-06-24 05:33:44 +00003554 LastArg = getCurMethodDecl()->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003555 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00003556
3557 Type = PV->getType();
3558 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003559 IsCRegister =
3560 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003561 }
3562 }
Mike Stump11289f42009-09-09 15:08:12 +00003563
Chris Lattner43be2e62007-12-19 23:59:04 +00003564 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003565 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003566 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003567 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00003568 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3569 // Promotable integers are UB, but enumerations need a bit of
3570 // extra checking to see what their promotable type actually is.
3571 if (!Type->isPromotableIntegerType())
3572 return false;
3573 if (!Type->isEnumeralType())
3574 return true;
3575 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3576 return !(ED &&
3577 Context.typesAreCompatible(ED->getPromotionType(), Type));
3578 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00003579 unsigned Reason = 0;
3580 if (Type->isReferenceType()) Reason = 1;
3581 else if (IsCRegister) Reason = 2;
3582 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003583 Diag(ParamLoc, diag::note_parameter_type) << Type;
3584 }
3585
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003586 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003587 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003588}
Chris Lattner43be2e62007-12-19 23:59:04 +00003589
Charles Davisc7d5c942015-09-17 20:55:33 +00003590/// Check the arguments to '__builtin_va_start' for validity, and that
3591/// it was called from a function of the native ABI.
3592/// Emit an error and return true on failure; return false on success.
3593bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3594 // On x86-64 Unix, don't allow this in Win64 ABI functions.
3595 // On x64 Windows, don't allow this in System V ABI functions.
3596 // (Yes, that means there's no corresponding way to support variadic
3597 // System V ABI functions on Windows.)
3598 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3599 unsigned OS = Context.getTargetInfo().getTriple().getOS();
3600 clang::CallingConv CC = CC_C;
3601 if (const FunctionDecl *FD = getCurFunctionDecl())
3602 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3603 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3604 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3605 return Diag(TheCall->getCallee()->getLocStart(),
3606 diag::err_va_start_used_in_wrong_abi_function)
3607 << (OS != llvm::Triple::Win32);
3608 }
3609 return SemaBuiltinVAStartImpl(TheCall);
3610}
3611
3612/// Check the arguments to '__builtin_ms_va_start' for validity, and that
3613/// it was called from a Win64 ABI function.
3614/// Emit an error and return true on failure; return false on success.
3615bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3616 // This only makes sense for x86-64.
3617 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3618 Expr *Callee = TheCall->getCallee();
3619 if (TT.getArch() != llvm::Triple::x86_64)
3620 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3621 // Don't allow this in System V ABI functions.
3622 clang::CallingConv CC = CC_C;
3623 if (const FunctionDecl *FD = getCurFunctionDecl())
3624 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3625 if (CC == CC_X86_64SysV ||
3626 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3627 return Diag(Callee->getLocStart(),
3628 diag::err_ms_va_start_used_in_sysv_function);
3629 return SemaBuiltinVAStartImpl(TheCall);
3630}
3631
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003632bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3633 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3634 // const char *named_addr);
3635
3636 Expr *Func = Call->getCallee();
3637
3638 if (Call->getNumArgs() < 3)
3639 return Diag(Call->getLocEnd(),
3640 diag::err_typecheck_call_too_few_args_at_least)
3641 << 0 /*function call*/ << 3 << Call->getNumArgs();
3642
3643 // Determine whether the current function is variadic or not.
3644 bool IsVariadic;
3645 if (BlockScopeInfo *CurBlock = getCurBlock())
3646 IsVariadic = CurBlock->TheDecl->isVariadic();
3647 else if (FunctionDecl *FD = getCurFunctionDecl())
3648 IsVariadic = FD->isVariadic();
3649 else if (ObjCMethodDecl *MD = getCurMethodDecl())
3650 IsVariadic = MD->isVariadic();
3651 else
3652 llvm_unreachable("unexpected statement type");
3653
3654 if (!IsVariadic) {
3655 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3656 return true;
3657 }
3658
3659 // Type-check the first argument normally.
3660 if (checkBuiltinArgument(*this, Call, 0))
3661 return true;
3662
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003663 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003664 unsigned ArgNo;
3665 QualType Type;
3666 } ArgumentTypes[] = {
3667 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3668 { 2, Context.getSizeType() },
3669 };
3670
3671 for (const auto &AT : ArgumentTypes) {
3672 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3673 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3674 continue;
3675 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3676 << Arg->getType() << AT.Type << 1 /* different class */
3677 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3678 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3679 }
3680
3681 return false;
3682}
3683
Chris Lattner2da14fb2007-12-20 00:26:33 +00003684/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3685/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003686bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3687 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003688 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003689 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003690 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003691 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003692 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003693 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003694 << SourceRange(TheCall->getArg(2)->getLocStart(),
3695 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003696
John Wiegley01296292011-04-08 18:41:53 +00003697 ExprResult OrigArg0 = TheCall->getArg(0);
3698 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003699
Chris Lattner2da14fb2007-12-20 00:26:33 +00003700 // Do standard promotions between the two arguments, returning their common
3701 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003702 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003703 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3704 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003705
3706 // Make sure any conversions are pushed back into the call; this is
3707 // type safe since unordered compare builtins are declared as "_Bool
3708 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003709 TheCall->setArg(0, OrigArg0.get());
3710 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003711
John Wiegley01296292011-04-08 18:41:53 +00003712 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003713 return false;
3714
Chris Lattner2da14fb2007-12-20 00:26:33 +00003715 // If the common type isn't a real floating type, then the arguments were
3716 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003717 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00003718 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003719 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00003720 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3721 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003722
Chris Lattner2da14fb2007-12-20 00:26:33 +00003723 return false;
3724}
3725
Benjamin Kramer634fc102010-02-15 22:42:31 +00003726/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3727/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00003728/// to check everything. We expect the last argument to be a floating point
3729/// value.
3730bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3731 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00003732 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003733 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00003734 if (TheCall->getNumArgs() > NumArgs)
3735 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003736 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003737 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00003738 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003739 (*(TheCall->arg_end()-1))->getLocEnd());
3740
Benjamin Kramer64aae502010-02-16 10:07:31 +00003741 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00003742
Eli Friedman7e4faac2009-08-31 20:06:00 +00003743 if (OrigArg->isTypeDependent())
3744 return false;
3745
Chris Lattner68784ef2010-05-06 05:50:07 +00003746 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00003747 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00003748 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003749 diag::err_typecheck_call_invalid_unary_fp)
3750 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003751
Chris Lattner68784ef2010-05-06 05:50:07 +00003752 // If this is an implicit conversion from float -> double, remove it.
3753 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3754 Expr *CastArg = Cast->getSubExpr();
3755 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3756 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
3757 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00003758 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00003759 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00003760 }
3761 }
3762
Eli Friedman7e4faac2009-08-31 20:06:00 +00003763 return false;
3764}
3765
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003766/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3767// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00003768ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00003769 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003770 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00003771 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00003772 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3773 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003774
Nate Begemana0110022010-06-08 00:16:34 +00003775 // Determine which of the following types of shufflevector we're checking:
3776 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00003777 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00003778 QualType resType = TheCall->getArg(0)->getType();
3779 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00003780
Douglas Gregorc25f7662009-05-19 22:10:17 +00003781 if (!TheCall->getArg(0)->isTypeDependent() &&
3782 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00003783 QualType LHSType = TheCall->getArg(0)->getType();
3784 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00003785
Craig Topperbaca3892013-07-29 06:47:04 +00003786 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3787 return ExprError(Diag(TheCall->getLocStart(),
3788 diag::err_shufflevector_non_vector)
3789 << SourceRange(TheCall->getArg(0)->getLocStart(),
3790 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003791
Nate Begemana0110022010-06-08 00:16:34 +00003792 numElements = LHSType->getAs<VectorType>()->getNumElements();
3793 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00003794
Nate Begemana0110022010-06-08 00:16:34 +00003795 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3796 // with mask. If so, verify that RHS is an integer vector type with the
3797 // same number of elts as lhs.
3798 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00003799 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00003800 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00003801 return ExprError(Diag(TheCall->getLocStart(),
3802 diag::err_shufflevector_incompatible_vector)
3803 << SourceRange(TheCall->getArg(1)->getLocStart(),
3804 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003805 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00003806 return ExprError(Diag(TheCall->getLocStart(),
3807 diag::err_shufflevector_incompatible_vector)
3808 << SourceRange(TheCall->getArg(0)->getLocStart(),
3809 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00003810 } else if (numElements != numResElements) {
3811 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00003812 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003813 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003814 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003815 }
3816
3817 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00003818 if (TheCall->getArg(i)->isTypeDependent() ||
3819 TheCall->getArg(i)->isValueDependent())
3820 continue;
3821
Nate Begemana0110022010-06-08 00:16:34 +00003822 llvm::APSInt Result(32);
3823 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3824 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003825 diag::err_shufflevector_nonconstant_argument)
3826 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003827
Craig Topper50ad5b72013-08-03 17:40:38 +00003828 // Allow -1 which will be translated to undef in the IR.
3829 if (Result.isSigned() && Result.isAllOnesValue())
3830 continue;
3831
Chris Lattner7ab824e2008-08-10 02:05:13 +00003832 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003833 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003834 diag::err_shufflevector_argument_too_large)
3835 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003836 }
3837
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003838 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003839
Chris Lattner7ab824e2008-08-10 02:05:13 +00003840 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003841 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00003842 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003843 }
3844
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003845 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3846 TheCall->getCallee()->getLocStart(),
3847 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003848}
Chris Lattner43be2e62007-12-19 23:59:04 +00003849
Hal Finkelc4d7c822013-09-18 03:29:45 +00003850/// SemaConvertVectorExpr - Handle __builtin_convertvector
3851ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3852 SourceLocation BuiltinLoc,
3853 SourceLocation RParenLoc) {
3854 ExprValueKind VK = VK_RValue;
3855 ExprObjectKind OK = OK_Ordinary;
3856 QualType DstTy = TInfo->getType();
3857 QualType SrcTy = E->getType();
3858
3859 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3860 return ExprError(Diag(BuiltinLoc,
3861 diag::err_convertvector_non_vector)
3862 << E->getSourceRange());
3863 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3864 return ExprError(Diag(BuiltinLoc,
3865 diag::err_convertvector_non_vector_type));
3866
3867 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3868 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3869 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3870 if (SrcElts != DstElts)
3871 return ExprError(Diag(BuiltinLoc,
3872 diag::err_convertvector_incompatible_vector)
3873 << E->getSourceRange());
3874 }
3875
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003876 return new (Context)
3877 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003878}
3879
Daniel Dunbarb7257262008-07-21 22:59:13 +00003880/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3881// This is declared to take (const void*, ...) and can take two
3882// optional constant int args.
3883bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003884 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003885
Chris Lattner3b054132008-11-19 05:08:23 +00003886 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003887 return Diag(TheCall->getLocEnd(),
3888 diag::err_typecheck_call_too_many_args_at_most)
3889 << 0 /*function call*/ << 3 << NumArgs
3890 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003891
3892 // Argument 0 is checked for us and the remaining arguments must be
3893 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003894 for (unsigned i = 1; i != NumArgs; ++i)
3895 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003896 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003897
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003898 return false;
3899}
3900
Hal Finkelf0417332014-07-17 14:25:55 +00003901/// SemaBuiltinAssume - Handle __assume (MS Extension).
3902// __assume does not evaluate its arguments, and should warn if its argument
3903// has side effects.
3904bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3905 Expr *Arg = TheCall->getArg(0);
3906 if (Arg->isInstantiationDependent()) return false;
3907
3908 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003909 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003910 << Arg->getSourceRange()
3911 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3912
3913 return false;
3914}
3915
David Majnemer86b1bfa2016-10-31 18:07:57 +00003916/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00003917/// as (size_t, size_t) where the second size_t must be a power of 2 greater
3918/// than 8.
3919bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
3920 // The alignment must be a constant integer.
3921 Expr *Arg = TheCall->getArg(1);
3922
3923 // We can't check the value of a dependent argument.
3924 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00003925 if (const auto *UE =
3926 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
3927 if (UE->getKind() == UETT_AlignOf)
3928 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
3929 << Arg->getSourceRange();
3930
David Majnemer51169932016-10-31 05:37:48 +00003931 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
3932
3933 if (!Result.isPowerOf2())
3934 return Diag(TheCall->getLocStart(),
3935 diag::err_alignment_not_power_of_two)
3936 << Arg->getSourceRange();
3937
3938 if (Result < Context.getCharWidth())
3939 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
3940 << (unsigned)Context.getCharWidth()
3941 << Arg->getSourceRange();
3942
3943 if (Result > INT32_MAX)
3944 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
3945 << INT32_MAX
3946 << Arg->getSourceRange();
3947 }
3948
3949 return false;
3950}
3951
3952/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00003953/// as (const void*, size_t, ...) and can take one optional constant int arg.
3954bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3955 unsigned NumArgs = TheCall->getNumArgs();
3956
3957 if (NumArgs > 3)
3958 return Diag(TheCall->getLocEnd(),
3959 diag::err_typecheck_call_too_many_args_at_most)
3960 << 0 /*function call*/ << 3 << NumArgs
3961 << TheCall->getSourceRange();
3962
3963 // The alignment must be a constant integer.
3964 Expr *Arg = TheCall->getArg(1);
3965
3966 // We can't check the value of a dependent argument.
3967 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3968 llvm::APSInt Result;
3969 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3970 return true;
3971
3972 if (!Result.isPowerOf2())
3973 return Diag(TheCall->getLocStart(),
3974 diag::err_alignment_not_power_of_two)
3975 << Arg->getSourceRange();
3976 }
3977
3978 if (NumArgs > 2) {
3979 ExprResult Arg(TheCall->getArg(2));
3980 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3981 Context.getSizeType(), false);
3982 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3983 if (Arg.isInvalid()) return true;
3984 TheCall->setArg(2, Arg.get());
3985 }
Hal Finkelf0417332014-07-17 14:25:55 +00003986
3987 return false;
3988}
3989
Mehdi Amini06d367c2016-10-24 20:39:34 +00003990bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
3991 unsigned BuiltinID =
3992 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
3993 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
3994
3995 unsigned NumArgs = TheCall->getNumArgs();
3996 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
3997 if (NumArgs < NumRequiredArgs) {
3998 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3999 << 0 /* function call */ << NumRequiredArgs << NumArgs
4000 << TheCall->getSourceRange();
4001 }
4002 if (NumArgs >= NumRequiredArgs + 0x100) {
4003 return Diag(TheCall->getLocEnd(),
4004 diag::err_typecheck_call_too_many_args_at_most)
4005 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4006 << TheCall->getSourceRange();
4007 }
4008 unsigned i = 0;
4009
4010 // For formatting call, check buffer arg.
4011 if (!IsSizeCall) {
4012 ExprResult Arg(TheCall->getArg(i));
4013 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4014 Context, Context.VoidPtrTy, false);
4015 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4016 if (Arg.isInvalid())
4017 return true;
4018 TheCall->setArg(i, Arg.get());
4019 i++;
4020 }
4021
4022 // Check string literal arg.
4023 unsigned FormatIdx = i;
4024 {
4025 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4026 if (Arg.isInvalid())
4027 return true;
4028 TheCall->setArg(i, Arg.get());
4029 i++;
4030 }
4031
4032 // Make sure variadic args are scalar.
4033 unsigned FirstDataArg = i;
4034 while (i < NumArgs) {
4035 ExprResult Arg = DefaultVariadicArgumentPromotion(
4036 TheCall->getArg(i), VariadicFunction, nullptr);
4037 if (Arg.isInvalid())
4038 return true;
4039 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4040 if (ArgSize.getQuantity() >= 0x100) {
4041 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4042 << i << (int)ArgSize.getQuantity() << 0xff
4043 << TheCall->getSourceRange();
4044 }
4045 TheCall->setArg(i, Arg.get());
4046 i++;
4047 }
4048
4049 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4050 // call to avoid duplicate diagnostics.
4051 if (!IsSizeCall) {
4052 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4053 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4054 bool Success = CheckFormatArguments(
4055 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4056 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4057 CheckedVarArgs);
4058 if (!Success)
4059 return true;
4060 }
4061
4062 if (IsSizeCall) {
4063 TheCall->setType(Context.getSizeType());
4064 } else {
4065 TheCall->setType(Context.VoidPtrTy);
4066 }
4067 return false;
4068}
4069
Eric Christopher8d0c6212010-04-17 02:26:23 +00004070/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4071/// TheCall is a constant expression.
4072bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4073 llvm::APSInt &Result) {
4074 Expr *Arg = TheCall->getArg(ArgNum);
4075 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4076 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4077
4078 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4079
4080 if (!Arg->isIntegerConstantExpr(Result, Context))
4081 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004082 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004083
Chris Lattnerd545ad12009-09-23 06:06:36 +00004084 return false;
4085}
4086
Richard Sandiford28940af2014-04-16 08:47:51 +00004087/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4088/// TheCall is a constant expression in the range [Low, High].
4089bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4090 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004091 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004092
4093 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004094 Expr *Arg = TheCall->getArg(ArgNum);
4095 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004096 return false;
4097
Eric Christopher8d0c6212010-04-17 02:26:23 +00004098 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004099 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004100 return true;
4101
Richard Sandiford28940af2014-04-16 08:47:51 +00004102 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004103 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004104 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004105
4106 return false;
4107}
4108
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004109/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4110/// TheCall is a constant expression is a multiple of Num..
4111bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4112 unsigned Num) {
4113 llvm::APSInt Result;
4114
4115 // We can't check the value of a dependent argument.
4116 Expr *Arg = TheCall->getArg(ArgNum);
4117 if (Arg->isTypeDependent() || Arg->isValueDependent())
4118 return false;
4119
4120 // Check constant-ness first.
4121 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4122 return true;
4123
4124 if (Result.getSExtValue() % Num != 0)
4125 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4126 << Num << Arg->getSourceRange();
4127
4128 return false;
4129}
4130
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004131/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4132/// TheCall is an ARM/AArch64 special register string literal.
4133bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4134 int ArgNum, unsigned ExpectedFieldNum,
4135 bool AllowName) {
4136 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4137 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4138 BuiltinID == ARM::BI__builtin_arm_rsr ||
4139 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4140 BuiltinID == ARM::BI__builtin_arm_wsr ||
4141 BuiltinID == ARM::BI__builtin_arm_wsrp;
4142 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4143 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4144 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4145 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4146 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4147 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4148 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4149
4150 // We can't check the value of a dependent argument.
4151 Expr *Arg = TheCall->getArg(ArgNum);
4152 if (Arg->isTypeDependent() || Arg->isValueDependent())
4153 return false;
4154
4155 // Check if the argument is a string literal.
4156 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4157 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4158 << Arg->getSourceRange();
4159
4160 // Check the type of special register given.
4161 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4162 SmallVector<StringRef, 6> Fields;
4163 Reg.split(Fields, ":");
4164
4165 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4166 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4167 << Arg->getSourceRange();
4168
4169 // If the string is the name of a register then we cannot check that it is
4170 // valid here but if the string is of one the forms described in ACLE then we
4171 // can check that the supplied fields are integers and within the valid
4172 // ranges.
4173 if (Fields.size() > 1) {
4174 bool FiveFields = Fields.size() == 5;
4175
4176 bool ValidString = true;
4177 if (IsARMBuiltin) {
4178 ValidString &= Fields[0].startswith_lower("cp") ||
4179 Fields[0].startswith_lower("p");
4180 if (ValidString)
4181 Fields[0] =
4182 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4183
4184 ValidString &= Fields[2].startswith_lower("c");
4185 if (ValidString)
4186 Fields[2] = Fields[2].drop_front(1);
4187
4188 if (FiveFields) {
4189 ValidString &= Fields[3].startswith_lower("c");
4190 if (ValidString)
4191 Fields[3] = Fields[3].drop_front(1);
4192 }
4193 }
4194
4195 SmallVector<int, 5> Ranges;
4196 if (FiveFields)
4197 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
4198 else
4199 Ranges.append({15, 7, 15});
4200
4201 for (unsigned i=0; i<Fields.size(); ++i) {
4202 int IntField;
4203 ValidString &= !Fields[i].getAsInteger(10, IntField);
4204 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4205 }
4206
4207 if (!ValidString)
4208 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4209 << Arg->getSourceRange();
4210
4211 } else if (IsAArch64Builtin && Fields.size() == 1) {
4212 // If the register name is one of those that appear in the condition below
4213 // and the special register builtin being used is one of the write builtins,
4214 // then we require that the argument provided for writing to the register
4215 // is an integer constant expression. This is because it will be lowered to
4216 // an MSR (immediate) instruction, so we need to know the immediate at
4217 // compile time.
4218 if (TheCall->getNumArgs() != 2)
4219 return false;
4220
4221 std::string RegLower = Reg.lower();
4222 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4223 RegLower != "pan" && RegLower != "uao")
4224 return false;
4225
4226 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4227 }
4228
4229 return false;
4230}
4231
Eli Friedmanc97d0142009-05-03 06:04:26 +00004232/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004233/// This checks that the target supports __builtin_longjmp and
4234/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004235bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004236 if (!Context.getTargetInfo().hasSjLjLowering())
4237 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4238 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4239
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004240 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004241 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004242
Eric Christopher8d0c6212010-04-17 02:26:23 +00004243 // TODO: This is less than ideal. Overload this to take a value.
4244 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4245 return true;
4246
4247 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004248 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4249 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4250
4251 return false;
4252}
4253
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004254/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4255/// This checks that the target supports __builtin_setjmp.
4256bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4257 if (!Context.getTargetInfo().hasSjLjLowering())
4258 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4259 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4260 return false;
4261}
4262
Richard Smithd7293d72013-08-05 18:49:43 +00004263namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004264class UncoveredArgHandler {
4265 enum { Unknown = -1, AllCovered = -2 };
4266 signed FirstUncoveredArg;
4267 SmallVector<const Expr *, 4> DiagnosticExprs;
4268
4269public:
4270 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4271
4272 bool hasUncoveredArg() const {
4273 return (FirstUncoveredArg >= 0);
4274 }
4275
4276 unsigned getUncoveredArg() const {
4277 assert(hasUncoveredArg() && "no uncovered argument");
4278 return FirstUncoveredArg;
4279 }
4280
4281 void setAllCovered() {
4282 // A string has been found with all arguments covered, so clear out
4283 // the diagnostics.
4284 DiagnosticExprs.clear();
4285 FirstUncoveredArg = AllCovered;
4286 }
4287
4288 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4289 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4290
4291 // Don't update if a previous string covers all arguments.
4292 if (FirstUncoveredArg == AllCovered)
4293 return;
4294
4295 // UncoveredArgHandler tracks the highest uncovered argument index
4296 // and with it all the strings that match this index.
4297 if (NewFirstUncoveredArg == FirstUncoveredArg)
4298 DiagnosticExprs.push_back(StrExpr);
4299 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4300 DiagnosticExprs.clear();
4301 DiagnosticExprs.push_back(StrExpr);
4302 FirstUncoveredArg = NewFirstUncoveredArg;
4303 }
4304 }
4305
4306 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4307};
4308
Richard Smithd7293d72013-08-05 18:49:43 +00004309enum StringLiteralCheckType {
4310 SLCT_NotALiteral,
4311 SLCT_UncheckedLiteral,
4312 SLCT_CheckedLiteral
4313};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004314} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00004315
Stephen Hines648c3692016-09-16 01:07:04 +00004316static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4317 BinaryOperatorKind BinOpKind,
4318 bool AddendIsRight) {
4319 unsigned BitWidth = Offset.getBitWidth();
4320 unsigned AddendBitWidth = Addend.getBitWidth();
4321 // There might be negative interim results.
4322 if (Addend.isUnsigned()) {
4323 Addend = Addend.zext(++AddendBitWidth);
4324 Addend.setIsSigned(true);
4325 }
4326 // Adjust the bit width of the APSInts.
4327 if (AddendBitWidth > BitWidth) {
4328 Offset = Offset.sext(AddendBitWidth);
4329 BitWidth = AddendBitWidth;
4330 } else if (BitWidth > AddendBitWidth) {
4331 Addend = Addend.sext(BitWidth);
4332 }
4333
4334 bool Ov = false;
4335 llvm::APSInt ResOffset = Offset;
4336 if (BinOpKind == BO_Add)
4337 ResOffset = Offset.sadd_ov(Addend, Ov);
4338 else {
4339 assert(AddendIsRight && BinOpKind == BO_Sub &&
4340 "operator must be add or sub with addend on the right");
4341 ResOffset = Offset.ssub_ov(Addend, Ov);
4342 }
4343
4344 // We add an offset to a pointer here so we should support an offset as big as
4345 // possible.
4346 if (Ov) {
4347 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00004348 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00004349 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4350 return;
4351 }
4352
4353 Offset = ResOffset;
4354}
4355
4356namespace {
4357// This is a wrapper class around StringLiteral to support offsetted string
4358// literals as format strings. It takes the offset into account when returning
4359// the string and its length or the source locations to display notes correctly.
4360class FormatStringLiteral {
4361 const StringLiteral *FExpr;
4362 int64_t Offset;
4363
4364 public:
4365 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4366 : FExpr(fexpr), Offset(Offset) {}
4367
4368 StringRef getString() const {
4369 return FExpr->getString().drop_front(Offset);
4370 }
4371
4372 unsigned getByteLength() const {
4373 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4374 }
4375 unsigned getLength() const { return FExpr->getLength() - Offset; }
4376 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4377
4378 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4379
4380 QualType getType() const { return FExpr->getType(); }
4381
4382 bool isAscii() const { return FExpr->isAscii(); }
4383 bool isWide() const { return FExpr->isWide(); }
4384 bool isUTF8() const { return FExpr->isUTF8(); }
4385 bool isUTF16() const { return FExpr->isUTF16(); }
4386 bool isUTF32() const { return FExpr->isUTF32(); }
4387 bool isPascal() const { return FExpr->isPascal(); }
4388
4389 SourceLocation getLocationOfByte(
4390 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4391 const TargetInfo &Target, unsigned *StartToken = nullptr,
4392 unsigned *StartTokenByteOffset = nullptr) const {
4393 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4394 StartToken, StartTokenByteOffset);
4395 }
4396
4397 SourceLocation getLocStart() const LLVM_READONLY {
4398 return FExpr->getLocStart().getLocWithOffset(Offset);
4399 }
4400 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4401};
4402} // end anonymous namespace
4403
4404static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004405 const Expr *OrigFormatExpr,
4406 ArrayRef<const Expr *> Args,
4407 bool HasVAListArg, unsigned format_idx,
4408 unsigned firstDataArg,
4409 Sema::FormatStringType Type,
4410 bool inFunctionCall,
4411 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004412 llvm::SmallBitVector &CheckedVarArgs,
4413 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004414
Richard Smith55ce3522012-06-25 20:30:08 +00004415// Determine if an expression is a string literal or constant string.
4416// If this function returns false on the arguments to a function expecting a
4417// format string, we will usually need to emit a warning.
4418// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00004419static StringLiteralCheckType
4420checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4421 bool HasVAListArg, unsigned format_idx,
4422 unsigned firstDataArg, Sema::FormatStringType Type,
4423 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004424 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004425 UncoveredArgHandler &UncoveredArg,
4426 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00004427 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00004428 assert(Offset.isSigned() && "invalid offset");
4429
Douglas Gregorc25f7662009-05-19 22:10:17 +00004430 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00004431 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004432
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004433 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00004434
Richard Smithd7293d72013-08-05 18:49:43 +00004435 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00004436 // Technically -Wformat-nonliteral does not warn about this case.
4437 // The behavior of printf and friends in this case is implementation
4438 // dependent. Ideally if the format string cannot be null then
4439 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00004440 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00004441
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004442 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00004443 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004444 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00004445 // The expression is a literal if both sub-expressions were, and it was
4446 // completely checked only if both sub-expressions were checked.
4447 const AbstractConditionalOperator *C =
4448 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004449
4450 // Determine whether it is necessary to check both sub-expressions, for
4451 // example, because the condition expression is a constant that can be
4452 // evaluated at compile time.
4453 bool CheckLeft = true, CheckRight = true;
4454
4455 bool Cond;
4456 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4457 if (Cond)
4458 CheckRight = false;
4459 else
4460 CheckLeft = false;
4461 }
4462
Stephen Hines648c3692016-09-16 01:07:04 +00004463 // We need to maintain the offsets for the right and the left hand side
4464 // separately to check if every possible indexed expression is a valid
4465 // string literal. They might have different offsets for different string
4466 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004467 StringLiteralCheckType Left;
4468 if (!CheckLeft)
4469 Left = SLCT_UncheckedLiteral;
4470 else {
4471 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4472 HasVAListArg, format_idx, firstDataArg,
4473 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004474 CheckedVarArgs, UncoveredArg, Offset);
4475 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004476 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004477 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004478 }
4479
Richard Smith55ce3522012-06-25 20:30:08 +00004480 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004481 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004482 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004483 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004484 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004485
4486 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004487 }
4488
4489 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00004490 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4491 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004492 }
4493
John McCallc07a0c72011-02-17 10:25:35 +00004494 case Stmt::OpaqueValueExprClass:
4495 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4496 E = src;
4497 goto tryAgain;
4498 }
Richard Smith55ce3522012-06-25 20:30:08 +00004499 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004500
Ted Kremeneka8890832011-02-24 23:03:04 +00004501 case Stmt::PredefinedExprClass:
4502 // While __func__, etc., are technically not string literals, they
4503 // cannot contain format specifiers and thus are not a security
4504 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004505 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004506
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004507 case Stmt::DeclRefExprClass: {
4508 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004509
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004510 // As an exception, do not flag errors for variables binding to
4511 // const string literals.
4512 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4513 bool isConstant = false;
4514 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004515
Richard Smithd7293d72013-08-05 18:49:43 +00004516 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4517 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004518 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004519 isConstant = T.isConstant(S.Context) &&
4520 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004521 } else if (T->isObjCObjectPointerType()) {
4522 // In ObjC, there is usually no "const ObjectPointer" type,
4523 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004524 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004525 }
Mike Stump11289f42009-09-09 15:08:12 +00004526
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004527 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004528 if (const Expr *Init = VD->getAnyInitializer()) {
4529 // Look through initializers like const char c[] = { "foo" }
4530 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4531 if (InitList->isStringLiteralInit())
4532 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4533 }
Richard Smithd7293d72013-08-05 18:49:43 +00004534 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004535 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004536 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004537 /*InFunctionCall*/ false, CheckedVarArgs,
4538 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004539 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004540 }
Mike Stump11289f42009-09-09 15:08:12 +00004541
Anders Carlssonb012ca92009-06-28 19:55:58 +00004542 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4543 // special check to see if the format string is a function parameter
4544 // of the function calling the printf function. If the function
4545 // has an attribute indicating it is a printf-like function, then we
4546 // should suppress warnings concerning non-literals being used in a call
4547 // to a vprintf function. For example:
4548 //
4549 // void
4550 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4551 // va_list ap;
4552 // va_start(ap, fmt);
4553 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4554 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00004555 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004556 if (HasVAListArg) {
4557 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4558 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4559 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004560 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004561 // adjust for implicit parameter
4562 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4563 if (MD->isInstance())
4564 ++PVIndex;
4565 // We also check if the formats are compatible.
4566 // We can't pass a 'scanf' string to a 'printf' function.
4567 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00004568 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00004569 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004570 }
4571 }
4572 }
4573 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004574 }
Mike Stump11289f42009-09-09 15:08:12 +00004575
Richard Smith55ce3522012-06-25 20:30:08 +00004576 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004577 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004578
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004579 case Stmt::CallExprClass:
4580 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004581 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004582 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4583 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4584 unsigned ArgIndex = FA->getFormatIdx();
4585 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4586 if (MD->isInstance())
4587 --ArgIndex;
4588 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00004589
Richard Smithd7293d72013-08-05 18:49:43 +00004590 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004591 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00004592 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004593 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004594 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4595 unsigned BuiltinID = FD->getBuiltinID();
4596 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4597 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4598 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00004599 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004600 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004601 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004602 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004603 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004604 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004605 }
4606 }
Mike Stump11289f42009-09-09 15:08:12 +00004607
Richard Smith55ce3522012-06-25 20:30:08 +00004608 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004609 }
Alex Lorenzd9007142016-10-24 09:42:34 +00004610 case Stmt::ObjCMessageExprClass: {
4611 const auto *ME = cast<ObjCMessageExpr>(E);
4612 if (const auto *ND = ME->getMethodDecl()) {
4613 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4614 unsigned ArgIndex = FA->getFormatIdx();
4615 const Expr *Arg = ME->getArg(ArgIndex - 1);
4616 return checkFormatStringExpr(
4617 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4618 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4619 }
4620 }
4621
4622 return SLCT_NotALiteral;
4623 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004624 case Stmt::ObjCStringLiteralClass:
4625 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00004626 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004627
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004628 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004629 StrE = ObjCFExpr->getString();
4630 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004631 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004632
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004633 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00004634 if (Offset.isNegative() || Offset > StrE->getLength()) {
4635 // TODO: It would be better to have an explicit warning for out of
4636 // bounds literals.
4637 return SLCT_NotALiteral;
4638 }
4639 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4640 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004641 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004642 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00004643 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004644 }
Mike Stump11289f42009-09-09 15:08:12 +00004645
Richard Smith55ce3522012-06-25 20:30:08 +00004646 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004647 }
Stephen Hines648c3692016-09-16 01:07:04 +00004648 case Stmt::BinaryOperatorClass: {
4649 llvm::APSInt LResult;
4650 llvm::APSInt RResult;
4651
4652 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4653
4654 // A string literal + an int offset is still a string literal.
4655 if (BinOp->isAdditiveOp()) {
4656 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4657 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4658
4659 if (LIsInt != RIsInt) {
4660 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4661
4662 if (LIsInt) {
4663 if (BinOpKind == BO_Add) {
4664 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4665 E = BinOp->getRHS();
4666 goto tryAgain;
4667 }
4668 } else {
4669 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4670 E = BinOp->getLHS();
4671 goto tryAgain;
4672 }
4673 }
Stephen Hines648c3692016-09-16 01:07:04 +00004674 }
George Burgess IVd273aab2016-09-22 00:00:26 +00004675
4676 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00004677 }
4678 case Stmt::UnaryOperatorClass: {
4679 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4680 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4681 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4682 llvm::APSInt IndexResult;
4683 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4684 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4685 E = ASE->getBase();
4686 goto tryAgain;
4687 }
4688 }
4689
4690 return SLCT_NotALiteral;
4691 }
Mike Stump11289f42009-09-09 15:08:12 +00004692
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004693 default:
Richard Smith55ce3522012-06-25 20:30:08 +00004694 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004695 }
4696}
4697
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004698Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00004699 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00004700 .Case("scanf", FST_Scanf)
4701 .Cases("printf", "printf0", FST_Printf)
4702 .Cases("NSString", "CFString", FST_NSString)
4703 .Case("strftime", FST_Strftime)
4704 .Case("strfmon", FST_Strfmon)
4705 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4706 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4707 .Case("os_trace", FST_OSLog)
4708 .Case("os_log", FST_OSLog)
4709 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004710}
4711
Jordan Rose3e0ec582012-07-19 18:10:23 +00004712/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00004713/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00004714/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004715bool Sema::CheckFormatArguments(const FormatAttr *Format,
4716 ArrayRef<const Expr *> Args,
4717 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004718 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004719 SourceLocation Loc, SourceRange Range,
4720 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00004721 FormatStringInfo FSI;
4722 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004723 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00004724 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00004725 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00004726 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004727}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00004728
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004729bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004730 bool HasVAListArg, unsigned format_idx,
4731 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004732 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004733 SourceLocation Loc, SourceRange Range,
4734 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004735 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004736 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004737 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00004738 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004739 }
Mike Stump11289f42009-09-09 15:08:12 +00004740
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004741 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004742
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004743 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00004744 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004745 // Dynamically generated format strings are difficult to
4746 // automatically vet at compile time. Requiring that format strings
4747 // are string literals: (1) permits the checking of format strings by
4748 // the compiler and thereby (2) can practically remove the source of
4749 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00004750
Mike Stump11289f42009-09-09 15:08:12 +00004751 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00004752 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00004753 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00004754 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004755 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00004756 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00004757 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4758 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004759 /*IsFunctionCall*/ true, CheckedVarArgs,
4760 UncoveredArg,
4761 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004762
4763 // Generate a diagnostic where an uncovered argument is detected.
4764 if (UncoveredArg.hasUncoveredArg()) {
4765 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4766 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4767 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4768 }
4769
Richard Smith55ce3522012-06-25 20:30:08 +00004770 if (CT != SLCT_NotALiteral)
4771 // Literal format string found, check done!
4772 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00004773
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004774 // Strftime is particular as it always uses a single 'time' argument,
4775 // so it is safe to pass a non-literal string.
4776 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00004777 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004778
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004779 // Do not emit diag when the string param is a macro expansion and the
4780 // format is either NSString or CFString. This is a hack to prevent
4781 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4782 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004783 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4784 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00004785 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004786
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004787 // If there are no arguments specified, warn with -Wformat-security, otherwise
4788 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004789 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00004790 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4791 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004792 switch (Type) {
4793 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004794 break;
4795 case FST_Kprintf:
4796 case FST_FreeBSDKPrintf:
4797 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00004798 Diag(FormatLoc, diag::note_format_security_fixit)
4799 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004800 break;
4801 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00004802 Diag(FormatLoc, diag::note_format_security_fixit)
4803 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004804 break;
4805 }
4806 } else {
4807 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004808 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004809 }
Richard Smith55ce3522012-06-25 20:30:08 +00004810 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004811}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004812
Ted Kremenekab278de2010-01-28 23:39:18 +00004813namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00004814class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4815protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00004816 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00004817 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00004818 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00004819 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00004820 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00004821 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00004822 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00004823 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004824 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00004825 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00004826 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00004827 bool usesPositionalArgs;
4828 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004829 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00004830 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00004831 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004832 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004833
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004834public:
Stephen Hines648c3692016-09-16 01:07:04 +00004835 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00004836 const Expr *origFormatExpr,
4837 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004838 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00004839 ArrayRef<const Expr *> Args, unsigned formatIdx,
4840 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004841 llvm::SmallBitVector &CheckedVarArgs,
4842 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00004843 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
4844 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
4845 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
4846 usesPositionalArgs(false), atFirstArg(true),
4847 inFunctionCall(inFunctionCall), CallType(callType),
4848 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00004849 CoveredArgs.resize(numDataArgs);
4850 CoveredArgs.reset();
4851 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004852
Ted Kremenek019d2242010-01-29 01:50:07 +00004853 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004854
Ted Kremenek02087932010-07-16 02:11:22 +00004855 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004856 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004857
Jordan Rose92303592012-09-08 04:00:03 +00004858 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004859 const analyze_format_string::FormatSpecifier &FS,
4860 const analyze_format_string::ConversionSpecifier &CS,
4861 const char *startSpecifier, unsigned specifierLen,
4862 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00004863
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004864 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004865 const analyze_format_string::FormatSpecifier &FS,
4866 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004867
4868 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004869 const analyze_format_string::ConversionSpecifier &CS,
4870 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004871
Craig Toppere14c0f82014-03-12 04:55:44 +00004872 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004873
Craig Toppere14c0f82014-03-12 04:55:44 +00004874 void HandleInvalidPosition(const char *startSpecifier,
4875 unsigned specifierLen,
4876 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004877
Craig Toppere14c0f82014-03-12 04:55:44 +00004878 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004879
Craig Toppere14c0f82014-03-12 04:55:44 +00004880 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004881
Richard Trieu03cf7b72011-10-28 00:41:25 +00004882 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00004883 static void
4884 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4885 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4886 bool IsStringLocation, Range StringRange,
4887 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004888
Ted Kremenek02087932010-07-16 02:11:22 +00004889protected:
Ted Kremenekce815422010-07-19 21:25:57 +00004890 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4891 const char *startSpec,
4892 unsigned specifierLen,
4893 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004894
4895 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4896 const char *startSpec,
4897 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00004898
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004899 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00004900 CharSourceRange getSpecifierRange(const char *startSpecifier,
4901 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00004902 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004903
Ted Kremenek5739de72010-01-29 01:06:55 +00004904 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004905
4906 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4907 const analyze_format_string::ConversionSpecifier &CS,
4908 const char *startSpecifier, unsigned specifierLen,
4909 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004910
4911 template <typename Range>
4912 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4913 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004914 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00004915};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004916} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004917
Ted Kremenek02087932010-07-16 02:11:22 +00004918SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00004919 return OrigFormatExpr->getSourceRange();
4920}
4921
Ted Kremenek02087932010-07-16 02:11:22 +00004922CharSourceRange CheckFormatHandler::
4923getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00004924 SourceLocation Start = getLocationOfByte(startSpecifier);
4925 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
4926
4927 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004928 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00004929
4930 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004931}
4932
Ted Kremenek02087932010-07-16 02:11:22 +00004933SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00004934 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
4935 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00004936}
4937
Ted Kremenek02087932010-07-16 02:11:22 +00004938void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4939 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00004940 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4941 getLocationOfByte(startSpecifier),
4942 /*IsStringLocation*/true,
4943 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00004944}
4945
Jordan Rose92303592012-09-08 04:00:03 +00004946void CheckFormatHandler::HandleInvalidLengthModifier(
4947 const analyze_format_string::FormatSpecifier &FS,
4948 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00004949 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00004950 using namespace analyze_format_string;
4951
4952 const LengthModifier &LM = FS.getLengthModifier();
4953 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4954
4955 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004956 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00004957 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004958 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004959 getLocationOfByte(LM.getStart()),
4960 /*IsStringLocation*/true,
4961 getSpecifierRange(startSpecifier, specifierLen));
4962
4963 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4964 << FixedLM->toString()
4965 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4966
4967 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004968 FixItHint Hint;
4969 if (DiagID == diag::warn_format_nonsensical_length)
4970 Hint = FixItHint::CreateRemoval(LMRange);
4971
4972 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004973 getLocationOfByte(LM.getStart()),
4974 /*IsStringLocation*/true,
4975 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00004976 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00004977 }
4978}
4979
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004980void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00004981 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004982 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004983 using namespace analyze_format_string;
4984
4985 const LengthModifier &LM = FS.getLengthModifier();
4986 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4987
4988 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004989 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00004990 if (FixedLM) {
4991 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4992 << LM.toString() << 0,
4993 getLocationOfByte(LM.getStart()),
4994 /*IsStringLocation*/true,
4995 getSpecifierRange(startSpecifier, specifierLen));
4996
4997 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4998 << FixedLM->toString()
4999 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5000
5001 } else {
5002 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5003 << LM.toString() << 0,
5004 getLocationOfByte(LM.getStart()),
5005 /*IsStringLocation*/true,
5006 getSpecifierRange(startSpecifier, specifierLen));
5007 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005008}
5009
5010void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5011 const analyze_format_string::ConversionSpecifier &CS,
5012 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005013 using namespace analyze_format_string;
5014
5015 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005016 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005017 if (FixedCS) {
5018 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5019 << CS.toString() << /*conversion specifier*/1,
5020 getLocationOfByte(CS.getStart()),
5021 /*IsStringLocation*/true,
5022 getSpecifierRange(startSpecifier, specifierLen));
5023
5024 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5025 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5026 << FixedCS->toString()
5027 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5028 } else {
5029 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5030 << CS.toString() << /*conversion specifier*/1,
5031 getLocationOfByte(CS.getStart()),
5032 /*IsStringLocation*/true,
5033 getSpecifierRange(startSpecifier, specifierLen));
5034 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005035}
5036
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005037void CheckFormatHandler::HandlePosition(const char *startPos,
5038 unsigned posLen) {
5039 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5040 getLocationOfByte(startPos),
5041 /*IsStringLocation*/true,
5042 getSpecifierRange(startPos, posLen));
5043}
5044
Ted Kremenekd1668192010-02-27 01:41:03 +00005045void
Ted Kremenek02087932010-07-16 02:11:22 +00005046CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5047 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005048 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5049 << (unsigned) p,
5050 getLocationOfByte(startPos), /*IsStringLocation*/true,
5051 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005052}
5053
Ted Kremenek02087932010-07-16 02:11:22 +00005054void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005055 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005056 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5057 getLocationOfByte(startPos),
5058 /*IsStringLocation*/true,
5059 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005060}
5061
Ted Kremenek02087932010-07-16 02:11:22 +00005062void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005063 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005064 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005065 EmitFormatDiagnostic(
5066 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5067 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5068 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005069 }
Ted Kremenek02087932010-07-16 02:11:22 +00005070}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005071
Jordan Rose58bbe422012-07-19 18:10:08 +00005072// Note that this may return NULL if there was an error parsing or building
5073// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005074const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005075 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005076}
5077
5078void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005079 // Does the number of data arguments exceed the number of
5080 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005081 if (!HasVAListArg) {
5082 // Find any arguments that weren't covered.
5083 CoveredArgs.flip();
5084 signed notCoveredArg = CoveredArgs.find_first();
5085 if (notCoveredArg >= 0) {
5086 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005087 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5088 } else {
5089 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005090 }
5091 }
5092}
5093
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005094void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5095 const Expr *ArgExpr) {
5096 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5097 "Invalid state");
5098
5099 if (!ArgExpr)
5100 return;
5101
5102 SourceLocation Loc = ArgExpr->getLocStart();
5103
5104 if (S.getSourceManager().isInSystemMacro(Loc))
5105 return;
5106
5107 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5108 for (auto E : DiagnosticExprs)
5109 PDiag << E->getSourceRange();
5110
5111 CheckFormatHandler::EmitFormatDiagnostic(
5112 S, IsFunctionCall, DiagnosticExprs[0],
5113 PDiag, Loc, /*IsStringLocation*/false,
5114 DiagnosticExprs[0]->getSourceRange());
5115}
5116
Ted Kremenekce815422010-07-19 21:25:57 +00005117bool
5118CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5119 SourceLocation Loc,
5120 const char *startSpec,
5121 unsigned specifierLen,
5122 const char *csStart,
5123 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005124 bool keepGoing = true;
5125 if (argIndex < NumDataArgs) {
5126 // Consider the argument coverered, even though the specifier doesn't
5127 // make sense.
5128 CoveredArgs.set(argIndex);
5129 }
5130 else {
5131 // If argIndex exceeds the number of data arguments we
5132 // don't issue a warning because that is just a cascade of warnings (and
5133 // they may have intended '%%' anyway). We don't want to continue processing
5134 // the format string after this point, however, as we will like just get
5135 // gibberish when trying to match arguments.
5136 keepGoing = false;
5137 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005138
5139 StringRef Specifier(csStart, csLen);
5140
5141 // If the specifier in non-printable, it could be the first byte of a UTF-8
5142 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5143 // hex value.
5144 std::string CodePointStr;
5145 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005146 llvm::UTF32 CodePoint;
5147 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5148 const llvm::UTF8 *E =
5149 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5150 llvm::ConversionResult Result =
5151 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005152
Justin Lebar90910552016-09-30 00:38:45 +00005153 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005154 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005155 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005156 }
5157
5158 llvm::raw_string_ostream OS(CodePointStr);
5159 if (CodePoint < 256)
5160 OS << "\\x" << llvm::format("%02x", CodePoint);
5161 else if (CodePoint <= 0xFFFF)
5162 OS << "\\u" << llvm::format("%04x", CodePoint);
5163 else
5164 OS << "\\U" << llvm::format("%08x", CodePoint);
5165 OS.flush();
5166 Specifier = CodePointStr;
5167 }
5168
5169 EmitFormatDiagnostic(
5170 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5171 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5172
Ted Kremenekce815422010-07-19 21:25:57 +00005173 return keepGoing;
5174}
5175
Richard Trieu03cf7b72011-10-28 00:41:25 +00005176void
5177CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5178 const char *startSpec,
5179 unsigned specifierLen) {
5180 EmitFormatDiagnostic(
5181 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5182 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5183}
5184
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005185bool
5186CheckFormatHandler::CheckNumArgs(
5187 const analyze_format_string::FormatSpecifier &FS,
5188 const analyze_format_string::ConversionSpecifier &CS,
5189 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5190
5191 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005192 PartialDiagnostic PDiag = FS.usesPositionalArg()
5193 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5194 << (argIndex+1) << NumDataArgs)
5195 : S.PDiag(diag::warn_printf_insufficient_data_args);
5196 EmitFormatDiagnostic(
5197 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5198 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005199
5200 // Since more arguments than conversion tokens are given, by extension
5201 // all arguments are covered, so mark this as so.
5202 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005203 return false;
5204 }
5205 return true;
5206}
5207
Richard Trieu03cf7b72011-10-28 00:41:25 +00005208template<typename Range>
5209void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5210 SourceLocation Loc,
5211 bool IsStringLocation,
5212 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005213 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005214 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005215 Loc, IsStringLocation, StringRange, FixIt);
5216}
5217
5218/// \brief If the format string is not within the funcion call, emit a note
5219/// so that the function call and string are in diagnostic messages.
5220///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005221/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005222/// call and only one diagnostic message will be produced. Otherwise, an
5223/// extra note will be emitted pointing to location of the format string.
5224///
5225/// \param ArgumentExpr the expression that is passed as the format string
5226/// argument in the function call. Used for getting locations when two
5227/// diagnostics are emitted.
5228///
5229/// \param PDiag the callee should already have provided any strings for the
5230/// diagnostic message. This function only adds locations and fixits
5231/// to diagnostics.
5232///
5233/// \param Loc primary location for diagnostic. If two diagnostics are
5234/// required, one will be at Loc and a new SourceLocation will be created for
5235/// the other one.
5236///
5237/// \param IsStringLocation if true, Loc points to the format string should be
5238/// used for the note. Otherwise, Loc points to the argument list and will
5239/// be used with PDiag.
5240///
5241/// \param StringRange some or all of the string to highlight. This is
5242/// templated so it can accept either a CharSourceRange or a SourceRange.
5243///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005244/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005245template <typename Range>
5246void CheckFormatHandler::EmitFormatDiagnostic(
5247 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5248 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5249 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005250 if (InFunctionCall) {
5251 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5252 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005253 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00005254 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005255 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5256 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00005257
5258 const Sema::SemaDiagnosticBuilder &Note =
5259 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5260 diag::note_format_string_defined);
5261
5262 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005263 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005264 }
5265}
5266
Ted Kremenek02087932010-07-16 02:11:22 +00005267//===--- CHECK: Printf format string checking ------------------------------===//
5268
5269namespace {
5270class CheckPrintfHandler : public CheckFormatHandler {
5271public:
Stephen Hines648c3692016-09-16 01:07:04 +00005272 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005273 const Expr *origFormatExpr,
5274 const Sema::FormatStringType type, unsigned firstDataArg,
5275 unsigned numDataArgs, bool isObjC, const char *beg,
5276 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005277 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005278 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005279 llvm::SmallBitVector &CheckedVarArgs,
5280 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005281 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5282 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5283 inFunctionCall, CallType, CheckedVarArgs,
5284 UncoveredArg) {}
5285
5286 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5287
5288 /// Returns true if '%@' specifiers are allowed in the format string.
5289 bool allowsObjCArg() const {
5290 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5291 FSType == Sema::FST_OSTrace;
5292 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00005293
Ted Kremenek02087932010-07-16 02:11:22 +00005294 bool HandleInvalidPrintfConversionSpecifier(
5295 const analyze_printf::PrintfSpecifier &FS,
5296 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005297 unsigned specifierLen) override;
5298
Ted Kremenek02087932010-07-16 02:11:22 +00005299 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5300 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005301 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005302 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5303 const char *StartSpecifier,
5304 unsigned SpecifierLen,
5305 const Expr *E);
5306
Ted Kremenek02087932010-07-16 02:11:22 +00005307 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5308 const char *startSpecifier, unsigned specifierLen);
5309 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5310 const analyze_printf::OptionalAmount &Amt,
5311 unsigned type,
5312 const char *startSpecifier, unsigned specifierLen);
5313 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5314 const analyze_printf::OptionalFlag &flag,
5315 const char *startSpecifier, unsigned specifierLen);
5316 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5317 const analyze_printf::OptionalFlag &ignoredFlag,
5318 const analyze_printf::OptionalFlag &flag,
5319 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005320 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00005321 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00005322
5323 void HandleEmptyObjCModifierFlag(const char *startFlag,
5324 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005325
Ted Kremenek2b417712015-07-02 05:39:16 +00005326 void HandleInvalidObjCModifierFlag(const char *startFlag,
5327 unsigned flagLen) override;
5328
5329 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5330 const char *flagsEnd,
5331 const char *conversionPosition)
5332 override;
5333};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005334} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00005335
5336bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5337 const analyze_printf::PrintfSpecifier &FS,
5338 const char *startSpecifier,
5339 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005340 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005341 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005342
Ted Kremenekce815422010-07-19 21:25:57 +00005343 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5344 getLocationOfByte(CS.getStart()),
5345 startSpecifier, specifierLen,
5346 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00005347}
5348
Ted Kremenek02087932010-07-16 02:11:22 +00005349bool CheckPrintfHandler::HandleAmount(
5350 const analyze_format_string::OptionalAmount &Amt,
5351 unsigned k, const char *startSpecifier,
5352 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005353 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005354 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00005355 unsigned argIndex = Amt.getArgIndex();
5356 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005357 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5358 << k,
5359 getLocationOfByte(Amt.getStart()),
5360 /*IsStringLocation*/true,
5361 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005362 // Don't do any more checking. We will just emit
5363 // spurious errors.
5364 return false;
5365 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005366
Ted Kremenek5739de72010-01-29 01:06:55 +00005367 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00005368 // Although not in conformance with C99, we also allow the argument to be
5369 // an 'unsigned int' as that is a reasonably safe case. GCC also
5370 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00005371 CoveredArgs.set(argIndex);
5372 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005373 if (!Arg)
5374 return false;
5375
Ted Kremenek5739de72010-01-29 01:06:55 +00005376 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005377
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005378 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5379 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005380
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005381 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005382 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005383 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00005384 << T << Arg->getSourceRange(),
5385 getLocationOfByte(Amt.getStart()),
5386 /*IsStringLocation*/true,
5387 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005388 // Don't do any more checking. We will just emit
5389 // spurious errors.
5390 return false;
5391 }
5392 }
5393 }
5394 return true;
5395}
Ted Kremenek5739de72010-01-29 01:06:55 +00005396
Tom Careb49ec692010-06-17 19:00:27 +00005397void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00005398 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005399 const analyze_printf::OptionalAmount &Amt,
5400 unsigned type,
5401 const char *startSpecifier,
5402 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005403 const analyze_printf::PrintfConversionSpecifier &CS =
5404 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00005405
Richard Trieu03cf7b72011-10-28 00:41:25 +00005406 FixItHint fixit =
5407 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5408 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5409 Amt.getConstantLength()))
5410 : FixItHint();
5411
5412 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5413 << type << CS.toString(),
5414 getLocationOfByte(Amt.getStart()),
5415 /*IsStringLocation*/true,
5416 getSpecifierRange(startSpecifier, specifierLen),
5417 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00005418}
5419
Ted Kremenek02087932010-07-16 02:11:22 +00005420void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005421 const analyze_printf::OptionalFlag &flag,
5422 const char *startSpecifier,
5423 unsigned specifierLen) {
5424 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005425 const analyze_printf::PrintfConversionSpecifier &CS =
5426 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00005427 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5428 << flag.toString() << CS.toString(),
5429 getLocationOfByte(flag.getPosition()),
5430 /*IsStringLocation*/true,
5431 getSpecifierRange(startSpecifier, specifierLen),
5432 FixItHint::CreateRemoval(
5433 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005434}
5435
5436void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00005437 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005438 const analyze_printf::OptionalFlag &ignoredFlag,
5439 const analyze_printf::OptionalFlag &flag,
5440 const char *startSpecifier,
5441 unsigned specifierLen) {
5442 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005443 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5444 << ignoredFlag.toString() << flag.toString(),
5445 getLocationOfByte(ignoredFlag.getPosition()),
5446 /*IsStringLocation*/true,
5447 getSpecifierRange(startSpecifier, specifierLen),
5448 FixItHint::CreateRemoval(
5449 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005450}
5451
Ted Kremenek2b417712015-07-02 05:39:16 +00005452// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5453// bool IsStringLocation, Range StringRange,
5454// ArrayRef<FixItHint> Fixit = None);
5455
5456void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5457 unsigned flagLen) {
5458 // Warn about an empty flag.
5459 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5460 getLocationOfByte(startFlag),
5461 /*IsStringLocation*/true,
5462 getSpecifierRange(startFlag, flagLen));
5463}
5464
5465void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5466 unsigned flagLen) {
5467 // Warn about an invalid flag.
5468 auto Range = getSpecifierRange(startFlag, flagLen);
5469 StringRef flag(startFlag, flagLen);
5470 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5471 getLocationOfByte(startFlag),
5472 /*IsStringLocation*/true,
5473 Range, FixItHint::CreateRemoval(Range));
5474}
5475
5476void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5477 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5478 // Warn about using '[...]' without a '@' conversion.
5479 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5480 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5481 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5482 getLocationOfByte(conversionPosition),
5483 /*IsStringLocation*/true,
5484 Range, FixItHint::CreateRemoval(Range));
5485}
5486
Richard Smith55ce3522012-06-25 20:30:08 +00005487// Determines if the specified is a C++ class or struct containing
5488// a member with the specified name and kind (e.g. a CXXMethodDecl named
5489// "c_str()").
5490template<typename MemberKind>
5491static llvm::SmallPtrSet<MemberKind*, 1>
5492CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5493 const RecordType *RT = Ty->getAs<RecordType>();
5494 llvm::SmallPtrSet<MemberKind*, 1> Results;
5495
5496 if (!RT)
5497 return Results;
5498 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005499 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005500 return Results;
5501
Alp Tokerb6cc5922014-05-03 03:45:55 +00005502 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005503 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005504 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005505
5506 // We just need to include all members of the right kind turned up by the
5507 // filter, at this point.
5508 if (S.LookupQualifiedName(R, RT->getDecl()))
5509 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5510 NamedDecl *decl = (*I)->getUnderlyingDecl();
5511 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5512 Results.insert(FK);
5513 }
5514 return Results;
5515}
5516
Richard Smith2868a732014-02-28 01:36:39 +00005517/// Check if we could call '.c_str()' on an object.
5518///
5519/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5520/// allow the call, or if it would be ambiguous).
5521bool Sema::hasCStrMethod(const Expr *E) {
5522 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5523 MethodSet Results =
5524 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5525 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5526 MI != ME; ++MI)
5527 if ((*MI)->getMinRequiredArguments() == 0)
5528 return true;
5529 return false;
5530}
5531
Richard Smith55ce3522012-06-25 20:30:08 +00005532// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005533// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00005534// Returns true when a c_str() conversion method is found.
5535bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00005536 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00005537 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5538
5539 MethodSet Results =
5540 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5541
5542 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5543 MI != ME; ++MI) {
5544 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00005545 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00005546 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00005547 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00005548 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00005549 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5550 << "c_str()"
5551 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5552 return true;
5553 }
5554 }
5555
5556 return false;
5557}
5558
Ted Kremenekab278de2010-01-28 23:39:18 +00005559bool
Ted Kremenek02087932010-07-16 02:11:22 +00005560CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00005561 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00005562 const char *startSpecifier,
5563 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005564 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00005565 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005566 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00005567
Ted Kremenek6cd69422010-07-19 22:01:06 +00005568 if (FS.consumesDataArgument()) {
5569 if (atFirstArg) {
5570 atFirstArg = false;
5571 usesPositionalArgs = FS.usesPositionalArg();
5572 }
5573 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005574 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5575 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005576 return false;
5577 }
Ted Kremenek5739de72010-01-29 01:06:55 +00005578 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005579
Ted Kremenekd1668192010-02-27 01:41:03 +00005580 // First check if the field width, precision, and conversion specifier
5581 // have matching data arguments.
5582 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5583 startSpecifier, specifierLen)) {
5584 return false;
5585 }
5586
5587 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5588 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005589 return false;
5590 }
5591
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005592 if (!CS.consumesDataArgument()) {
5593 // FIXME: Technically specifying a precision or field width here
5594 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00005595 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005596 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005597
Ted Kremenek4a49d982010-02-26 19:18:41 +00005598 // Consume the argument.
5599 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00005600 if (argIndex < NumDataArgs) {
5601 // The check to see if the argIndex is valid will come later.
5602 // We set the bit here because we may exit early from this
5603 // function if we encounter some other error.
5604 CoveredArgs.set(argIndex);
5605 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00005606
Dimitry Andric6b5ed342015-02-19 22:32:33 +00005607 // FreeBSD kernel extensions.
5608 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5609 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5610 // We need at least two arguments.
5611 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5612 return false;
5613
5614 // Claim the second argument.
5615 CoveredArgs.set(argIndex + 1);
5616
5617 // Type check the first argument (int for %b, pointer for %D)
5618 const Expr *Ex = getDataArg(argIndex);
5619 const analyze_printf::ArgType &AT =
5620 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5621 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5622 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5623 EmitFormatDiagnostic(
5624 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5625 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5626 << false << Ex->getSourceRange(),
5627 Ex->getLocStart(), /*IsStringLocation*/false,
5628 getSpecifierRange(startSpecifier, specifierLen));
5629
5630 // Type check the second argument (char * for both %b and %D)
5631 Ex = getDataArg(argIndex + 1);
5632 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5633 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5634 EmitFormatDiagnostic(
5635 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5636 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5637 << false << Ex->getSourceRange(),
5638 Ex->getLocStart(), /*IsStringLocation*/false,
5639 getSpecifierRange(startSpecifier, specifierLen));
5640
5641 return true;
5642 }
5643
Ted Kremenek4a49d982010-02-26 19:18:41 +00005644 // Check for using an Objective-C specific conversion specifier
5645 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00005646 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00005647 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5648 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00005649 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005650
Mehdi Amini06d367c2016-10-24 20:39:34 +00005651 // %P can only be used with os_log.
5652 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
5653 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5654 specifierLen);
5655 }
5656
5657 // %n is not allowed with os_log.
5658 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
5659 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
5660 getLocationOfByte(CS.getStart()),
5661 /*IsStringLocation*/ false,
5662 getSpecifierRange(startSpecifier, specifierLen));
5663
5664 return true;
5665 }
5666
5667 // Only scalars are allowed for os_trace.
5668 if (FSType == Sema::FST_OSTrace &&
5669 (CS.getKind() == ConversionSpecifier::PArg ||
5670 CS.getKind() == ConversionSpecifier::sArg ||
5671 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
5672 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5673 specifierLen);
5674 }
5675
5676 // Check for use of public/private annotation outside of os_log().
5677 if (FSType != Sema::FST_OSLog) {
5678 if (FS.isPublic().isSet()) {
5679 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5680 << "public",
5681 getLocationOfByte(FS.isPublic().getPosition()),
5682 /*IsStringLocation*/ false,
5683 getSpecifierRange(startSpecifier, specifierLen));
5684 }
5685 if (FS.isPrivate().isSet()) {
5686 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5687 << "private",
5688 getLocationOfByte(FS.isPrivate().getPosition()),
5689 /*IsStringLocation*/ false,
5690 getSpecifierRange(startSpecifier, specifierLen));
5691 }
5692 }
5693
Tom Careb49ec692010-06-17 19:00:27 +00005694 // Check for invalid use of field width
5695 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00005696 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00005697 startSpecifier, specifierLen);
5698 }
5699
5700 // Check for invalid use of precision
5701 if (!FS.hasValidPrecision()) {
5702 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5703 startSpecifier, specifierLen);
5704 }
5705
Mehdi Amini06d367c2016-10-24 20:39:34 +00005706 // Precision is mandatory for %P specifier.
5707 if (CS.getKind() == ConversionSpecifier::PArg &&
5708 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
5709 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
5710 getLocationOfByte(startSpecifier),
5711 /*IsStringLocation*/ false,
5712 getSpecifierRange(startSpecifier, specifierLen));
5713 }
5714
Tom Careb49ec692010-06-17 19:00:27 +00005715 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00005716 if (!FS.hasValidThousandsGroupingPrefix())
5717 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005718 if (!FS.hasValidLeadingZeros())
5719 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5720 if (!FS.hasValidPlusPrefix())
5721 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00005722 if (!FS.hasValidSpacePrefix())
5723 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005724 if (!FS.hasValidAlternativeForm())
5725 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5726 if (!FS.hasValidLeftJustified())
5727 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5728
5729 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00005730 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5731 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5732 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005733 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5734 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5735 startSpecifier, specifierLen);
5736
5737 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005738 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005739 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5740 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005741 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005742 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005743 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005744 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5745 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00005746
Jordan Rose92303592012-09-08 04:00:03 +00005747 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5748 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5749
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005750 // The remaining checks depend on the data arguments.
5751 if (HasVAListArg)
5752 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005753
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005754 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005755 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005756
Jordan Rose58bbe422012-07-19 18:10:08 +00005757 const Expr *Arg = getDataArg(argIndex);
5758 if (!Arg)
5759 return true;
5760
5761 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00005762}
5763
Jordan Roseaee34382012-09-05 22:56:26 +00005764static bool requiresParensToAddCast(const Expr *E) {
5765 // FIXME: We should have a general way to reason about operator
5766 // precedence and whether parens are actually needed here.
5767 // Take care of a few common cases where they aren't.
5768 const Expr *Inside = E->IgnoreImpCasts();
5769 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5770 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5771
5772 switch (Inside->getStmtClass()) {
5773 case Stmt::ArraySubscriptExprClass:
5774 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005775 case Stmt::CharacterLiteralClass:
5776 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005777 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005778 case Stmt::FloatingLiteralClass:
5779 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005780 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005781 case Stmt::ObjCArrayLiteralClass:
5782 case Stmt::ObjCBoolLiteralExprClass:
5783 case Stmt::ObjCBoxedExprClass:
5784 case Stmt::ObjCDictionaryLiteralClass:
5785 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005786 case Stmt::ObjCIvarRefExprClass:
5787 case Stmt::ObjCMessageExprClass:
5788 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005789 case Stmt::ObjCStringLiteralClass:
5790 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005791 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005792 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005793 case Stmt::UnaryOperatorClass:
5794 return false;
5795 default:
5796 return true;
5797 }
5798}
5799
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005800static std::pair<QualType, StringRef>
5801shouldNotPrintDirectly(const ASTContext &Context,
5802 QualType IntendedTy,
5803 const Expr *E) {
5804 // Use a 'while' to peel off layers of typedefs.
5805 QualType TyTy = IntendedTy;
5806 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5807 StringRef Name = UserTy->getDecl()->getName();
5808 QualType CastTy = llvm::StringSwitch<QualType>(Name)
5809 .Case("NSInteger", Context.LongTy)
5810 .Case("NSUInteger", Context.UnsignedLongTy)
5811 .Case("SInt32", Context.IntTy)
5812 .Case("UInt32", Context.UnsignedIntTy)
5813 .Default(QualType());
5814
5815 if (!CastTy.isNull())
5816 return std::make_pair(CastTy, Name);
5817
5818 TyTy = UserTy->desugar();
5819 }
5820
5821 // Strip parens if necessary.
5822 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5823 return shouldNotPrintDirectly(Context,
5824 PE->getSubExpr()->getType(),
5825 PE->getSubExpr());
5826
5827 // If this is a conditional expression, then its result type is constructed
5828 // via usual arithmetic conversions and thus there might be no necessary
5829 // typedef sugar there. Recurse to operands to check for NSInteger &
5830 // Co. usage condition.
5831 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5832 QualType TrueTy, FalseTy;
5833 StringRef TrueName, FalseName;
5834
5835 std::tie(TrueTy, TrueName) =
5836 shouldNotPrintDirectly(Context,
5837 CO->getTrueExpr()->getType(),
5838 CO->getTrueExpr());
5839 std::tie(FalseTy, FalseName) =
5840 shouldNotPrintDirectly(Context,
5841 CO->getFalseExpr()->getType(),
5842 CO->getFalseExpr());
5843
5844 if (TrueTy == FalseTy)
5845 return std::make_pair(TrueTy, TrueName);
5846 else if (TrueTy.isNull())
5847 return std::make_pair(FalseTy, FalseName);
5848 else if (FalseTy.isNull())
5849 return std::make_pair(TrueTy, TrueName);
5850 }
5851
5852 return std::make_pair(QualType(), StringRef());
5853}
5854
Richard Smith55ce3522012-06-25 20:30:08 +00005855bool
5856CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5857 const char *StartSpecifier,
5858 unsigned SpecifierLen,
5859 const Expr *E) {
5860 using namespace analyze_format_string;
5861 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005862 // Now type check the data expression that matches the
5863 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00005864 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00005865 if (!AT.isValid())
5866 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00005867
Jordan Rose598ec092012-12-05 18:44:40 +00005868 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00005869 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5870 ExprTy = TET->getUnderlyingExpr()->getType();
5871 }
5872
Seth Cantrellb4802962015-03-04 03:12:10 +00005873 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5874
5875 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00005876 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005877 }
Jordan Rose98709982012-06-04 22:48:57 +00005878
Jordan Rose22b74712012-09-05 22:56:19 +00005879 // Look through argument promotions for our error message's reported type.
5880 // This includes the integral and floating promotions, but excludes array
5881 // and function pointer decay; seeing that an argument intended to be a
5882 // string has type 'char [6]' is probably more confusing than 'char *'.
5883 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5884 if (ICE->getCastKind() == CK_IntegralCast ||
5885 ICE->getCastKind() == CK_FloatingCast) {
5886 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00005887 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00005888
5889 // Check if we didn't match because of an implicit cast from a 'char'
5890 // or 'short' to an 'int'. This is done because printf is a varargs
5891 // function.
5892 if (ICE->getType() == S.Context.IntTy ||
5893 ICE->getType() == S.Context.UnsignedIntTy) {
5894 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00005895 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00005896 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00005897 }
Jordan Rose98709982012-06-04 22:48:57 +00005898 }
Jordan Rose598ec092012-12-05 18:44:40 +00005899 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5900 // Special case for 'a', which has type 'int' in C.
5901 // Note, however, that we do /not/ want to treat multibyte constants like
5902 // 'MooV' as characters! This form is deprecated but still exists.
5903 if (ExprTy == S.Context.IntTy)
5904 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5905 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00005906 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005907
Jordan Rosebc53ed12014-05-31 04:12:14 +00005908 // Look through enums to their underlying type.
5909 bool IsEnum = false;
5910 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5911 ExprTy = EnumTy->getDecl()->getIntegerType();
5912 IsEnum = true;
5913 }
5914
Jordan Rose0e5badd2012-12-05 18:44:49 +00005915 // %C in an Objective-C context prints a unichar, not a wchar_t.
5916 // If the argument is an integer of some kind, believe the %C and suggest
5917 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00005918 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005919 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00005920 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5921 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5922 !ExprTy->isCharType()) {
5923 // 'unichar' is defined as a typedef of unsigned short, but we should
5924 // prefer using the typedef if it is visible.
5925 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00005926
5927 // While we are here, check if the value is an IntegerLiteral that happens
5928 // to be within the valid range.
5929 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5930 const llvm::APInt &V = IL->getValue();
5931 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5932 return true;
5933 }
5934
Jordan Rose0e5badd2012-12-05 18:44:49 +00005935 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5936 Sema::LookupOrdinaryName);
5937 if (S.LookupName(Result, S.getCurScope())) {
5938 NamedDecl *ND = Result.getFoundDecl();
5939 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5940 if (TD->getUnderlyingType() == IntendedTy)
5941 IntendedTy = S.Context.getTypedefType(TD);
5942 }
5943 }
5944 }
5945
5946 // Special-case some of Darwin's platform-independence types by suggesting
5947 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005948 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00005949 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005950 QualType CastTy;
5951 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5952 if (!CastTy.isNull()) {
5953 IntendedTy = CastTy;
5954 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00005955 }
5956 }
5957
Jordan Rose22b74712012-09-05 22:56:19 +00005958 // We may be able to offer a FixItHint if it is a supported type.
5959 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005960 bool success =
5961 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005962
Jordan Rose22b74712012-09-05 22:56:19 +00005963 if (success) {
5964 // Get the fix string from the fixed format specifier
5965 SmallString<16> buf;
5966 llvm::raw_svector_ostream os(buf);
5967 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005968
Jordan Roseaee34382012-09-05 22:56:26 +00005969 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5970
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005971 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00005972 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5973 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5974 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5975 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00005976 // In this case, the specifier is wrong and should be changed to match
5977 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00005978 EmitFormatDiagnostic(S.PDiag(diag)
5979 << AT.getRepresentativeTypeName(S.Context)
5980 << IntendedTy << IsEnum << E->getSourceRange(),
5981 E->getLocStart(),
5982 /*IsStringLocation*/ false, SpecRange,
5983 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00005984 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00005985 // The canonical type for formatting this value is different from the
5986 // actual type of the expression. (This occurs, for example, with Darwin's
5987 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
5988 // should be printed as 'long' for 64-bit compatibility.)
5989 // Rather than emitting a normal format/argument mismatch, we want to
5990 // add a cast to the recommended type (and correct the format string
5991 // if necessary).
5992 SmallString<16> CastBuf;
5993 llvm::raw_svector_ostream CastFix(CastBuf);
5994 CastFix << "(";
5995 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
5996 CastFix << ")";
5997
5998 SmallVector<FixItHint,4> Hints;
5999 if (!AT.matchesType(S.Context, IntendedTy))
6000 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6001
6002 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6003 // If there's already a cast present, just replace it.
6004 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6005 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6006
6007 } else if (!requiresParensToAddCast(E)) {
6008 // If the expression has high enough precedence,
6009 // just write the C-style cast.
6010 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6011 CastFix.str()));
6012 } else {
6013 // Otherwise, add parens around the expression as well as the cast.
6014 CastFix << "(";
6015 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6016 CastFix.str()));
6017
Alp Tokerb6cc5922014-05-03 03:45:55 +00006018 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006019 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6020 }
6021
Jordan Rose0e5badd2012-12-05 18:44:49 +00006022 if (ShouldNotPrintDirectly) {
6023 // The expression has a type that should not be printed directly.
6024 // We extract the name from the typedef because we don't want to show
6025 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006026 StringRef Name;
6027 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6028 Name = TypedefTy->getDecl()->getName();
6029 else
6030 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006031 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006032 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006033 << E->getSourceRange(),
6034 E->getLocStart(), /*IsStringLocation=*/false,
6035 SpecRange, Hints);
6036 } else {
6037 // In this case, the expression could be printed using a different
6038 // specifier, but we've decided that the specifier is probably correct
6039 // and we should cast instead. Just use the normal warning message.
6040 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006041 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6042 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006043 << E->getSourceRange(),
6044 E->getLocStart(), /*IsStringLocation*/false,
6045 SpecRange, Hints);
6046 }
Jordan Roseaee34382012-09-05 22:56:26 +00006047 }
Jordan Rose22b74712012-09-05 22:56:19 +00006048 } else {
6049 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6050 SpecifierLen);
6051 // Since the warning for passing non-POD types to variadic functions
6052 // was deferred until now, we emit a warning for non-POD
6053 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006054 switch (S.isValidVarArgType(ExprTy)) {
6055 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006056 case Sema::VAK_ValidInCXX11: {
6057 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6058 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6059 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6060 }
Richard Smithd7293d72013-08-05 18:49:43 +00006061
Seth Cantrellb4802962015-03-04 03:12:10 +00006062 EmitFormatDiagnostic(
6063 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6064 << IsEnum << CSR << E->getSourceRange(),
6065 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6066 break;
6067 }
Richard Smithd7293d72013-08-05 18:49:43 +00006068 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006069 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006070 EmitFormatDiagnostic(
6071 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006072 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006073 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006074 << CallType
6075 << AT.getRepresentativeTypeName(S.Context)
6076 << CSR
6077 << E->getSourceRange(),
6078 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006079 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006080 break;
6081
6082 case Sema::VAK_Invalid:
6083 if (ExprTy->isObjCObjectType())
6084 EmitFormatDiagnostic(
6085 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6086 << S.getLangOpts().CPlusPlus11
6087 << ExprTy
6088 << CallType
6089 << AT.getRepresentativeTypeName(S.Context)
6090 << CSR
6091 << E->getSourceRange(),
6092 E->getLocStart(), /*IsStringLocation*/false, CSR);
6093 else
6094 // FIXME: If this is an initializer list, suggest removing the braces
6095 // or inserting a cast to the target type.
6096 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6097 << isa<InitListExpr>(E) << ExprTy << CallType
6098 << AT.getRepresentativeTypeName(S.Context)
6099 << E->getSourceRange();
6100 break;
6101 }
6102
6103 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6104 "format string specifier index out of range");
6105 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006106 }
6107
Ted Kremenekab278de2010-01-28 23:39:18 +00006108 return true;
6109}
6110
Ted Kremenek02087932010-07-16 02:11:22 +00006111//===--- CHECK: Scanf format string checking ------------------------------===//
6112
6113namespace {
6114class CheckScanfHandler : public CheckFormatHandler {
6115public:
Stephen Hines648c3692016-09-16 01:07:04 +00006116 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006117 const Expr *origFormatExpr, Sema::FormatStringType type,
6118 unsigned firstDataArg, unsigned numDataArgs,
6119 const char *beg, bool hasVAListArg,
6120 ArrayRef<const Expr *> Args, unsigned formatIdx,
6121 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006122 llvm::SmallBitVector &CheckedVarArgs,
6123 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006124 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6125 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6126 inFunctionCall, CallType, CheckedVarArgs,
6127 UncoveredArg) {}
6128
Ted Kremenek02087932010-07-16 02:11:22 +00006129 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6130 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006131 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006132
6133 bool HandleInvalidScanfConversionSpecifier(
6134 const analyze_scanf::ScanfSpecifier &FS,
6135 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006136 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006137
Craig Toppere14c0f82014-03-12 04:55:44 +00006138 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006139};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006140} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006141
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006142void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6143 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006144 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6145 getLocationOfByte(end), /*IsStringLocation*/true,
6146 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006147}
6148
Ted Kremenekce815422010-07-19 21:25:57 +00006149bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6150 const analyze_scanf::ScanfSpecifier &FS,
6151 const char *startSpecifier,
6152 unsigned specifierLen) {
6153
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006154 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006155 FS.getConversionSpecifier();
6156
6157 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6158 getLocationOfByte(CS.getStart()),
6159 startSpecifier, specifierLen,
6160 CS.getStart(), CS.getLength());
6161}
6162
Ted Kremenek02087932010-07-16 02:11:22 +00006163bool CheckScanfHandler::HandleScanfSpecifier(
6164 const analyze_scanf::ScanfSpecifier &FS,
6165 const char *startSpecifier,
6166 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006167 using namespace analyze_scanf;
6168 using namespace analyze_format_string;
6169
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006170 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006171
Ted Kremenek6cd69422010-07-19 22:01:06 +00006172 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6173 // be used to decide if we are using positional arguments consistently.
6174 if (FS.consumesDataArgument()) {
6175 if (atFirstArg) {
6176 atFirstArg = false;
6177 usesPositionalArgs = FS.usesPositionalArg();
6178 }
6179 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006180 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6181 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006182 return false;
6183 }
Ted Kremenek02087932010-07-16 02:11:22 +00006184 }
6185
6186 // Check if the field with is non-zero.
6187 const OptionalAmount &Amt = FS.getFieldWidth();
6188 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6189 if (Amt.getConstantAmount() == 0) {
6190 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6191 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006192 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6193 getLocationOfByte(Amt.getStart()),
6194 /*IsStringLocation*/true, R,
6195 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006196 }
6197 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006198
Ted Kremenek02087932010-07-16 02:11:22 +00006199 if (!FS.consumesDataArgument()) {
6200 // FIXME: Technically specifying a precision or field width here
6201 // makes no sense. Worth issuing a warning at some point.
6202 return true;
6203 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006204
Ted Kremenek02087932010-07-16 02:11:22 +00006205 // Consume the argument.
6206 unsigned argIndex = FS.getArgIndex();
6207 if (argIndex < NumDataArgs) {
6208 // The check to see if the argIndex is valid will come later.
6209 // We set the bit here because we may exit early from this
6210 // function if we encounter some other error.
6211 CoveredArgs.set(argIndex);
6212 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006213
Ted Kremenek4407ea42010-07-20 20:04:47 +00006214 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006215 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006216 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6217 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006218 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006219 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006220 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006221 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6222 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006223
Jordan Rose92303592012-09-08 04:00:03 +00006224 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6225 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6226
Ted Kremenek02087932010-07-16 02:11:22 +00006227 // The remaining checks depend on the data arguments.
6228 if (HasVAListArg)
6229 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006230
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006231 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006232 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006233
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006234 // Check that the argument type matches the format specifier.
6235 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006236 if (!Ex)
6237 return true;
6238
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006239 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006240
6241 if (!AT.isValid()) {
6242 return true;
6243 }
6244
Seth Cantrellb4802962015-03-04 03:12:10 +00006245 analyze_format_string::ArgType::MatchKind match =
6246 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006247 if (match == analyze_format_string::ArgType::Match) {
6248 return true;
6249 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006250
Seth Cantrell79340072015-03-04 05:58:08 +00006251 ScanfSpecifier fixedFS = FS;
6252 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6253 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006254
Seth Cantrell79340072015-03-04 05:58:08 +00006255 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6256 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6257 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6258 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006259
Seth Cantrell79340072015-03-04 05:58:08 +00006260 if (success) {
6261 // Get the fix string from the fixed format specifier.
6262 SmallString<128> buf;
6263 llvm::raw_svector_ostream os(buf);
6264 fixedFS.toString(os);
6265
6266 EmitFormatDiagnostic(
6267 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6268 << Ex->getType() << false << Ex->getSourceRange(),
6269 Ex->getLocStart(),
6270 /*IsStringLocation*/ false,
6271 getSpecifierRange(startSpecifier, specifierLen),
6272 FixItHint::CreateReplacement(
6273 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6274 } else {
6275 EmitFormatDiagnostic(S.PDiag(diag)
6276 << AT.getRepresentativeTypeName(S.Context)
6277 << Ex->getType() << false << Ex->getSourceRange(),
6278 Ex->getLocStart(),
6279 /*IsStringLocation*/ false,
6280 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006281 }
6282
Ted Kremenek02087932010-07-16 02:11:22 +00006283 return true;
6284}
6285
Stephen Hines648c3692016-09-16 01:07:04 +00006286static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006287 const Expr *OrigFormatExpr,
6288 ArrayRef<const Expr *> Args,
6289 bool HasVAListArg, unsigned format_idx,
6290 unsigned firstDataArg,
6291 Sema::FormatStringType Type,
6292 bool inFunctionCall,
6293 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006294 llvm::SmallBitVector &CheckedVarArgs,
6295 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00006296 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00006297 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006298 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006299 S, inFunctionCall, Args[format_idx],
6300 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006301 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006302 return;
6303 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006304
Ted Kremenekab278de2010-01-28 23:39:18 +00006305 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006306 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00006307 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006308 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006309 const ConstantArrayType *T =
6310 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006311 assert(T && "String literal not of constant array type!");
6312 size_t TypeSize = T->getSize().getZExtValue();
6313 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006314 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006315
6316 // Emit a warning if the string literal is truncated and does not contain an
6317 // embedded null character.
6318 if (TypeSize <= StrRef.size() &&
6319 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6320 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006321 S, inFunctionCall, Args[format_idx],
6322 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006323 FExpr->getLocStart(),
6324 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6325 return;
6326 }
6327
Ted Kremenekab278de2010-01-28 23:39:18 +00006328 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006329 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006330 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006331 S, inFunctionCall, Args[format_idx],
6332 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006333 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006334 return;
6335 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006336
6337 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00006338 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6339 Type == Sema::FST_OSTrace) {
6340 CheckPrintfHandler H(
6341 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6342 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6343 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6344 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006345
Hans Wennborg23926bd2011-12-15 10:25:47 +00006346 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006347 S.getLangOpts(),
6348 S.Context.getTargetInfo(),
6349 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006350 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006351 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00006352 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6353 numDataArgs, Str, HasVAListArg, Args, format_idx,
6354 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006355
Hans Wennborg23926bd2011-12-15 10:25:47 +00006356 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006357 S.getLangOpts(),
6358 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006359 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006360 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006361}
6362
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006363bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6364 // Str - The format string. NOTE: this is NOT null-terminated!
6365 StringRef StrRef = FExpr->getString();
6366 const char *Str = StrRef.data();
6367 // Account for cases where the string literal is truncated in a declaration.
6368 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6369 assert(T && "String literal not of constant array type!");
6370 size_t TypeSize = T->getSize().getZExtValue();
6371 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6372 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6373 getLangOpts(),
6374 Context.getTargetInfo());
6375}
6376
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006377//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6378
6379// Returns the related absolute value function that is larger, of 0 if one
6380// does not exist.
6381static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6382 switch (AbsFunction) {
6383 default:
6384 return 0;
6385
6386 case Builtin::BI__builtin_abs:
6387 return Builtin::BI__builtin_labs;
6388 case Builtin::BI__builtin_labs:
6389 return Builtin::BI__builtin_llabs;
6390 case Builtin::BI__builtin_llabs:
6391 return 0;
6392
6393 case Builtin::BI__builtin_fabsf:
6394 return Builtin::BI__builtin_fabs;
6395 case Builtin::BI__builtin_fabs:
6396 return Builtin::BI__builtin_fabsl;
6397 case Builtin::BI__builtin_fabsl:
6398 return 0;
6399
6400 case Builtin::BI__builtin_cabsf:
6401 return Builtin::BI__builtin_cabs;
6402 case Builtin::BI__builtin_cabs:
6403 return Builtin::BI__builtin_cabsl;
6404 case Builtin::BI__builtin_cabsl:
6405 return 0;
6406
6407 case Builtin::BIabs:
6408 return Builtin::BIlabs;
6409 case Builtin::BIlabs:
6410 return Builtin::BIllabs;
6411 case Builtin::BIllabs:
6412 return 0;
6413
6414 case Builtin::BIfabsf:
6415 return Builtin::BIfabs;
6416 case Builtin::BIfabs:
6417 return Builtin::BIfabsl;
6418 case Builtin::BIfabsl:
6419 return 0;
6420
6421 case Builtin::BIcabsf:
6422 return Builtin::BIcabs;
6423 case Builtin::BIcabs:
6424 return Builtin::BIcabsl;
6425 case Builtin::BIcabsl:
6426 return 0;
6427 }
6428}
6429
6430// Returns the argument type of the absolute value function.
6431static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6432 unsigned AbsType) {
6433 if (AbsType == 0)
6434 return QualType();
6435
6436 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6437 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6438 if (Error != ASTContext::GE_None)
6439 return QualType();
6440
6441 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6442 if (!FT)
6443 return QualType();
6444
6445 if (FT->getNumParams() != 1)
6446 return QualType();
6447
6448 return FT->getParamType(0);
6449}
6450
6451// Returns the best absolute value function, or zero, based on type and
6452// current absolute value function.
6453static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6454 unsigned AbsFunctionKind) {
6455 unsigned BestKind = 0;
6456 uint64_t ArgSize = Context.getTypeSize(ArgType);
6457 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6458 Kind = getLargerAbsoluteValueFunction(Kind)) {
6459 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6460 if (Context.getTypeSize(ParamType) >= ArgSize) {
6461 if (BestKind == 0)
6462 BestKind = Kind;
6463 else if (Context.hasSameType(ParamType, ArgType)) {
6464 BestKind = Kind;
6465 break;
6466 }
6467 }
6468 }
6469 return BestKind;
6470}
6471
6472enum AbsoluteValueKind {
6473 AVK_Integer,
6474 AVK_Floating,
6475 AVK_Complex
6476};
6477
6478static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6479 if (T->isIntegralOrEnumerationType())
6480 return AVK_Integer;
6481 if (T->isRealFloatingType())
6482 return AVK_Floating;
6483 if (T->isAnyComplexType())
6484 return AVK_Complex;
6485
6486 llvm_unreachable("Type not integer, floating, or complex");
6487}
6488
6489// Changes the absolute value function to a different type. Preserves whether
6490// the function is a builtin.
6491static unsigned changeAbsFunction(unsigned AbsKind,
6492 AbsoluteValueKind ValueKind) {
6493 switch (ValueKind) {
6494 case AVK_Integer:
6495 switch (AbsKind) {
6496 default:
6497 return 0;
6498 case Builtin::BI__builtin_fabsf:
6499 case Builtin::BI__builtin_fabs:
6500 case Builtin::BI__builtin_fabsl:
6501 case Builtin::BI__builtin_cabsf:
6502 case Builtin::BI__builtin_cabs:
6503 case Builtin::BI__builtin_cabsl:
6504 return Builtin::BI__builtin_abs;
6505 case Builtin::BIfabsf:
6506 case Builtin::BIfabs:
6507 case Builtin::BIfabsl:
6508 case Builtin::BIcabsf:
6509 case Builtin::BIcabs:
6510 case Builtin::BIcabsl:
6511 return Builtin::BIabs;
6512 }
6513 case AVK_Floating:
6514 switch (AbsKind) {
6515 default:
6516 return 0;
6517 case Builtin::BI__builtin_abs:
6518 case Builtin::BI__builtin_labs:
6519 case Builtin::BI__builtin_llabs:
6520 case Builtin::BI__builtin_cabsf:
6521 case Builtin::BI__builtin_cabs:
6522 case Builtin::BI__builtin_cabsl:
6523 return Builtin::BI__builtin_fabsf;
6524 case Builtin::BIabs:
6525 case Builtin::BIlabs:
6526 case Builtin::BIllabs:
6527 case Builtin::BIcabsf:
6528 case Builtin::BIcabs:
6529 case Builtin::BIcabsl:
6530 return Builtin::BIfabsf;
6531 }
6532 case AVK_Complex:
6533 switch (AbsKind) {
6534 default:
6535 return 0;
6536 case Builtin::BI__builtin_abs:
6537 case Builtin::BI__builtin_labs:
6538 case Builtin::BI__builtin_llabs:
6539 case Builtin::BI__builtin_fabsf:
6540 case Builtin::BI__builtin_fabs:
6541 case Builtin::BI__builtin_fabsl:
6542 return Builtin::BI__builtin_cabsf;
6543 case Builtin::BIabs:
6544 case Builtin::BIlabs:
6545 case Builtin::BIllabs:
6546 case Builtin::BIfabsf:
6547 case Builtin::BIfabs:
6548 case Builtin::BIfabsl:
6549 return Builtin::BIcabsf;
6550 }
6551 }
6552 llvm_unreachable("Unable to convert function");
6553}
6554
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006555static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006556 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6557 if (!FnInfo)
6558 return 0;
6559
6560 switch (FDecl->getBuiltinID()) {
6561 default:
6562 return 0;
6563 case Builtin::BI__builtin_abs:
6564 case Builtin::BI__builtin_fabs:
6565 case Builtin::BI__builtin_fabsf:
6566 case Builtin::BI__builtin_fabsl:
6567 case Builtin::BI__builtin_labs:
6568 case Builtin::BI__builtin_llabs:
6569 case Builtin::BI__builtin_cabs:
6570 case Builtin::BI__builtin_cabsf:
6571 case Builtin::BI__builtin_cabsl:
6572 case Builtin::BIabs:
6573 case Builtin::BIlabs:
6574 case Builtin::BIllabs:
6575 case Builtin::BIfabs:
6576 case Builtin::BIfabsf:
6577 case Builtin::BIfabsl:
6578 case Builtin::BIcabs:
6579 case Builtin::BIcabsf:
6580 case Builtin::BIcabsl:
6581 return FDecl->getBuiltinID();
6582 }
6583 llvm_unreachable("Unknown Builtin type");
6584}
6585
6586// If the replacement is valid, emit a note with replacement function.
6587// Additionally, suggest including the proper header if not already included.
6588static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00006589 unsigned AbsKind, QualType ArgType) {
6590 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006591 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00006592 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006593 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6594 FunctionName = "std::abs";
6595 if (ArgType->isIntegralOrEnumerationType()) {
6596 HeaderName = "cstdlib";
6597 } else if (ArgType->isRealFloatingType()) {
6598 HeaderName = "cmath";
6599 } else {
6600 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006601 }
Richard Trieubeffb832014-04-15 23:47:53 +00006602
6603 // Lookup all std::abs
6604 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00006605 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00006606 R.suppressDiagnostics();
6607 S.LookupQualifiedName(R, Std);
6608
6609 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006610 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006611 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6612 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6613 } else {
6614 FDecl = dyn_cast<FunctionDecl>(I);
6615 }
6616 if (!FDecl)
6617 continue;
6618
6619 // Found std::abs(), check that they are the right ones.
6620 if (FDecl->getNumParams() != 1)
6621 continue;
6622
6623 // Check that the parameter type can handle the argument.
6624 QualType ParamType = FDecl->getParamDecl(0)->getType();
6625 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6626 S.Context.getTypeSize(ArgType) <=
6627 S.Context.getTypeSize(ParamType)) {
6628 // Found a function, don't need the header hint.
6629 EmitHeaderHint = false;
6630 break;
6631 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006632 }
Richard Trieubeffb832014-04-15 23:47:53 +00006633 }
6634 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00006635 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00006636 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6637
6638 if (HeaderName) {
6639 DeclarationName DN(&S.Context.Idents.get(FunctionName));
6640 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6641 R.suppressDiagnostics();
6642 S.LookupName(R, S.getCurScope());
6643
6644 if (R.isSingleResult()) {
6645 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6646 if (FD && FD->getBuiltinID() == AbsKind) {
6647 EmitHeaderHint = false;
6648 } else {
6649 return;
6650 }
6651 } else if (!R.empty()) {
6652 return;
6653 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006654 }
6655 }
6656
6657 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00006658 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006659
Richard Trieubeffb832014-04-15 23:47:53 +00006660 if (!HeaderName)
6661 return;
6662
6663 if (!EmitHeaderHint)
6664 return;
6665
Alp Toker5d96e0a2014-07-11 20:53:51 +00006666 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6667 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00006668}
6669
6670static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
6671 if (!FDecl)
6672 return false;
6673
6674 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
6675 return false;
6676
6677 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
6678
6679 while (ND && ND->isInlineNamespace()) {
6680 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006681 }
Richard Trieubeffb832014-04-15 23:47:53 +00006682
6683 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
6684 return false;
6685
6686 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
6687 return false;
6688
6689 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006690}
6691
6692// Warn when using the wrong abs() function.
6693void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
6694 const FunctionDecl *FDecl,
6695 IdentifierInfo *FnInfo) {
6696 if (Call->getNumArgs() != 1)
6697 return;
6698
6699 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00006700 bool IsStdAbs = IsFunctionStdAbs(FDecl);
6701 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006702 return;
6703
6704 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6705 QualType ParamType = Call->getArg(0)->getType();
6706
Alp Toker5d96e0a2014-07-11 20:53:51 +00006707 // Unsigned types cannot be negative. Suggest removing the absolute value
6708 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006709 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00006710 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00006711 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006712 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6713 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00006714 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006715 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6716 return;
6717 }
6718
David Majnemer7f77eb92015-11-15 03:04:34 +00006719 // Taking the absolute value of a pointer is very suspicious, they probably
6720 // wanted to index into an array, dereference a pointer, call a function, etc.
6721 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6722 unsigned DiagType = 0;
6723 if (ArgType->isFunctionType())
6724 DiagType = 1;
6725 else if (ArgType->isArrayType())
6726 DiagType = 2;
6727
6728 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6729 return;
6730 }
6731
Richard Trieubeffb832014-04-15 23:47:53 +00006732 // std::abs has overloads which prevent most of the absolute value problems
6733 // from occurring.
6734 if (IsStdAbs)
6735 return;
6736
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006737 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6738 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6739
6740 // The argument and parameter are the same kind. Check if they are the right
6741 // size.
6742 if (ArgValueKind == ParamValueKind) {
6743 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6744 return;
6745
6746 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6747 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6748 << FDecl << ArgType << ParamType;
6749
6750 if (NewAbsKind == 0)
6751 return;
6752
6753 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006754 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006755 return;
6756 }
6757
6758 // ArgValueKind != ParamValueKind
6759 // The wrong type of absolute value function was used. Attempt to find the
6760 // proper one.
6761 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6762 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6763 if (NewAbsKind == 0)
6764 return;
6765
6766 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6767 << FDecl << ParamValueKind << ArgValueKind;
6768
6769 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006770 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006771}
6772
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006773//===--- CHECK: Standard memory functions ---------------------------------===//
6774
Nico Weber0e6daef2013-12-26 23:38:39 +00006775/// \brief Takes the expression passed to the size_t parameter of functions
6776/// such as memcmp, strncat, etc and warns if it's a comparison.
6777///
6778/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6779static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6780 IdentifierInfo *FnName,
6781 SourceLocation FnLoc,
6782 SourceLocation RParenLoc) {
6783 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6784 if (!Size)
6785 return false;
6786
6787 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6788 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6789 return false;
6790
Nico Weber0e6daef2013-12-26 23:38:39 +00006791 SourceRange SizeRange = Size->getSourceRange();
6792 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6793 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00006794 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006795 << FnName << FixItHint::CreateInsertion(
6796 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00006797 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00006798 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00006799 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00006800 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6801 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00006802
6803 return true;
6804}
6805
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006806/// \brief Determine whether the given type is or contains a dynamic class type
6807/// (e.g., whether it has a vtable).
6808static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6809 bool &IsContained) {
6810 // Look through array types while ignoring qualifiers.
6811 const Type *Ty = T->getBaseElementTypeUnsafe();
6812 IsContained = false;
6813
6814 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6815 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00006816 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006817 return nullptr;
6818
6819 if (RD->isDynamicClass())
6820 return RD;
6821
6822 // Check all the fields. If any bases were dynamic, the class is dynamic.
6823 // It's impossible for a class to transitively contain itself by value, so
6824 // infinite recursion is impossible.
6825 for (auto *FD : RD->fields()) {
6826 bool SubContained;
6827 if (const CXXRecordDecl *ContainedRD =
6828 getContainedDynamicClass(FD->getType(), SubContained)) {
6829 IsContained = true;
6830 return ContainedRD;
6831 }
6832 }
6833
6834 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00006835}
6836
Chandler Carruth889ed862011-06-21 23:04:20 +00006837/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006838/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00006839static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00006840 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006841 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6842 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6843 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006844
Craig Topperc3ec1492014-05-26 06:22:03 +00006845 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006846}
6847
Chandler Carruth889ed862011-06-21 23:04:20 +00006848/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00006849static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006850 if (const UnaryExprOrTypeTraitExpr *SizeOf =
6851 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6852 if (SizeOf->getKind() == clang::UETT_SizeOf)
6853 return SizeOf->getTypeOfArgument();
6854
6855 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00006856}
6857
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006858/// \brief Check for dangerous or invalid arguments to memset().
6859///
Chandler Carruthac687262011-06-03 06:23:57 +00006860/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006861/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6862/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006863///
6864/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006865void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00006866 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006867 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00006868 assert(BId != 0);
6869
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006870 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00006871 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006872 unsigned ExpectedNumArgs =
6873 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00006874 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006875 return;
6876
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006877 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00006878 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006879 unsigned LenArg =
6880 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00006881 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006882
Nico Weber0e6daef2013-12-26 23:38:39 +00006883 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6884 Call->getLocStart(), Call->getRParenLoc()))
6885 return;
6886
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006887 // We have special checking when the length is a sizeof expression.
6888 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6889 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6890 llvm::FoldingSetNodeID SizeOfArgID;
6891
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00006892 // Although widely used, 'bzero' is not a standard function. Be more strict
6893 // with the argument types before allowing diagnostics and only allow the
6894 // form bzero(ptr, sizeof(...)).
6895 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6896 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
6897 return;
6898
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006899 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6900 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006901 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006902
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006903 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00006904 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006905 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00006906 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00006907
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006908 // Never warn about void type pointers. This can be used to suppress
6909 // false positives.
6910 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006911 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006912
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006913 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6914 // actually comparing the expressions for equality. Because computing the
6915 // expression IDs can be expensive, we only do this if the diagnostic is
6916 // enabled.
6917 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006918 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6919 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006920 // We only compute IDs for expressions if the warning is enabled, and
6921 // cache the sizeof arg's ID.
6922 if (SizeOfArgID == llvm::FoldingSetNodeID())
6923 SizeOfArg->Profile(SizeOfArgID, Context, true);
6924 llvm::FoldingSetNodeID DestID;
6925 Dest->Profile(DestID, Context, true);
6926 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00006927 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6928 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006929 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00006930 StringRef ReadableName = FnName->getName();
6931
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006932 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00006933 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006934 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00006935 if (!PointeeTy->isIncompleteType() &&
6936 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006937 ActionIdx = 2; // If the pointee's size is sizeof(char),
6938 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00006939
6940 // If the function is defined as a builtin macro, do not show macro
6941 // expansion.
6942 SourceLocation SL = SizeOfArg->getExprLoc();
6943 SourceRange DSR = Dest->getSourceRange();
6944 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006945 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00006946
6947 if (SM.isMacroArgExpansion(SL)) {
6948 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
6949 SL = SM.getSpellingLoc(SL);
6950 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
6951 SM.getSpellingLoc(DSR.getEnd()));
6952 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
6953 SM.getSpellingLoc(SSR.getEnd()));
6954 }
6955
Anna Zaksd08d9152012-05-30 23:14:52 +00006956 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006957 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00006958 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00006959 << PointeeTy
6960 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00006961 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00006962 << SSR);
6963 DiagRuntimeBehavior(SL, SizeOfArg,
6964 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
6965 << ActionIdx
6966 << SSR);
6967
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006968 break;
6969 }
6970 }
6971
6972 // Also check for cases where the sizeof argument is the exact same
6973 // type as the memory argument, and where it points to a user-defined
6974 // record type.
6975 if (SizeOfArgTy != QualType()) {
6976 if (PointeeTy->isRecordType() &&
6977 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
6978 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
6979 PDiag(diag::warn_sizeof_pointer_type_memaccess)
6980 << FnName << SizeOfArgTy << ArgIdx
6981 << PointeeTy << Dest->getSourceRange()
6982 << LenExpr->getSourceRange());
6983 break;
6984 }
Nico Weberc5e73862011-06-14 16:14:58 +00006985 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00006986 } else if (DestTy->isArrayType()) {
6987 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00006988 }
Nico Weberc5e73862011-06-14 16:14:58 +00006989
Nico Weberc44b35e2015-03-21 17:37:46 +00006990 if (PointeeTy == QualType())
6991 continue;
Anna Zaks22122702012-01-17 00:37:07 +00006992
Nico Weberc44b35e2015-03-21 17:37:46 +00006993 // Always complain about dynamic classes.
6994 bool IsContained;
6995 if (const CXXRecordDecl *ContainedRD =
6996 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00006997
Nico Weberc44b35e2015-03-21 17:37:46 +00006998 unsigned OperationType = 0;
6999 // "overwritten" if we're warning about the destination for any call
7000 // but memcmp; otherwise a verb appropriate to the call.
7001 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7002 if (BId == Builtin::BImemcpy)
7003 OperationType = 1;
7004 else if(BId == Builtin::BImemmove)
7005 OperationType = 2;
7006 else if (BId == Builtin::BImemcmp)
7007 OperationType = 3;
7008 }
7009
John McCall31168b02011-06-15 23:02:42 +00007010 DiagRuntimeBehavior(
7011 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007012 PDiag(diag::warn_dyn_class_memaccess)
7013 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7014 << FnName << IsContained << ContainedRD << OperationType
7015 << Call->getCallee()->getSourceRange());
7016 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7017 BId != Builtin::BImemset)
7018 DiagRuntimeBehavior(
7019 Dest->getExprLoc(), Dest,
7020 PDiag(diag::warn_arc_object_memaccess)
7021 << ArgIdx << FnName << PointeeTy
7022 << Call->getCallee()->getSourceRange());
7023 else
7024 continue;
7025
7026 DiagRuntimeBehavior(
7027 Dest->getExprLoc(), Dest,
7028 PDiag(diag::note_bad_memaccess_silence)
7029 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7030 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007031 }
7032}
7033
Ted Kremenek6865f772011-08-18 20:55:45 +00007034// A little helper routine: ignore addition and subtraction of integer literals.
7035// This intentionally does not ignore all integer constant expressions because
7036// we don't want to remove sizeof().
7037static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7038 Ex = Ex->IgnoreParenCasts();
7039
7040 for (;;) {
7041 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7042 if (!BO || !BO->isAdditiveOp())
7043 break;
7044
7045 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7046 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7047
7048 if (isa<IntegerLiteral>(RHS))
7049 Ex = LHS;
7050 else if (isa<IntegerLiteral>(LHS))
7051 Ex = RHS;
7052 else
7053 break;
7054 }
7055
7056 return Ex;
7057}
7058
Anna Zaks13b08572012-08-08 21:42:23 +00007059static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7060 ASTContext &Context) {
7061 // Only handle constant-sized or VLAs, but not flexible members.
7062 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7063 // Only issue the FIXIT for arrays of size > 1.
7064 if (CAT->getSize().getSExtValue() <= 1)
7065 return false;
7066 } else if (!Ty->isVariableArrayType()) {
7067 return false;
7068 }
7069 return true;
7070}
7071
Ted Kremenek6865f772011-08-18 20:55:45 +00007072// Warn if the user has made the 'size' argument to strlcpy or strlcat
7073// be the size of the source, instead of the destination.
7074void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7075 IdentifierInfo *FnName) {
7076
7077 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007078 unsigned NumArgs = Call->getNumArgs();
7079 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007080 return;
7081
7082 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7083 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007084 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007085
7086 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7087 Call->getLocStart(), Call->getRParenLoc()))
7088 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00007089
7090 // Look for 'strlcpy(dst, x, sizeof(x))'
7091 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7092 CompareWithSrc = Ex;
7093 else {
7094 // Look for 'strlcpy(dst, x, strlen(x))'
7095 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00007096 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7097 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00007098 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7099 }
7100 }
7101
7102 if (!CompareWithSrc)
7103 return;
7104
7105 // Determine if the argument to sizeof/strlen is equal to the source
7106 // argument. In principle there's all kinds of things you could do
7107 // here, for instance creating an == expression and evaluating it with
7108 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7109 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7110 if (!SrcArgDRE)
7111 return;
7112
7113 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7114 if (!CompareWithSrcDRE ||
7115 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7116 return;
7117
7118 const Expr *OriginalSizeArg = Call->getArg(2);
7119 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7120 << OriginalSizeArg->getSourceRange() << FnName;
7121
7122 // Output a FIXIT hint if the destination is an array (rather than a
7123 // pointer to an array). This could be enhanced to handle some
7124 // pointers if we know the actual size, like if DstArg is 'array+2'
7125 // we could say 'sizeof(array)-2'.
7126 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00007127 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00007128 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007129
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007130 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007131 llvm::raw_svector_ostream OS(sizeString);
7132 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007133 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00007134 OS << ")";
7135
7136 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7137 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7138 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00007139}
7140
Anna Zaks314cd092012-02-01 19:08:57 +00007141/// Check if two expressions refer to the same declaration.
7142static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7143 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7144 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7145 return D1->getDecl() == D2->getDecl();
7146 return false;
7147}
7148
7149static const Expr *getStrlenExprArg(const Expr *E) {
7150 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7151 const FunctionDecl *FD = CE->getDirectCallee();
7152 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00007153 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007154 return CE->getArg(0)->IgnoreParenCasts();
7155 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007156 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007157}
7158
7159// Warn on anti-patterns as the 'size' argument to strncat.
7160// The correct size argument should look like following:
7161// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7162void Sema::CheckStrncatArguments(const CallExpr *CE,
7163 IdentifierInfo *FnName) {
7164 // Don't crash if the user has the wrong number of arguments.
7165 if (CE->getNumArgs() < 3)
7166 return;
7167 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7168 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7169 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7170
Nico Weber0e6daef2013-12-26 23:38:39 +00007171 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7172 CE->getRParenLoc()))
7173 return;
7174
Anna Zaks314cd092012-02-01 19:08:57 +00007175 // Identify common expressions, which are wrongly used as the size argument
7176 // to strncat and may lead to buffer overflows.
7177 unsigned PatternType = 0;
7178 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7179 // - sizeof(dst)
7180 if (referToTheSameDecl(SizeOfArg, DstArg))
7181 PatternType = 1;
7182 // - sizeof(src)
7183 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7184 PatternType = 2;
7185 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7186 if (BE->getOpcode() == BO_Sub) {
7187 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7188 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7189 // - sizeof(dst) - strlen(dst)
7190 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7191 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7192 PatternType = 1;
7193 // - sizeof(src) - (anything)
7194 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7195 PatternType = 2;
7196 }
7197 }
7198
7199 if (PatternType == 0)
7200 return;
7201
Anna Zaks5069aa32012-02-03 01:27:37 +00007202 // Generate the diagnostic.
7203 SourceLocation SL = LenArg->getLocStart();
7204 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007205 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00007206
7207 // If the function is defined as a builtin macro, do not show macro expansion.
7208 if (SM.isMacroArgExpansion(SL)) {
7209 SL = SM.getSpellingLoc(SL);
7210 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7211 SM.getSpellingLoc(SR.getEnd()));
7212 }
7213
Anna Zaks13b08572012-08-08 21:42:23 +00007214 // Check if the destination is an array (rather than a pointer to an array).
7215 QualType DstTy = DstArg->getType();
7216 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7217 Context);
7218 if (!isKnownSizeArray) {
7219 if (PatternType == 1)
7220 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7221 else
7222 Diag(SL, diag::warn_strncat_src_size) << SR;
7223 return;
7224 }
7225
Anna Zaks314cd092012-02-01 19:08:57 +00007226 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00007227 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007228 else
Anna Zaks5069aa32012-02-03 01:27:37 +00007229 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007230
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007231 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00007232 llvm::raw_svector_ostream OS(sizeString);
7233 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007234 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007235 OS << ") - ";
7236 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007237 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007238 OS << ") - 1";
7239
Anna Zaks5069aa32012-02-03 01:27:37 +00007240 Diag(SL, diag::note_strncat_wrong_size)
7241 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00007242}
7243
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007244//===--- CHECK: Return Address of Stack Variable --------------------------===//
7245
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007246static const Expr *EvalVal(const Expr *E,
7247 SmallVectorImpl<const DeclRefExpr *> &refVars,
7248 const Decl *ParentDecl);
7249static const Expr *EvalAddr(const Expr *E,
7250 SmallVectorImpl<const DeclRefExpr *> &refVars,
7251 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007252
7253/// CheckReturnStackAddr - Check if a return statement returns the address
7254/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007255static void
7256CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7257 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00007258
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007259 const Expr *stackE = nullptr;
7260 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007261
7262 // Perform checking for returned stack addresses, local blocks,
7263 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00007264 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007265 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007266 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00007267 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007268 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007269 }
7270
Craig Topperc3ec1492014-05-26 06:22:03 +00007271 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007272 return; // Nothing suspicious was found.
7273
Richard Trieu81b6c562016-08-05 23:24:47 +00007274 // Parameters are initalized in the calling scope, so taking the address
7275 // of a parameter reference doesn't need a warning.
7276 for (auto *DRE : refVars)
7277 if (isa<ParmVarDecl>(DRE->getDecl()))
7278 return;
7279
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007280 SourceLocation diagLoc;
7281 SourceRange diagRange;
7282 if (refVars.empty()) {
7283 diagLoc = stackE->getLocStart();
7284 diagRange = stackE->getSourceRange();
7285 } else {
7286 // We followed through a reference variable. 'stackE' contains the
7287 // problematic expression but we will warn at the return statement pointing
7288 // at the reference variable. We will later display the "trail" of
7289 // reference variables using notes.
7290 diagLoc = refVars[0]->getLocStart();
7291 diagRange = refVars[0]->getSourceRange();
7292 }
7293
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007294 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7295 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00007296 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007297 << DR->getDecl()->getDeclName() << diagRange;
7298 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007299 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007300 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007301 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007302 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00007303 // If there is an LValue->RValue conversion, then the value of the
7304 // reference type is used, not the reference.
7305 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7306 if (ICE->getCastKind() == CK_LValueToRValue) {
7307 return;
7308 }
7309 }
Craig Topperda7b27f2015-11-17 05:40:09 +00007310 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7311 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007312 }
7313
7314 // Display the "trail" of reference variables that we followed until we
7315 // found the problematic expression using notes.
7316 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007317 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007318 // If this var binds to another reference var, show the range of the next
7319 // var, otherwise the var binds to the problematic expression, in which case
7320 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007321 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7322 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007323 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7324 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007325 }
7326}
7327
7328/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7329/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007330/// to a location on the stack, a local block, an address of a label, or a
7331/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007332/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007333/// encounter a subexpression that (1) clearly does not lead to one of the
7334/// above problematic expressions (2) is something we cannot determine leads to
7335/// a problematic expression based on such local checking.
7336///
7337/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7338/// the expression that they point to. Such variables are added to the
7339/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007340///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007341/// EvalAddr processes expressions that are pointers that are used as
7342/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007343/// At the base case of the recursion is a check for the above problematic
7344/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007345///
7346/// This implementation handles:
7347///
7348/// * pointer-to-pointer casts
7349/// * implicit conversions from array references to pointers
7350/// * taking the address of fields
7351/// * arbitrary interplay between "&" and "*" operators
7352/// * pointer arithmetic from an address of a stack variable
7353/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007354static const Expr *EvalAddr(const Expr *E,
7355 SmallVectorImpl<const DeclRefExpr *> &refVars,
7356 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007357 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00007358 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007359
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007360 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00007361 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00007362 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007363 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00007364 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00007365
Peter Collingbourne91147592011-04-15 00:35:48 +00007366 E = E->IgnoreParens();
7367
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007368 // Our "symbolic interpreter" is just a dispatch off the currently
7369 // viewed AST node. We then recursively traverse the AST by calling
7370 // EvalAddr and EvalVal appropriately.
7371 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007372 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007373 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007374
Richard Smith40f08eb2014-01-30 22:05:38 +00007375 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00007376 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00007377 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00007378
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007379 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007380 // If this is a reference variable, follow through to the expression that
7381 // it points to.
7382 if (V->hasLocalStorage() &&
7383 V->getType()->isReferenceType() && V->hasInit()) {
7384 // Add the reference variable to the "trail".
7385 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007386 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007387 }
7388
Craig Topperc3ec1492014-05-26 06:22:03 +00007389 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007390 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007391
Chris Lattner934edb22007-12-28 05:31:15 +00007392 case Stmt::UnaryOperatorClass: {
7393 // The only unary operator that make sense to handle here
7394 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007395 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007396
John McCalle3027922010-08-25 11:45:40 +00007397 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007398 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007399 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007400 }
Mike Stump11289f42009-09-09 15:08:12 +00007401
Chris Lattner934edb22007-12-28 05:31:15 +00007402 case Stmt::BinaryOperatorClass: {
7403 // Handle pointer arithmetic. All other binary operators are not valid
7404 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007405 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00007406 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00007407
John McCalle3027922010-08-25 11:45:40 +00007408 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00007409 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007410
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007411 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00007412
7413 // Determine which argument is the real pointer base. It could be
7414 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007415 if (!Base->getType()->isPointerType())
7416 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00007417
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007418 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007419 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007420 }
Steve Naroff2752a172008-09-10 19:17:48 +00007421
Chris Lattner934edb22007-12-28 05:31:15 +00007422 // For conditional operators we need to see if either the LHS or RHS are
7423 // valid DeclRefExpr*s. If one of them is valid, we return it.
7424 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007425 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007426
Chris Lattner934edb22007-12-28 05:31:15 +00007427 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007428 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007429 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007430 // In C++, we can have a throw-expression, which has 'void' type.
7431 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007432 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007433 return LHS;
7434 }
Chris Lattner934edb22007-12-28 05:31:15 +00007435
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007436 // In C++, we can have a throw-expression, which has 'void' type.
7437 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00007438 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007439
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007440 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007441 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007442
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007443 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00007444 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007445 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00007446 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007447
7448 case Stmt::AddrLabelExprClass:
7449 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00007450
John McCall28fc7092011-11-10 05:35:25 +00007451 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007452 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7453 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00007454
Ted Kremenekc3b4c522008-08-07 00:49:01 +00007455 // For casts, we need to handle conversions from arrays to
7456 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00007457 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00007458 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007459 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00007460 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00007461 case Stmt::CXXStaticCastExprClass:
7462 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00007463 case Stmt::CXXConstCastExprClass:
7464 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007465 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00007466 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00007467 case CK_LValueToRValue:
7468 case CK_NoOp:
7469 case CK_BaseToDerived:
7470 case CK_DerivedToBase:
7471 case CK_UncheckedDerivedToBase:
7472 case CK_Dynamic:
7473 case CK_CPointerToObjCPointerCast:
7474 case CK_BlockPointerToObjCPointerCast:
7475 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007476 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007477
7478 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007479 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007480
Richard Trieudadefde2014-07-02 04:39:38 +00007481 case CK_BitCast:
7482 if (SubExpr->getType()->isAnyPointerType() ||
7483 SubExpr->getType()->isBlockPointerType() ||
7484 SubExpr->getType()->isObjCQualifiedIdType())
7485 return EvalAddr(SubExpr, refVars, ParentDecl);
7486 else
7487 return nullptr;
7488
Eli Friedman8195ad72012-02-23 23:04:32 +00007489 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007490 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00007491 }
Chris Lattner934edb22007-12-28 05:31:15 +00007492 }
Mike Stump11289f42009-09-09 15:08:12 +00007493
Douglas Gregorfe314812011-06-21 17:03:29 +00007494 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007495 if (const Expr *Result =
7496 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7497 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00007498 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00007499 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007500
Chris Lattner934edb22007-12-28 05:31:15 +00007501 // Everything else: we simply don't reason about them.
7502 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007503 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00007504 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007505}
Mike Stump11289f42009-09-09 15:08:12 +00007506
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007507/// EvalVal - This function is complements EvalAddr in the mutual recursion.
7508/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007509static const Expr *EvalVal(const Expr *E,
7510 SmallVectorImpl<const DeclRefExpr *> &refVars,
7511 const Decl *ParentDecl) {
7512 do {
7513 // We should only be called for evaluating non-pointer expressions, or
7514 // expressions with a pointer type that are not used as references but
7515 // instead
7516 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00007517
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007518 // Our "symbolic interpreter" is just a dispatch off the currently
7519 // viewed AST node. We then recursively traverse the AST by calling
7520 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00007521
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007522 E = E->IgnoreParens();
7523 switch (E->getStmtClass()) {
7524 case Stmt::ImplicitCastExprClass: {
7525 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7526 if (IE->getValueKind() == VK_LValue) {
7527 E = IE->getSubExpr();
7528 continue;
7529 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007530 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007531 }
Richard Smith40f08eb2014-01-30 22:05:38 +00007532
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007533 case Stmt::ExprWithCleanupsClass:
7534 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7535 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007536
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007537 case Stmt::DeclRefExprClass: {
7538 // When we hit a DeclRefExpr we are looking at code that refers to a
7539 // variable's name. If it's not a reference variable we check if it has
7540 // local storage within the function, and if so, return the expression.
7541 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7542
7543 // If we leave the immediate function, the lifetime isn't about to end.
7544 if (DR->refersToEnclosingVariableOrCapture())
7545 return nullptr;
7546
7547 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7548 // Check if it refers to itself, e.g. "int& i = i;".
7549 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007550 return DR;
7551
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007552 if (V->hasLocalStorage()) {
7553 if (!V->getType()->isReferenceType())
7554 return DR;
7555
7556 // Reference variable, follow through to the expression that
7557 // it points to.
7558 if (V->hasInit()) {
7559 // Add the reference variable to the "trail".
7560 refVars.push_back(DR);
7561 return EvalVal(V->getInit(), refVars, V);
7562 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007563 }
7564 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007565
7566 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007567 }
Mike Stump11289f42009-09-09 15:08:12 +00007568
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007569 case Stmt::UnaryOperatorClass: {
7570 // The only unary operator that make sense to handle here
7571 // is Deref. All others don't resolve to a "name." This includes
7572 // handling all sorts of rvalues passed to a unary operator.
7573 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007574
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007575 if (U->getOpcode() == UO_Deref)
7576 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007577
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007578 return nullptr;
7579 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007580
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007581 case Stmt::ArraySubscriptExprClass: {
7582 // Array subscripts are potential references to data on the stack. We
7583 // retrieve the DeclRefExpr* for the array variable if it indeed
7584 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00007585 const auto *ASE = cast<ArraySubscriptExpr>(E);
7586 if (ASE->isTypeDependent())
7587 return nullptr;
7588 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007589 }
Mike Stump11289f42009-09-09 15:08:12 +00007590
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007591 case Stmt::OMPArraySectionExprClass: {
7592 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7593 ParentDecl);
7594 }
Mike Stump11289f42009-09-09 15:08:12 +00007595
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007596 case Stmt::ConditionalOperatorClass: {
7597 // For conditional operators we need to see if either the LHS or RHS are
7598 // non-NULL Expr's. If one is non-NULL, we return it.
7599 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007600
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007601 // Handle the GNU extension for missing LHS.
7602 if (const Expr *LHSExpr = C->getLHS()) {
7603 // In C++, we can have a throw-expression, which has 'void' type.
7604 if (!LHSExpr->getType()->isVoidType())
7605 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7606 return LHS;
7607 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007608
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007609 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007610 if (C->getRHS()->getType()->isVoidType())
7611 return nullptr;
7612
7613 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007614 }
7615
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007616 // Accesses to members are potential references to data on the stack.
7617 case Stmt::MemberExprClass: {
7618 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00007619
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007620 // Check for indirect access. We only want direct field accesses.
7621 if (M->isArrow())
7622 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007623
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007624 // Check whether the member type is itself a reference, in which case
7625 // we're not going to refer to the member, but to what the member refers
7626 // to.
7627 if (M->getMemberDecl()->getType()->isReferenceType())
7628 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007629
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007630 return EvalVal(M->getBase(), refVars, ParentDecl);
7631 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00007632
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007633 case Stmt::MaterializeTemporaryExprClass:
7634 if (const Expr *Result =
7635 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7636 refVars, ParentDecl))
7637 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007638 return E;
7639
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007640 default:
7641 // Check that we don't return or take the address of a reference to a
7642 // temporary. This is only useful in C++.
7643 if (!E->isTypeDependent() && E->isRValue())
7644 return E;
7645
7646 // Everything else: we simply don't reason about them.
7647 return nullptr;
7648 }
7649 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007650}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007651
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007652void
7653Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7654 SourceLocation ReturnLoc,
7655 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00007656 const AttrVec *Attrs,
7657 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007658 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7659
7660 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00007661 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7662 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00007663 CheckNonNullExpr(*this, RetValExp))
7664 Diag(ReturnLoc, diag::warn_null_ret)
7665 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00007666
7667 // C++11 [basic.stc.dynamic.allocation]p4:
7668 // If an allocation function declared with a non-throwing
7669 // exception-specification fails to allocate storage, it shall return
7670 // a null pointer. Any other allocation function that fails to allocate
7671 // storage shall indicate failure only by throwing an exception [...]
7672 if (FD) {
7673 OverloadedOperatorKind Op = FD->getOverloadedOperator();
7674 if (Op == OO_New || Op == OO_Array_New) {
7675 const FunctionProtoType *Proto
7676 = FD->getType()->castAs<FunctionProtoType>();
7677 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7678 CheckNonNullExpr(*this, RetValExp))
7679 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7680 << FD << getLangOpts().CPlusPlus11;
7681 }
7682 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007683}
7684
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007685//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7686
7687/// Check for comparisons of floating point operands using != and ==.
7688/// Issue a warning if these are no self-comparisons, as they are not likely
7689/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00007690void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00007691 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7692 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007693
7694 // Special case: check for x == x (which is OK).
7695 // Do not emit warnings for such cases.
7696 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7697 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7698 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00007699 return;
Mike Stump11289f42009-09-09 15:08:12 +00007700
Ted Kremenekeda40e22007-11-29 00:59:04 +00007701 // Special case: check for comparisons against literals that can be exactly
7702 // represented by APFloat. In such cases, do not emit a warning. This
7703 // is a heuristic: often comparison against such literals are used to
7704 // detect if a value in a variable has not changed. This clearly can
7705 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00007706 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7707 if (FLL->isExact())
7708 return;
7709 } else
7710 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7711 if (FLR->isExact())
7712 return;
Mike Stump11289f42009-09-09 15:08:12 +00007713
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007714 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00007715 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007716 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007717 return;
Mike Stump11289f42009-09-09 15:08:12 +00007718
David Blaikie1f4ff152012-07-16 20:47:22 +00007719 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007720 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007721 return;
Mike Stump11289f42009-09-09 15:08:12 +00007722
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007723 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00007724 Diag(Loc, diag::warn_floatingpoint_eq)
7725 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007726}
John McCallca01b222010-01-04 23:21:16 +00007727
John McCall70aa5392010-01-06 05:24:50 +00007728//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7729//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00007730
John McCall70aa5392010-01-06 05:24:50 +00007731namespace {
John McCallca01b222010-01-04 23:21:16 +00007732
John McCall70aa5392010-01-06 05:24:50 +00007733/// Structure recording the 'active' range of an integer-valued
7734/// expression.
7735struct IntRange {
7736 /// The number of bits active in the int.
7737 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00007738
John McCall70aa5392010-01-06 05:24:50 +00007739 /// True if the int is known not to have negative values.
7740 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00007741
John McCall70aa5392010-01-06 05:24:50 +00007742 IntRange(unsigned Width, bool NonNegative)
7743 : Width(Width), NonNegative(NonNegative)
7744 {}
John McCallca01b222010-01-04 23:21:16 +00007745
John McCall817d4af2010-11-10 23:38:19 +00007746 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00007747 static IntRange forBoolType() {
7748 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00007749 }
7750
John McCall817d4af2010-11-10 23:38:19 +00007751 /// Returns the range of an opaque value of the given integral type.
7752 static IntRange forValueOfType(ASTContext &C, QualType T) {
7753 return forValueOfCanonicalType(C,
7754 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00007755 }
7756
John McCall817d4af2010-11-10 23:38:19 +00007757 /// Returns the range of an opaque value of a canonical integral type.
7758 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00007759 assert(T->isCanonicalUnqualified());
7760
7761 if (const VectorType *VT = dyn_cast<VectorType>(T))
7762 T = VT->getElementType().getTypePtr();
7763 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7764 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007765 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7766 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00007767
David Majnemer6a426652013-06-07 22:07:20 +00007768 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00007769 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00007770 EnumDecl *Enum = ET->getDecl();
7771 if (!Enum->isCompleteDefinition())
7772 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00007773
David Majnemer6a426652013-06-07 22:07:20 +00007774 unsigned NumPositive = Enum->getNumPositiveBits();
7775 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00007776
David Majnemer6a426652013-06-07 22:07:20 +00007777 if (NumNegative == 0)
7778 return IntRange(NumPositive, true/*NonNegative*/);
7779 else
7780 return IntRange(std::max(NumPositive + 1, NumNegative),
7781 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00007782 }
John McCall70aa5392010-01-06 05:24:50 +00007783
7784 const BuiltinType *BT = cast<BuiltinType>(T);
7785 assert(BT->isInteger());
7786
7787 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7788 }
7789
John McCall817d4af2010-11-10 23:38:19 +00007790 /// Returns the "target" range of a canonical integral type, i.e.
7791 /// the range of values expressible in the type.
7792 ///
7793 /// This matches forValueOfCanonicalType except that enums have the
7794 /// full range of their type, not the range of their enumerators.
7795 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7796 assert(T->isCanonicalUnqualified());
7797
7798 if (const VectorType *VT = dyn_cast<VectorType>(T))
7799 T = VT->getElementType().getTypePtr();
7800 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7801 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007802 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7803 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007804 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00007805 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007806
7807 const BuiltinType *BT = cast<BuiltinType>(T);
7808 assert(BT->isInteger());
7809
7810 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7811 }
7812
7813 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00007814 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00007815 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00007816 L.NonNegative && R.NonNegative);
7817 }
7818
John McCall817d4af2010-11-10 23:38:19 +00007819 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00007820 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00007821 return IntRange(std::min(L.Width, R.Width),
7822 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00007823 }
7824};
7825
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007826IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007827 if (value.isSigned() && value.isNegative())
7828 return IntRange(value.getMinSignedBits(), false);
7829
7830 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00007831 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007832
7833 // isNonNegative() just checks the sign bit without considering
7834 // signedness.
7835 return IntRange(value.getActiveBits(), true);
7836}
7837
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007838IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7839 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007840 if (result.isInt())
7841 return GetValueRange(C, result.getInt(), MaxWidth);
7842
7843 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00007844 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7845 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7846 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7847 R = IntRange::join(R, El);
7848 }
John McCall70aa5392010-01-06 05:24:50 +00007849 return R;
7850 }
7851
7852 if (result.isComplexInt()) {
7853 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7854 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7855 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00007856 }
7857
7858 // This can happen with lossless casts to intptr_t of "based" lvalues.
7859 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00007860 // FIXME: The only reason we need to pass the type in here is to get
7861 // the sign right on this one case. It would be nice if APValue
7862 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007863 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00007864 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00007865}
John McCall70aa5392010-01-06 05:24:50 +00007866
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007867QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007868 QualType Ty = E->getType();
7869 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7870 Ty = AtomicRHS->getValueType();
7871 return Ty;
7872}
7873
John McCall70aa5392010-01-06 05:24:50 +00007874/// Pseudo-evaluate the given integer expression, estimating the
7875/// range of values it might take.
7876///
7877/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007878IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007879 E = E->IgnoreParens();
7880
7881 // Try a full evaluation first.
7882 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007883 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00007884 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007885
7886 // I think we only want to look through implicit casts here; if the
7887 // user has an explicit widening cast, we should treat the value as
7888 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007889 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00007890 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00007891 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7892
Eli Friedmane6d33952013-07-08 20:20:06 +00007893 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00007894
George Burgess IVdf1ed002016-01-13 01:52:39 +00007895 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7896 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00007897
John McCall70aa5392010-01-06 05:24:50 +00007898 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00007899 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00007900 return OutputTypeRange;
7901
7902 IntRange SubRange
7903 = GetExprRange(C, CE->getSubExpr(),
7904 std::min(MaxWidth, OutputTypeRange.Width));
7905
7906 // Bail out if the subexpr's range is as wide as the cast type.
7907 if (SubRange.Width >= OutputTypeRange.Width)
7908 return OutputTypeRange;
7909
7910 // Otherwise, we take the smaller width, and we're non-negative if
7911 // either the output type or the subexpr is.
7912 return IntRange(SubRange.Width,
7913 SubRange.NonNegative || OutputTypeRange.NonNegative);
7914 }
7915
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007916 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007917 // If we can fold the condition, just take that operand.
7918 bool CondResult;
7919 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7920 return GetExprRange(C, CondResult ? CO->getTrueExpr()
7921 : CO->getFalseExpr(),
7922 MaxWidth);
7923
7924 // Otherwise, conservatively merge.
7925 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7926 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7927 return IntRange::join(L, R);
7928 }
7929
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007930 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007931 switch (BO->getOpcode()) {
7932
7933 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00007934 case BO_LAnd:
7935 case BO_LOr:
7936 case BO_LT:
7937 case BO_GT:
7938 case BO_LE:
7939 case BO_GE:
7940 case BO_EQ:
7941 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00007942 return IntRange::forBoolType();
7943
John McCallc3688382011-07-13 06:35:24 +00007944 // The type of the assignments is the type of the LHS, so the RHS
7945 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00007946 case BO_MulAssign:
7947 case BO_DivAssign:
7948 case BO_RemAssign:
7949 case BO_AddAssign:
7950 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00007951 case BO_XorAssign:
7952 case BO_OrAssign:
7953 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00007954 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00007955
John McCallc3688382011-07-13 06:35:24 +00007956 // Simple assignments just pass through the RHS, which will have
7957 // been coerced to the LHS type.
7958 case BO_Assign:
7959 // TODO: bitfields?
7960 return GetExprRange(C, BO->getRHS(), MaxWidth);
7961
John McCall70aa5392010-01-06 05:24:50 +00007962 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00007963 case BO_PtrMemD:
7964 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00007965 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007966
John McCall2ce81ad2010-01-06 22:07:33 +00007967 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00007968 case BO_And:
7969 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00007970 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
7971 GetExprRange(C, BO->getRHS(), MaxWidth));
7972
John McCall70aa5392010-01-06 05:24:50 +00007973 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00007974 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00007975 // ...except that we want to treat '1 << (blah)' as logically
7976 // positive. It's an important idiom.
7977 if (IntegerLiteral *I
7978 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
7979 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007980 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00007981 return IntRange(R.Width, /*NonNegative*/ true);
7982 }
7983 }
7984 // fallthrough
7985
John McCalle3027922010-08-25 11:45:40 +00007986 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00007987 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007988
John McCall2ce81ad2010-01-06 22:07:33 +00007989 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00007990 case BO_Shr:
7991 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00007992 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7993
7994 // If the shift amount is a positive constant, drop the width by
7995 // that much.
7996 llvm::APSInt shift;
7997 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
7998 shift.isNonNegative()) {
7999 unsigned zext = shift.getZExtValue();
8000 if (zext >= L.Width)
8001 L.Width = (L.NonNegative ? 0 : 1);
8002 else
8003 L.Width -= zext;
8004 }
8005
8006 return L;
8007 }
8008
8009 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008010 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008011 return GetExprRange(C, BO->getRHS(), MaxWidth);
8012
John McCall2ce81ad2010-01-06 22:07:33 +00008013 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008014 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008015 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008016 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008017 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008018
John McCall51431812011-07-14 22:39:48 +00008019 // The width of a division result is mostly determined by the size
8020 // of the LHS.
8021 case BO_Div: {
8022 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008023 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008024 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8025
8026 // If the divisor is constant, use that.
8027 llvm::APSInt divisor;
8028 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8029 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8030 if (log2 >= L.Width)
8031 L.Width = (L.NonNegative ? 0 : 1);
8032 else
8033 L.Width = std::min(L.Width - log2, MaxWidth);
8034 return L;
8035 }
8036
8037 // Otherwise, just use the LHS's width.
8038 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8039 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8040 }
8041
8042 // The result of a remainder can't be larger than the result of
8043 // either side.
8044 case BO_Rem: {
8045 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008046 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008047 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8048 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8049
8050 IntRange meet = IntRange::meet(L, R);
8051 meet.Width = std::min(meet.Width, MaxWidth);
8052 return meet;
8053 }
8054
8055 // The default behavior is okay for these.
8056 case BO_Mul:
8057 case BO_Add:
8058 case BO_Xor:
8059 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008060 break;
8061 }
8062
John McCall51431812011-07-14 22:39:48 +00008063 // The default case is to treat the operation as if it were closed
8064 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008065 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8066 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8067 return IntRange::join(L, R);
8068 }
8069
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008070 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008071 switch (UO->getOpcode()) {
8072 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008073 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008074 return IntRange::forBoolType();
8075
8076 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008077 case UO_Deref:
8078 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00008079 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008080
8081 default:
8082 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8083 }
8084 }
8085
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008086 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00008087 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8088
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008089 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00008090 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00008091 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00008092
Eli Friedmane6d33952013-07-08 20:20:06 +00008093 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008094}
John McCall263a48b2010-01-04 23:31:57 +00008095
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008096IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008097 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00008098}
8099
John McCall263a48b2010-01-04 23:31:57 +00008100/// Checks whether the given value, which currently has the given
8101/// source semantics, has the same value when coerced through the
8102/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008103bool IsSameFloatAfterCast(const llvm::APFloat &value,
8104 const llvm::fltSemantics &Src,
8105 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008106 llvm::APFloat truncated = value;
8107
8108 bool ignored;
8109 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8110 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8111
8112 return truncated.bitwiseIsEqual(value);
8113}
8114
8115/// Checks whether the given value, which currently has the given
8116/// source semantics, has the same value when coerced through the
8117/// target semantics.
8118///
8119/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008120bool IsSameFloatAfterCast(const APValue &value,
8121 const llvm::fltSemantics &Src,
8122 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008123 if (value.isFloat())
8124 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8125
8126 if (value.isVector()) {
8127 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8128 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8129 return false;
8130 return true;
8131 }
8132
8133 assert(value.isComplexFloat());
8134 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8135 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8136}
8137
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008138void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008139
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008140bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00008141 // Suppress cases where we are comparing against an enum constant.
8142 if (const DeclRefExpr *DR =
8143 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8144 if (isa<EnumConstantDecl>(DR->getDecl()))
8145 return false;
8146
8147 // Suppress cases where the '0' value is expanded from a macro.
8148 if (E->getLocStart().isMacroID())
8149 return false;
8150
John McCallcc7e5bf2010-05-06 08:58:33 +00008151 llvm::APSInt Value;
8152 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8153}
8154
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008155bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00008156 // Strip off implicit integral promotions.
8157 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008158 if (ICE->getCastKind() != CK_IntegralCast &&
8159 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00008160 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008161 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00008162 }
8163
8164 return E->getType()->isEnumeralType();
8165}
8166
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008167void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00008168 // Disable warning in template instantiations.
8169 if (!S.ActiveTemplateInstantiations.empty())
8170 return;
8171
John McCalle3027922010-08-25 11:45:40 +00008172 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00008173 if (E->isValueDependent())
8174 return;
8175
John McCalle3027922010-08-25 11:45:40 +00008176 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008177 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008178 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008179 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008180 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008181 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008182 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008183 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008184 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008185 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008186 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008187 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008188 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008189 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008190 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008191 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8192 }
8193}
8194
Benjamin Kramer7320b992016-06-15 14:20:56 +00008195void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8196 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008197 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00008198 // Disable warning in template instantiations.
8199 if (!S.ActiveTemplateInstantiations.empty())
8200 return;
8201
Richard Trieu0f097742014-04-04 04:13:47 +00008202 // TODO: Investigate using GetExprRange() to get tighter bounds
8203 // on the bit ranges.
8204 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00008205 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00008206 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00008207 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8208 unsigned OtherWidth = OtherRange.Width;
8209
8210 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8211
Richard Trieu560910c2012-11-14 22:50:24 +00008212 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00008213 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00008214 return;
8215
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008216 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00008217 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008218
Richard Trieu0f097742014-04-04 04:13:47 +00008219 // Used for diagnostic printout.
8220 enum {
8221 LiteralConstant = 0,
8222 CXXBoolLiteralTrue,
8223 CXXBoolLiteralFalse
8224 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008225
Richard Trieu0f097742014-04-04 04:13:47 +00008226 if (!OtherIsBooleanType) {
8227 QualType ConstantT = Constant->getType();
8228 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00008229
Richard Trieu0f097742014-04-04 04:13:47 +00008230 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8231 return;
8232 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8233 "comparison with non-integer type");
8234
8235 bool ConstantSigned = ConstantT->isSignedIntegerType();
8236 bool CommonSigned = CommonT->isSignedIntegerType();
8237
8238 bool EqualityOnly = false;
8239
8240 if (CommonSigned) {
8241 // The common type is signed, therefore no signed to unsigned conversion.
8242 if (!OtherRange.NonNegative) {
8243 // Check that the constant is representable in type OtherT.
8244 if (ConstantSigned) {
8245 if (OtherWidth >= Value.getMinSignedBits())
8246 return;
8247 } else { // !ConstantSigned
8248 if (OtherWidth >= Value.getActiveBits() + 1)
8249 return;
8250 }
8251 } else { // !OtherSigned
8252 // Check that the constant is representable in type OtherT.
8253 // Negative values are out of range.
8254 if (ConstantSigned) {
8255 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8256 return;
8257 } else { // !ConstantSigned
8258 if (OtherWidth >= Value.getActiveBits())
8259 return;
8260 }
Richard Trieu560910c2012-11-14 22:50:24 +00008261 }
Richard Trieu0f097742014-04-04 04:13:47 +00008262 } else { // !CommonSigned
8263 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00008264 if (OtherWidth >= Value.getActiveBits())
8265 return;
Craig Toppercf360162014-06-18 05:13:11 +00008266 } else { // OtherSigned
8267 assert(!ConstantSigned &&
8268 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00008269 // Check to see if the constant is representable in OtherT.
8270 if (OtherWidth > Value.getActiveBits())
8271 return;
8272 // Check to see if the constant is equivalent to a negative value
8273 // cast to CommonT.
8274 if (S.Context.getIntWidth(ConstantT) ==
8275 S.Context.getIntWidth(CommonT) &&
8276 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8277 return;
8278 // The constant value rests between values that OtherT can represent
8279 // after conversion. Relational comparison still works, but equality
8280 // comparisons will be tautological.
8281 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008282 }
8283 }
Richard Trieu0f097742014-04-04 04:13:47 +00008284
8285 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8286
8287 if (op == BO_EQ || op == BO_NE) {
8288 IsTrue = op == BO_NE;
8289 } else if (EqualityOnly) {
8290 return;
8291 } else if (RhsConstant) {
8292 if (op == BO_GT || op == BO_GE)
8293 IsTrue = !PositiveConstant;
8294 else // op == BO_LT || op == BO_LE
8295 IsTrue = PositiveConstant;
8296 } else {
8297 if (op == BO_LT || op == BO_LE)
8298 IsTrue = !PositiveConstant;
8299 else // op == BO_GT || op == BO_GE
8300 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008301 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008302 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00008303 // Other isKnownToHaveBooleanValue
8304 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8305 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8306 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8307
8308 static const struct LinkedConditions {
8309 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8310 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8311 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8312 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8313 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8314 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8315
8316 } TruthTable = {
8317 // Constant on LHS. | Constant on RHS. |
8318 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
8319 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8320 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8321 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8322 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8323 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8324 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8325 };
8326
8327 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8328
8329 enum ConstantValue ConstVal = Zero;
8330 if (Value.isUnsigned() || Value.isNonNegative()) {
8331 if (Value == 0) {
8332 LiteralOrBoolConstant =
8333 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8334 ConstVal = Zero;
8335 } else if (Value == 1) {
8336 LiteralOrBoolConstant =
8337 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8338 ConstVal = One;
8339 } else {
8340 LiteralOrBoolConstant = LiteralConstant;
8341 ConstVal = GT_One;
8342 }
8343 } else {
8344 ConstVal = LT_Zero;
8345 }
8346
8347 CompareBoolWithConstantResult CmpRes;
8348
8349 switch (op) {
8350 case BO_LT:
8351 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8352 break;
8353 case BO_GT:
8354 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8355 break;
8356 case BO_LE:
8357 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8358 break;
8359 case BO_GE:
8360 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8361 break;
8362 case BO_EQ:
8363 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8364 break;
8365 case BO_NE:
8366 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8367 break;
8368 default:
8369 CmpRes = Unkwn;
8370 break;
8371 }
8372
8373 if (CmpRes == AFals) {
8374 IsTrue = false;
8375 } else if (CmpRes == ATrue) {
8376 IsTrue = true;
8377 } else {
8378 return;
8379 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008380 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008381
8382 // If this is a comparison to an enum constant, include that
8383 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00008384 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008385 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8386 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8387
8388 SmallString<64> PrettySourceValue;
8389 llvm::raw_svector_ostream OS(PrettySourceValue);
8390 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00008391 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008392 else
8393 OS << Value;
8394
Richard Trieu0f097742014-04-04 04:13:47 +00008395 S.DiagRuntimeBehavior(
8396 E->getOperatorLoc(), E,
8397 S.PDiag(diag::warn_out_of_range_compare)
8398 << OS.str() << LiteralOrBoolConstant
8399 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8400 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008401}
8402
John McCallcc7e5bf2010-05-06 08:58:33 +00008403/// Analyze the operands of the given comparison. Implements the
8404/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008405void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00008406 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8407 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008408}
John McCall263a48b2010-01-04 23:31:57 +00008409
John McCallca01b222010-01-04 23:21:16 +00008410/// \brief Implements -Wsign-compare.
8411///
Richard Trieu82402a02011-09-15 21:56:47 +00008412/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008413void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008414 // The type the comparison is being performed in.
8415 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00008416
8417 // Only analyze comparison operators where both sides have been converted to
8418 // the same type.
8419 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8420 return AnalyzeImpConvsInComparison(S, E);
8421
8422 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00008423 if (E->isValueDependent())
8424 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008425
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008426 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8427 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008428
8429 bool IsComparisonConstant = false;
8430
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008431 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008432 // of 'true' or 'false'.
8433 if (T->isIntegralType(S.Context)) {
8434 llvm::APSInt RHSValue;
8435 bool IsRHSIntegralLiteral =
8436 RHS->isIntegerConstantExpr(RHSValue, S.Context);
8437 llvm::APSInt LHSValue;
8438 bool IsLHSIntegralLiteral =
8439 LHS->isIntegerConstantExpr(LHSValue, S.Context);
8440 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8441 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8442 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8443 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8444 else
8445 IsComparisonConstant =
8446 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008447 } else if (!T->hasUnsignedIntegerRepresentation())
8448 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008449
John McCallcc7e5bf2010-05-06 08:58:33 +00008450 // We don't do anything special if this isn't an unsigned integral
8451 // comparison: we're only interested in integral comparisons, and
8452 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00008453 //
8454 // We also don't care about value-dependent expressions or expressions
8455 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008456 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00008457 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008458
John McCallcc7e5bf2010-05-06 08:58:33 +00008459 // Check to see if one of the (unmodified) operands is of different
8460 // signedness.
8461 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00008462 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8463 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00008464 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00008465 signedOperand = LHS;
8466 unsignedOperand = RHS;
8467 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8468 signedOperand = RHS;
8469 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00008470 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00008471 CheckTrivialUnsignedComparison(S, E);
8472 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008473 }
8474
John McCallcc7e5bf2010-05-06 08:58:33 +00008475 // Otherwise, calculate the effective range of the signed operand.
8476 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00008477
John McCallcc7e5bf2010-05-06 08:58:33 +00008478 // Go ahead and analyze implicit conversions in the operands. Note
8479 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00008480 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8481 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00008482
John McCallcc7e5bf2010-05-06 08:58:33 +00008483 // If the signed range is non-negative, -Wsign-compare won't fire,
8484 // but we should still check for comparisons which are always true
8485 // or false.
8486 if (signedRange.NonNegative)
8487 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008488
8489 // For (in)equality comparisons, if the unsigned operand is a
8490 // constant which cannot collide with a overflowed signed operand,
8491 // then reinterpreting the signed operand as unsigned will not
8492 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00008493 if (E->isEqualityOp()) {
8494 unsigned comparisonWidth = S.Context.getIntWidth(T);
8495 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00008496
John McCallcc7e5bf2010-05-06 08:58:33 +00008497 // We should never be unable to prove that the unsigned operand is
8498 // non-negative.
8499 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8500
8501 if (unsignedRange.Width < comparisonWidth)
8502 return;
8503 }
8504
Douglas Gregorbfb4a212012-05-01 01:53:49 +00008505 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8506 S.PDiag(diag::warn_mixed_sign_comparison)
8507 << LHS->getType() << RHS->getType()
8508 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00008509}
8510
John McCall1f425642010-11-11 03:21:53 +00008511/// Analyzes an attempt to assign the given value to a bitfield.
8512///
8513/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008514bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8515 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00008516 assert(Bitfield->isBitField());
8517 if (Bitfield->isInvalidDecl())
8518 return false;
8519
John McCalldeebbcf2010-11-11 05:33:51 +00008520 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00008521 QualType BitfieldType = Bitfield->getType();
8522 if (BitfieldType->isBooleanType())
8523 return false;
8524
8525 if (BitfieldType->isEnumeralType()) {
8526 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
8527 // If the underlying enum type was not explicitly specified as an unsigned
8528 // type and the enum contain only positive values, MSVC++ will cause an
8529 // inconsistency by storing this as a signed type.
8530 if (S.getLangOpts().CPlusPlus11 &&
8531 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
8532 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
8533 BitfieldEnumDecl->getNumNegativeBits() == 0) {
8534 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
8535 << BitfieldEnumDecl->getNameAsString();
8536 }
8537 }
8538
John McCalldeebbcf2010-11-11 05:33:51 +00008539 if (Bitfield->getType()->isBooleanType())
8540 return false;
8541
Douglas Gregor789adec2011-02-04 13:09:01 +00008542 // Ignore value- or type-dependent expressions.
8543 if (Bitfield->getBitWidth()->isValueDependent() ||
8544 Bitfield->getBitWidth()->isTypeDependent() ||
8545 Init->isValueDependent() ||
8546 Init->isTypeDependent())
8547 return false;
8548
John McCall1f425642010-11-11 03:21:53 +00008549 Expr *OriginalInit = Init->IgnoreParenImpCasts();
8550
Richard Smith5fab0c92011-12-28 19:48:30 +00008551 llvm::APSInt Value;
8552 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00008553 return false;
8554
John McCall1f425642010-11-11 03:21:53 +00008555 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00008556 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00008557
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008558 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00008559 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008560 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8561 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00008562
John McCall1f425642010-11-11 03:21:53 +00008563 if (OriginalWidth <= FieldWidth)
8564 return false;
8565
Eli Friedmanc267a322012-01-26 23:11:39 +00008566 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00008567 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00008568 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00008569
Eli Friedmanc267a322012-01-26 23:11:39 +00008570 // Check whether the stored value is equal to the original value.
8571 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00008572 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00008573 return false;
8574
Eli Friedmanc267a322012-01-26 23:11:39 +00008575 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00008576 // therefore don't strictly fit into a signed bitfield of width 1.
8577 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00008578 return false;
8579
John McCall1f425642010-11-11 03:21:53 +00008580 std::string PrettyValue = Value.toString(10);
8581 std::string PrettyTrunc = TruncatedValue.toString(10);
8582
8583 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8584 << PrettyValue << PrettyTrunc << OriginalInit->getType()
8585 << Init->getSourceRange();
8586
8587 return true;
8588}
8589
John McCalld2a53122010-11-09 23:24:47 +00008590/// Analyze the given simple or compound assignment for warning-worthy
8591/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008592void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00008593 // Just recurse on the LHS.
8594 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8595
8596 // We want to recurse on the RHS as normal unless we're assigning to
8597 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00008598 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008599 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00008600 E->getOperatorLoc())) {
8601 // Recurse, ignoring any implicit conversions on the RHS.
8602 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8603 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00008604 }
8605 }
8606
8607 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8608}
8609
John McCall263a48b2010-01-04 23:31:57 +00008610/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008611void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8612 SourceLocation CContext, unsigned diag,
8613 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008614 if (pruneControlFlow) {
8615 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8616 S.PDiag(diag)
8617 << SourceType << T << E->getSourceRange()
8618 << SourceRange(CContext));
8619 return;
8620 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00008621 S.Diag(E->getExprLoc(), diag)
8622 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8623}
8624
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008625/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008626void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8627 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008628 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008629}
8630
Richard Trieube234c32016-04-21 21:04:55 +00008631
8632/// Diagnose an implicit cast from a floating point value to an integer value.
8633void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8634
8635 SourceLocation CContext) {
8636 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
8637 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
8638
8639 Expr *InnerE = E->IgnoreParenImpCasts();
8640 // We also want to warn on, e.g., "int i = -1.234"
8641 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8642 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8643 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8644
8645 const bool IsLiteral =
8646 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8647
8648 llvm::APFloat Value(0.0);
8649 bool IsConstant =
8650 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8651 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00008652 return DiagnoseImpCast(S, E, T, CContext,
8653 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00008654 }
8655
Chandler Carruth016ef402011-04-10 08:36:24 +00008656 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00008657
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00008658 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8659 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00008660 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8661 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00008662 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00008663 if (IsLiteral) return;
8664 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8665 PruneWarnings);
8666 }
8667
8668 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00008669 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00008670 // Warn on floating point literal to integer.
8671 DiagID = diag::warn_impcast_literal_float_to_integer;
8672 } else if (IntegerValue == 0) {
8673 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
8674 return DiagnoseImpCast(S, E, T, CContext,
8675 diag::warn_impcast_float_integer, PruneWarnings);
8676 }
8677 // Warn on non-zero to zero conversion.
8678 DiagID = diag::warn_impcast_float_to_integer_zero;
8679 } else {
8680 if (IntegerValue.isUnsigned()) {
8681 if (!IntegerValue.isMaxValue()) {
8682 return DiagnoseImpCast(S, E, T, CContext,
8683 diag::warn_impcast_float_integer, PruneWarnings);
8684 }
8685 } else { // IntegerValue.isSigned()
8686 if (!IntegerValue.isMaxSignedValue() &&
8687 !IntegerValue.isMinSignedValue()) {
8688 return DiagnoseImpCast(S, E, T, CContext,
8689 diag::warn_impcast_float_integer, PruneWarnings);
8690 }
8691 }
8692 // Warn on evaluatable floating point expression to integer conversion.
8693 DiagID = diag::warn_impcast_float_to_integer;
8694 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008695
Eli Friedman07185912013-08-29 23:44:43 +00008696 // FIXME: Force the precision of the source value down so we don't print
8697 // digits which are usually useless (we don't really care here if we
8698 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
8699 // would automatically print the shortest representation, but it's a bit
8700 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00008701 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00008702 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
8703 precision = (precision * 59 + 195) / 196;
8704 Value.toString(PrettySourceValue, precision);
8705
David Blaikie9b88cc02012-05-15 17:18:27 +00008706 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00008707 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00008708 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00008709 else
David Blaikie9b88cc02012-05-15 17:18:27 +00008710 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00008711
Richard Trieube234c32016-04-21 21:04:55 +00008712 if (PruneWarnings) {
8713 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8714 S.PDiag(DiagID)
8715 << E->getType() << T.getUnqualifiedType()
8716 << PrettySourceValue << PrettyTargetValue
8717 << E->getSourceRange() << SourceRange(CContext));
8718 } else {
8719 S.Diag(E->getExprLoc(), DiagID)
8720 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8721 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8722 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008723}
8724
John McCall18a2c2c2010-11-09 22:22:12 +00008725std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8726 if (!Range.Width) return "0";
8727
8728 llvm::APSInt ValueInRange = Value;
8729 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00008730 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00008731 return ValueInRange.toString(10);
8732}
8733
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008734bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008735 if (!isa<ImplicitCastExpr>(Ex))
8736 return false;
8737
8738 Expr *InnerE = Ex->IgnoreParenImpCasts();
8739 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8740 const Type *Source =
8741 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8742 if (Target->isDependentType())
8743 return false;
8744
8745 const BuiltinType *FloatCandidateBT =
8746 dyn_cast<BuiltinType>(ToBool ? Source : Target);
8747 const Type *BoolCandidateType = ToBool ? Target : Source;
8748
8749 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8750 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8751}
8752
8753void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8754 SourceLocation CC) {
8755 unsigned NumArgs = TheCall->getNumArgs();
8756 for (unsigned i = 0; i < NumArgs; ++i) {
8757 Expr *CurrA = TheCall->getArg(i);
8758 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8759 continue;
8760
8761 bool IsSwapped = ((i > 0) &&
8762 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8763 IsSwapped |= ((i < (NumArgs - 1)) &&
8764 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8765 if (IsSwapped) {
8766 // Warn on this floating-point to bool conversion.
8767 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8768 CurrA->getType(), CC,
8769 diag::warn_impcast_floating_point_to_bool);
8770 }
8771 }
8772}
8773
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008774void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00008775 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
8776 E->getExprLoc()))
8777 return;
8778
Richard Trieu09d6b802016-01-08 23:35:06 +00008779 // Don't warn on functions which have return type nullptr_t.
8780 if (isa<CallExpr>(E))
8781 return;
8782
Richard Trieu5b993502014-10-15 03:42:06 +00008783 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
8784 const Expr::NullPointerConstantKind NullKind =
8785 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
8786 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
8787 return;
8788
8789 // Return if target type is a safe conversion.
8790 if (T->isAnyPointerType() || T->isBlockPointerType() ||
8791 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8792 return;
8793
8794 SourceLocation Loc = E->getSourceRange().getBegin();
8795
Richard Trieu0a5e1662016-02-13 00:58:53 +00008796 // Venture through the macro stacks to get to the source of macro arguments.
8797 // The new location is a better location than the complete location that was
8798 // passed in.
8799 while (S.SourceMgr.isMacroArgExpansion(Loc))
8800 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8801
8802 while (S.SourceMgr.isMacroArgExpansion(CC))
8803 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8804
Richard Trieu5b993502014-10-15 03:42:06 +00008805 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00008806 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8807 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8808 Loc, S.SourceMgr, S.getLangOpts());
8809 if (MacroName == "NULL")
8810 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00008811 }
8812
8813 // Only warn if the null and context location are in the same macro expansion.
8814 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8815 return;
8816
8817 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8818 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8819 << FixItHint::CreateReplacement(Loc,
8820 S.getFixItZeroLiteralForType(T, Loc));
8821}
8822
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008823void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8824 ObjCArrayLiteral *ArrayLiteral);
8825void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8826 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00008827
8828/// Check a single element within a collection literal against the
8829/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008830void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8831 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008832 // Skip a bitcast to 'id' or qualified 'id'.
8833 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8834 if (ICE->getCastKind() == CK_BitCast &&
8835 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8836 Element = ICE->getSubExpr();
8837 }
8838
8839 QualType ElementType = Element->getType();
8840 ExprResult ElementResult(Element);
8841 if (ElementType->getAs<ObjCObjectPointerType>() &&
8842 S.CheckSingleAssignmentConstraints(TargetElementType,
8843 ElementResult,
8844 false, false)
8845 != Sema::Compatible) {
8846 S.Diag(Element->getLocStart(),
8847 diag::warn_objc_collection_literal_element)
8848 << ElementType << ElementKind << TargetElementType
8849 << Element->getSourceRange();
8850 }
8851
8852 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8853 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8854 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8855 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8856}
8857
8858/// Check an Objective-C array literal being converted to the given
8859/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008860void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8861 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008862 if (!S.NSArrayDecl)
8863 return;
8864
8865 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8866 if (!TargetObjCPtr)
8867 return;
8868
8869 if (TargetObjCPtr->isUnspecialized() ||
8870 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8871 != S.NSArrayDecl->getCanonicalDecl())
8872 return;
8873
8874 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8875 if (TypeArgs.size() != 1)
8876 return;
8877
8878 QualType TargetElementType = TypeArgs[0];
8879 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8880 checkObjCCollectionLiteralElement(S, TargetElementType,
8881 ArrayLiteral->getElement(I),
8882 0);
8883 }
8884}
8885
8886/// Check an Objective-C dictionary literal being converted to the given
8887/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008888void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8889 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008890 if (!S.NSDictionaryDecl)
8891 return;
8892
8893 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8894 if (!TargetObjCPtr)
8895 return;
8896
8897 if (TargetObjCPtr->isUnspecialized() ||
8898 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8899 != S.NSDictionaryDecl->getCanonicalDecl())
8900 return;
8901
8902 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8903 if (TypeArgs.size() != 2)
8904 return;
8905
8906 QualType TargetKeyType = TypeArgs[0];
8907 QualType TargetObjectType = TypeArgs[1];
8908 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8909 auto Element = DictionaryLiteral->getKeyValueElement(I);
8910 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8911 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8912 }
8913}
8914
Richard Trieufc404c72016-02-05 23:02:38 +00008915// Helper function to filter out cases for constant width constant conversion.
8916// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008917bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8918 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00008919 // If initializing from a constant, and the constant starts with '0',
8920 // then it is a binary, octal, or hexadecimal. Allow these constants
8921 // to fill all the bits, even if there is a sign change.
8922 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8923 const char FirstLiteralCharacter =
8924 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8925 if (FirstLiteralCharacter == '0')
8926 return false;
8927 }
8928
8929 // If the CC location points to a '{', and the type is char, then assume
8930 // assume it is an array initialization.
8931 if (CC.isValid() && T->isCharType()) {
8932 const char FirstContextCharacter =
8933 S.getSourceManager().getCharacterData(CC)[0];
8934 if (FirstContextCharacter == '{')
8935 return false;
8936 }
8937
8938 return true;
8939}
8940
John McCallcc7e5bf2010-05-06 08:58:33 +00008941void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00008942 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008943 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00008944
John McCallcc7e5bf2010-05-06 08:58:33 +00008945 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
8946 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
8947 if (Source == Target) return;
8948 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00008949
Chandler Carruthc22845a2011-07-26 05:40:03 +00008950 // If the conversion context location is invalid don't complain. We also
8951 // don't want to emit a warning if the issue occurs from the expansion of
8952 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
8953 // delay this check as long as possible. Once we detect we are in that
8954 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008955 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00008956 return;
8957
Richard Trieu021baa32011-09-23 20:10:00 +00008958 // Diagnose implicit casts to bool.
8959 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
8960 if (isa<StringLiteral>(E))
8961 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00008962 // and expressions, for instance, assert(0 && "error here"), are
8963 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00008964 return DiagnoseImpCast(S, E, T, CC,
8965 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00008966 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
8967 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
8968 // This covers the literal expressions that evaluate to Objective-C
8969 // objects.
8970 return DiagnoseImpCast(S, E, T, CC,
8971 diag::warn_impcast_objective_c_literal_to_bool);
8972 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008973 if (Source->isPointerType() || Source->canDecayToPointerType()) {
8974 // Warn on pointer to bool conversion that is always true.
8975 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
8976 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00008977 }
Richard Trieu021baa32011-09-23 20:10:00 +00008978 }
John McCall263a48b2010-01-04 23:31:57 +00008979
Douglas Gregor5054cb02015-07-07 03:58:22 +00008980 // Check implicit casts from Objective-C collection literals to specialized
8981 // collection types, e.g., NSArray<NSString *> *.
8982 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
8983 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
8984 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
8985 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
8986
John McCall263a48b2010-01-04 23:31:57 +00008987 // Strip vector types.
8988 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008989 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008990 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008991 return;
John McCallacf0ee52010-10-08 02:01:28 +00008992 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008993 }
Chris Lattneree7286f2011-06-14 04:51:15 +00008994
8995 // If the vector cast is cast between two vectors of the same size, it is
8996 // a bitcast, not a conversion.
8997 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
8998 return;
John McCall263a48b2010-01-04 23:31:57 +00008999
9000 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9001 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9002 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00009003 if (auto VecTy = dyn_cast<VectorType>(Target))
9004 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00009005
9006 // Strip complex types.
9007 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009008 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009009 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009010 return;
9011
John McCallacf0ee52010-10-08 02:01:28 +00009012 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009013 }
John McCall263a48b2010-01-04 23:31:57 +00009014
9015 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9016 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9017 }
9018
9019 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9020 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9021
9022 // If the source is floating point...
9023 if (SourceBT && SourceBT->isFloatingPoint()) {
9024 // ...and the target is floating point...
9025 if (TargetBT && TargetBT->isFloatingPoint()) {
9026 // ...then warn if we're dropping FP rank.
9027
9028 // Builtin FP kinds are ordered by increasing FP rank.
9029 if (SourceBT->getKind() > TargetBT->getKind()) {
9030 // Don't warn about float constants that are precisely
9031 // representable in the target type.
9032 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009033 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00009034 // Value might be a float, a float vector, or a float complex.
9035 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00009036 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9037 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00009038 return;
9039 }
9040
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009041 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009042 return;
9043
John McCallacf0ee52010-10-08 02:01:28 +00009044 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00009045 }
9046 // ... or possibly if we're increasing rank, too
9047 else if (TargetBT->getKind() > SourceBT->getKind()) {
9048 if (S.SourceMgr.isInSystemMacro(CC))
9049 return;
9050
9051 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00009052 }
9053 return;
9054 }
9055
Richard Trieube234c32016-04-21 21:04:55 +00009056 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00009057 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009058 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009059 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00009060
Richard Trieube234c32016-04-21 21:04:55 +00009061 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00009062 }
John McCall263a48b2010-01-04 23:31:57 +00009063
Richard Smith54894fd2015-12-30 01:06:52 +00009064 // Detect the case where a call result is converted from floating-point to
9065 // to bool, and the final argument to the call is converted from bool, to
9066 // discover this typo:
9067 //
9068 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9069 //
9070 // FIXME: This is an incredibly special case; is there some more general
9071 // way to detect this class of misplaced-parentheses bug?
9072 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009073 // Check last argument of function call to see if it is an
9074 // implicit cast from a type matching the type the result
9075 // is being cast to.
9076 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00009077 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009078 Expr *LastA = CEx->getArg(NumArgs - 1);
9079 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00009080 if (isa<ImplicitCastExpr>(LastA) &&
9081 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009082 // Warn on this floating-point to bool conversion
9083 DiagnoseImpCast(S, E, T, CC,
9084 diag::warn_impcast_floating_point_to_bool);
9085 }
9086 }
9087 }
John McCall263a48b2010-01-04 23:31:57 +00009088 return;
9089 }
9090
Richard Trieu5b993502014-10-15 03:42:06 +00009091 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00009092
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009093 S.DiscardMisalignedMemberAddress(Target, E);
9094
David Blaikie9366d2b2012-06-19 21:19:06 +00009095 if (!Source->isIntegerType() || !Target->isIntegerType())
9096 return;
9097
David Blaikie7555b6a2012-05-15 16:56:36 +00009098 // TODO: remove this early return once the false positives for constant->bool
9099 // in templates, macros, etc, are reduced or removed.
9100 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9101 return;
9102
John McCallcc7e5bf2010-05-06 08:58:33 +00009103 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00009104 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00009105
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009106 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00009107 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009108 // TODO: this should happen for bitfield stores, too.
9109 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00009110 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009111 if (S.SourceMgr.isInSystemMacro(CC))
9112 return;
9113
John McCall18a2c2c2010-11-09 22:22:12 +00009114 std::string PrettySourceValue = Value.toString(10);
9115 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009116
Ted Kremenek33ba9952011-10-22 02:37:33 +00009117 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9118 S.PDiag(diag::warn_impcast_integer_precision_constant)
9119 << PrettySourceValue << PrettyTargetValue
9120 << E->getType() << T << E->getSourceRange()
9121 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00009122 return;
9123 }
9124
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009125 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9126 if (S.SourceMgr.isInSystemMacro(CC))
9127 return;
9128
David Blaikie9455da02012-04-12 22:40:54 +00009129 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00009130 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9131 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00009132 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00009133 }
9134
Richard Trieudcb55572016-01-29 23:51:16 +00009135 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9136 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9137 // Warn when doing a signed to signed conversion, warn if the positive
9138 // source value is exactly the width of the target type, which will
9139 // cause a negative value to be stored.
9140
9141 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00009142 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9143 !S.SourceMgr.isInSystemMacro(CC)) {
9144 if (isSameWidthConstantConversion(S, E, T, CC)) {
9145 std::string PrettySourceValue = Value.toString(10);
9146 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00009147
Richard Trieufc404c72016-02-05 23:02:38 +00009148 S.DiagRuntimeBehavior(
9149 E->getExprLoc(), E,
9150 S.PDiag(diag::warn_impcast_integer_precision_constant)
9151 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9152 << E->getSourceRange() << clang::SourceRange(CC));
9153 return;
Richard Trieudcb55572016-01-29 23:51:16 +00009154 }
9155 }
Richard Trieufc404c72016-02-05 23:02:38 +00009156
Richard Trieudcb55572016-01-29 23:51:16 +00009157 // Fall through for non-constants to give a sign conversion warning.
9158 }
9159
John McCallcc7e5bf2010-05-06 08:58:33 +00009160 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9161 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9162 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009163 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009164 return;
9165
John McCallcc7e5bf2010-05-06 08:58:33 +00009166 unsigned DiagID = diag::warn_impcast_integer_sign;
9167
9168 // Traditionally, gcc has warned about this under -Wsign-compare.
9169 // We also want to warn about it in -Wconversion.
9170 // So if -Wconversion is off, use a completely identical diagnostic
9171 // in the sign-compare group.
9172 // The conditional-checking code will
9173 if (ICContext) {
9174 DiagID = diag::warn_impcast_integer_sign_conditional;
9175 *ICContext = true;
9176 }
9177
John McCallacf0ee52010-10-08 02:01:28 +00009178 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00009179 }
9180
Douglas Gregora78f1932011-02-22 02:45:07 +00009181 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00009182 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9183 // type, to give us better diagnostics.
9184 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009185 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00009186 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9187 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9188 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9189 SourceType = S.Context.getTypeDeclType(Enum);
9190 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9191 }
9192 }
9193
Douglas Gregora78f1932011-02-22 02:45:07 +00009194 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9195 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00009196 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9197 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009198 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009199 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009200 return;
9201
Douglas Gregor364f7db2011-03-12 00:14:31 +00009202 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00009203 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009204 }
John McCall263a48b2010-01-04 23:31:57 +00009205}
9206
David Blaikie18e9ac72012-05-15 21:57:38 +00009207void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9208 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009209
9210void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00009211 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009212 E = E->IgnoreParenImpCasts();
9213
9214 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00009215 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009216
John McCallacf0ee52010-10-08 02:01:28 +00009217 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009218 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009219 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00009220}
9221
David Blaikie18e9ac72012-05-15 21:57:38 +00009222void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9223 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00009224 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009225
9226 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00009227 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9228 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009229
9230 // If -Wconversion would have warned about either of the candidates
9231 // for a signedness conversion to the context type...
9232 if (!Suspicious) return;
9233
9234 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009235 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00009236 return;
9237
John McCallcc7e5bf2010-05-06 08:58:33 +00009238 // ...then check whether it would have warned about either of the
9239 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00009240 if (E->getType() == T) return;
9241
9242 Suspicious = false;
9243 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9244 E->getType(), CC, &Suspicious);
9245 if (!Suspicious)
9246 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00009247 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009248}
9249
Richard Trieu65724892014-11-15 06:37:39 +00009250/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9251/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009252void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00009253 if (S.getLangOpts().Bool)
9254 return;
9255 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9256}
9257
John McCallcc7e5bf2010-05-06 08:58:33 +00009258/// AnalyzeImplicitConversions - Find and report any interesting
9259/// implicit conversions in the given expression. There are a couple
9260/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009261void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00009262 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00009263 Expr *E = OrigE->IgnoreParenImpCasts();
9264
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00009265 if (E->isTypeDependent() || E->isValueDependent())
9266 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00009267
John McCallcc7e5bf2010-05-06 08:58:33 +00009268 // For conditional operators, we analyze the arguments as if they
9269 // were being fed directly into the output.
9270 if (isa<ConditionalOperator>(E)) {
9271 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00009272 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009273 return;
9274 }
9275
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009276 // Check implicit argument conversions for function calls.
9277 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9278 CheckImplicitArgumentConversions(S, Call, CC);
9279
John McCallcc7e5bf2010-05-06 08:58:33 +00009280 // Go ahead and check any implicit conversions we might have skipped.
9281 // The non-canonical typecheck is just an optimization;
9282 // CheckImplicitConversion will filter out dead implicit conversions.
9283 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009284 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009285
9286 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00009287
9288 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9289 // The bound subexpressions in a PseudoObjectExpr are not reachable
9290 // as transitive children.
9291 // FIXME: Use a more uniform representation for this.
9292 for (auto *SE : POE->semantics())
9293 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9294 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00009295 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00009296
John McCallcc7e5bf2010-05-06 08:58:33 +00009297 // Skip past explicit casts.
9298 if (isa<ExplicitCastExpr>(E)) {
9299 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00009300 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009301 }
9302
John McCalld2a53122010-11-09 23:24:47 +00009303 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9304 // Do a somewhat different check with comparison operators.
9305 if (BO->isComparisonOp())
9306 return AnalyzeComparison(S, BO);
9307
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009308 // And with simple assignments.
9309 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00009310 return AnalyzeAssignment(S, BO);
9311 }
John McCallcc7e5bf2010-05-06 08:58:33 +00009312
9313 // These break the otherwise-useful invariant below. Fortunately,
9314 // we don't really need to recurse into them, because any internal
9315 // expressions should have been analyzed already when they were
9316 // built into statements.
9317 if (isa<StmtExpr>(E)) return;
9318
9319 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00009320 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00009321
9322 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00009323 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00009324 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00009325 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00009326 for (Stmt *SubStmt : E->children()) {
9327 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00009328 if (!ChildExpr)
9329 continue;
9330
Richard Trieu955231d2014-01-25 01:10:35 +00009331 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00009332 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00009333 // Ignore checking string literals that are in logical and operators.
9334 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00009335 continue;
9336 AnalyzeImplicitConversions(S, ChildExpr, CC);
9337 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009338
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009339 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00009340 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9341 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009342 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00009343
9344 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9345 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009346 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009347 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009348
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009349 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9350 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00009351 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009352}
9353
9354} // end anonymous namespace
9355
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009356/// Diagnose integer type and any valid implicit convertion to it.
9357static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9358 // Taking into account implicit conversions,
9359 // allow any integer.
9360 if (!E->getType()->isIntegerType()) {
9361 S.Diag(E->getLocStart(),
9362 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9363 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009364 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009365 // Potentially emit standard warnings for implicit conversions if enabled
9366 // using -Wconversion.
9367 CheckImplicitConversion(S, E, IntT, E->getLocStart());
9368 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009369}
9370
Richard Trieuc1888e02014-06-28 23:25:37 +00009371// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9372// Returns true when emitting a warning about taking the address of a reference.
9373static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00009374 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00009375 E = E->IgnoreParenImpCasts();
9376
9377 const FunctionDecl *FD = nullptr;
9378
9379 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9380 if (!DRE->getDecl()->getType()->isReferenceType())
9381 return false;
9382 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9383 if (!M->getMemberDecl()->getType()->isReferenceType())
9384 return false;
9385 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00009386 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00009387 return false;
9388 FD = Call->getDirectCallee();
9389 } else {
9390 return false;
9391 }
9392
9393 SemaRef.Diag(E->getExprLoc(), PD);
9394
9395 // If possible, point to location of function.
9396 if (FD) {
9397 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9398 }
9399
9400 return true;
9401}
9402
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009403// Returns true if the SourceLocation is expanded from any macro body.
9404// Returns false if the SourceLocation is invalid, is from not in a macro
9405// expansion, or is from expanded from a top-level macro argument.
9406static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9407 if (Loc.isInvalid())
9408 return false;
9409
9410 while (Loc.isMacroID()) {
9411 if (SM.isMacroBodyExpansion(Loc))
9412 return true;
9413 Loc = SM.getImmediateMacroCallerLoc(Loc);
9414 }
9415
9416 return false;
9417}
9418
Richard Trieu3bb8b562014-02-26 02:36:06 +00009419/// \brief Diagnose pointers that are always non-null.
9420/// \param E the expression containing the pointer
9421/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9422/// compared to a null pointer
9423/// \param IsEqual True when the comparison is equal to a null pointer
9424/// \param Range Extra SourceRange to highlight in the diagnostic
9425void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9426 Expr::NullPointerConstantKind NullKind,
9427 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00009428 if (!E)
9429 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009430
9431 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009432 if (E->getExprLoc().isMacroID()) {
9433 const SourceManager &SM = getSourceManager();
9434 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9435 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00009436 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009437 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009438 E = E->IgnoreImpCasts();
9439
9440 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9441
Richard Trieuf7432752014-06-06 21:39:26 +00009442 if (isa<CXXThisExpr>(E)) {
9443 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9444 : diag::warn_this_bool_conversion;
9445 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9446 return;
9447 }
9448
Richard Trieu3bb8b562014-02-26 02:36:06 +00009449 bool IsAddressOf = false;
9450
9451 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9452 if (UO->getOpcode() != UO_AddrOf)
9453 return;
9454 IsAddressOf = true;
9455 E = UO->getSubExpr();
9456 }
9457
Richard Trieuc1888e02014-06-28 23:25:37 +00009458 if (IsAddressOf) {
9459 unsigned DiagID = IsCompare
9460 ? diag::warn_address_of_reference_null_compare
9461 : diag::warn_address_of_reference_bool_conversion;
9462 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9463 << IsEqual;
9464 if (CheckForReference(*this, E, PD)) {
9465 return;
9466 }
9467 }
9468
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009469 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9470 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00009471 std::string Str;
9472 llvm::raw_string_ostream S(Str);
9473 E->printPretty(S, nullptr, getPrintingPolicy());
9474 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9475 : diag::warn_cast_nonnull_to_bool;
9476 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9477 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009478 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00009479 };
9480
9481 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9482 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9483 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009484 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9485 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009486 return;
9487 }
9488 }
9489 }
9490
Richard Trieu3bb8b562014-02-26 02:36:06 +00009491 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00009492 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009493 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9494 D = R->getDecl();
9495 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9496 D = M->getMemberDecl();
9497 }
9498
9499 // Weak Decls can be null.
9500 if (!D || D->isWeak())
9501 return;
George Burgess IV850269a2015-12-08 22:02:00 +00009502
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009503 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00009504 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9505 if (getCurFunction() &&
9506 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009507 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9508 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009509 return;
9510 }
9511
9512 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +00009513 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +00009514 assert(ParamIter != FD->param_end());
9515 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9516
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009517 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9518 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009519 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +00009520 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009521 }
George Burgess IV850269a2015-12-08 22:02:00 +00009522
9523 for (unsigned ArgNo : NonNull->args()) {
9524 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009525 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009526 return;
9527 }
George Burgess IV850269a2015-12-08 22:02:00 +00009528 }
9529 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009530 }
9531 }
George Burgess IV850269a2015-12-08 22:02:00 +00009532 }
9533
Richard Trieu3bb8b562014-02-26 02:36:06 +00009534 QualType T = D->getType();
9535 const bool IsArray = T->isArrayType();
9536 const bool IsFunction = T->isFunctionType();
9537
Richard Trieuc1888e02014-06-28 23:25:37 +00009538 // Address of function is used to silence the function warning.
9539 if (IsAddressOf && IsFunction) {
9540 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009541 }
9542
9543 // Found nothing.
9544 if (!IsAddressOf && !IsFunction && !IsArray)
9545 return;
9546
9547 // Pretty print the expression for the diagnostic.
9548 std::string Str;
9549 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00009550 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00009551
9552 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9553 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00009554 enum {
9555 AddressOf,
9556 FunctionPointer,
9557 ArrayPointer
9558 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009559 if (IsAddressOf)
9560 DiagType = AddressOf;
9561 else if (IsFunction)
9562 DiagType = FunctionPointer;
9563 else if (IsArray)
9564 DiagType = ArrayPointer;
9565 else
9566 llvm_unreachable("Could not determine diagnostic.");
9567 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9568 << Range << IsEqual;
9569
9570 if (!IsFunction)
9571 return;
9572
9573 // Suggest '&' to silence the function warning.
9574 Diag(E->getExprLoc(), diag::note_function_warning_silence)
9575 << FixItHint::CreateInsertion(E->getLocStart(), "&");
9576
9577 // Check to see if '()' fixit should be emitted.
9578 QualType ReturnType;
9579 UnresolvedSet<4> NonTemplateOverloads;
9580 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9581 if (ReturnType.isNull())
9582 return;
9583
9584 if (IsCompare) {
9585 // There are two cases here. If there is null constant, the only suggest
9586 // for a pointer return type. If the null is 0, then suggest if the return
9587 // type is a pointer or an integer type.
9588 if (!ReturnType->isPointerType()) {
9589 if (NullKind == Expr::NPCK_ZeroExpression ||
9590 NullKind == Expr::NPCK_ZeroLiteral) {
9591 if (!ReturnType->isIntegerType())
9592 return;
9593 } else {
9594 return;
9595 }
9596 }
9597 } else { // !IsCompare
9598 // For function to bool, only suggest if the function pointer has bool
9599 // return type.
9600 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9601 return;
9602 }
9603 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00009604 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00009605}
9606
John McCallcc7e5bf2010-05-06 08:58:33 +00009607/// Diagnoses "dangerous" implicit conversions within the given
9608/// expression (which is a full expression). Implements -Wconversion
9609/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009610///
9611/// \param CC the "context" location of the implicit conversion, i.e.
9612/// the most location of the syntactic entity requiring the implicit
9613/// conversion
9614void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009615 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00009616 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00009617 return;
9618
9619 // Don't diagnose for value- or type-dependent expressions.
9620 if (E->isTypeDependent() || E->isValueDependent())
9621 return;
9622
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009623 // Check for array bounds violations in cases where the check isn't triggered
9624 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9625 // ArraySubscriptExpr is on the RHS of a variable initialization.
9626 CheckArrayAccess(E);
9627
John McCallacf0ee52010-10-08 02:01:28 +00009628 // This is not the right CC for (e.g.) a variable initialization.
9629 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009630}
9631
Richard Trieu65724892014-11-15 06:37:39 +00009632/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9633/// Input argument E is a logical expression.
9634void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9635 ::CheckBoolLikeConversion(*this, E, CC);
9636}
9637
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009638/// Diagnose when expression is an integer constant expression and its evaluation
9639/// results in integer overflow
9640void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00009641 // Use a work list to deal with nested struct initializers.
9642 SmallVector<Expr *, 2> Exprs(1, E);
9643
9644 do {
9645 Expr *E = Exprs.pop_back_val();
9646
9647 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9648 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9649 continue;
9650 }
9651
9652 if (auto InitList = dyn_cast<InitListExpr>(E))
9653 Exprs.append(InitList->inits().begin(), InitList->inits().end());
9654 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009655}
9656
Richard Smithc406cb72013-01-17 01:17:56 +00009657namespace {
9658/// \brief Visitor for expressions which looks for unsequenced operations on the
9659/// same object.
9660class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009661 typedef EvaluatedExprVisitor<SequenceChecker> Base;
9662
Richard Smithc406cb72013-01-17 01:17:56 +00009663 /// \brief A tree of sequenced regions within an expression. Two regions are
9664 /// unsequenced if one is an ancestor or a descendent of the other. When we
9665 /// finish processing an expression with sequencing, such as a comma
9666 /// expression, we fold its tree nodes into its parent, since they are
9667 /// unsequenced with respect to nodes we will visit later.
9668 class SequenceTree {
9669 struct Value {
9670 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9671 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +00009672 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +00009673 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009674 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00009675
9676 public:
9677 /// \brief A region within an expression which may be sequenced with respect
9678 /// to some other region.
9679 class Seq {
9680 explicit Seq(unsigned N) : Index(N) {}
9681 unsigned Index;
9682 friend class SequenceTree;
9683 public:
9684 Seq() : Index(0) {}
9685 };
9686
9687 SequenceTree() { Values.push_back(Value(0)); }
9688 Seq root() const { return Seq(0); }
9689
9690 /// \brief Create a new sequence of operations, which is an unsequenced
9691 /// subset of \p Parent. This sequence of operations is sequenced with
9692 /// respect to other children of \p Parent.
9693 Seq allocate(Seq Parent) {
9694 Values.push_back(Value(Parent.Index));
9695 return Seq(Values.size() - 1);
9696 }
9697
9698 /// \brief Merge a sequence of operations into its parent.
9699 void merge(Seq S) {
9700 Values[S.Index].Merged = true;
9701 }
9702
9703 /// \brief Determine whether two operations are unsequenced. This operation
9704 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9705 /// should have been merged into its parent as appropriate.
9706 bool isUnsequenced(Seq Cur, Seq Old) {
9707 unsigned C = representative(Cur.Index);
9708 unsigned Target = representative(Old.Index);
9709 while (C >= Target) {
9710 if (C == Target)
9711 return true;
9712 C = Values[C].Parent;
9713 }
9714 return false;
9715 }
9716
9717 private:
9718 /// \brief Pick a representative for a sequence.
9719 unsigned representative(unsigned K) {
9720 if (Values[K].Merged)
9721 // Perform path compression as we go.
9722 return Values[K].Parent = representative(Values[K].Parent);
9723 return K;
9724 }
9725 };
9726
9727 /// An object for which we can track unsequenced uses.
9728 typedef NamedDecl *Object;
9729
9730 /// Different flavors of object usage which we track. We only track the
9731 /// least-sequenced usage of each kind.
9732 enum UsageKind {
9733 /// A read of an object. Multiple unsequenced reads are OK.
9734 UK_Use,
9735 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00009736 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00009737 UK_ModAsValue,
9738 /// A modification of an object which is not sequenced before the value
9739 /// computation of the expression, such as n++.
9740 UK_ModAsSideEffect,
9741
9742 UK_Count = UK_ModAsSideEffect + 1
9743 };
9744
9745 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00009746 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00009747 Expr *Use;
9748 SequenceTree::Seq Seq;
9749 };
9750
9751 struct UsageInfo {
9752 UsageInfo() : Diagnosed(false) {}
9753 Usage Uses[UK_Count];
9754 /// Have we issued a diagnostic for this variable already?
9755 bool Diagnosed;
9756 };
9757 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9758
9759 Sema &SemaRef;
9760 /// Sequenced regions within the expression.
9761 SequenceTree Tree;
9762 /// Declaration modifications and references which we have seen.
9763 UsageInfoMap UsageMap;
9764 /// The region we are currently within.
9765 SequenceTree::Seq Region;
9766 /// Filled in with declarations which were modified as a side-effect
9767 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009768 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00009769 /// Expressions to check later. We defer checking these to reduce
9770 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009771 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00009772
9773 /// RAII object wrapping the visitation of a sequenced subexpression of an
9774 /// expression. At the end of this process, the side-effects of the evaluation
9775 /// become sequenced with respect to the value computation of the result, so
9776 /// we downgrade any UK_ModAsSideEffect within the evaluation to
9777 /// UK_ModAsValue.
9778 struct SequencedSubexpression {
9779 SequencedSubexpression(SequenceChecker &Self)
9780 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9781 Self.ModAsSideEffect = &ModAsSideEffect;
9782 }
9783 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +00009784 for (auto &M : llvm::reverse(ModAsSideEffect)) {
9785 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +00009786 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +00009787 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9788 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +00009789 }
9790 Self.ModAsSideEffect = OldModAsSideEffect;
9791 }
9792
9793 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009794 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9795 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00009796 };
9797
Richard Smith40238f02013-06-20 22:21:56 +00009798 /// RAII object wrapping the visitation of a subexpression which we might
9799 /// choose to evaluate as a constant. If any subexpression is evaluated and
9800 /// found to be non-constant, this allows us to suppress the evaluation of
9801 /// the outer expression.
9802 class EvaluationTracker {
9803 public:
9804 EvaluationTracker(SequenceChecker &Self)
9805 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9806 Self.EvalTracker = this;
9807 }
9808 ~EvaluationTracker() {
9809 Self.EvalTracker = Prev;
9810 if (Prev)
9811 Prev->EvalOK &= EvalOK;
9812 }
9813
9814 bool evaluate(const Expr *E, bool &Result) {
9815 if (!EvalOK || E->isValueDependent())
9816 return false;
9817 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9818 return EvalOK;
9819 }
9820
9821 private:
9822 SequenceChecker &Self;
9823 EvaluationTracker *Prev;
9824 bool EvalOK;
9825 } *EvalTracker;
9826
Richard Smithc406cb72013-01-17 01:17:56 +00009827 /// \brief Find the object which is produced by the specified expression,
9828 /// if any.
9829 Object getObject(Expr *E, bool Mod) const {
9830 E = E->IgnoreParenCasts();
9831 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9832 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9833 return getObject(UO->getSubExpr(), Mod);
9834 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9835 if (BO->getOpcode() == BO_Comma)
9836 return getObject(BO->getRHS(), Mod);
9837 if (Mod && BO->isAssignmentOp())
9838 return getObject(BO->getLHS(), Mod);
9839 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9840 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9841 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9842 return ME->getMemberDecl();
9843 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9844 // FIXME: If this is a reference, map through to its value.
9845 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00009846 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00009847 }
9848
9849 /// \brief Note that an object was modified or used by an expression.
9850 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9851 Usage &U = UI.Uses[UK];
9852 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9853 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9854 ModAsSideEffect->push_back(std::make_pair(O, U));
9855 U.Use = Ref;
9856 U.Seq = Region;
9857 }
9858 }
9859 /// \brief Check whether a modification or use conflicts with a prior usage.
9860 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9861 bool IsModMod) {
9862 if (UI.Diagnosed)
9863 return;
9864
9865 const Usage &U = UI.Uses[OtherKind];
9866 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9867 return;
9868
9869 Expr *Mod = U.Use;
9870 Expr *ModOrUse = Ref;
9871 if (OtherKind == UK_Use)
9872 std::swap(Mod, ModOrUse);
9873
9874 SemaRef.Diag(Mod->getExprLoc(),
9875 IsModMod ? diag::warn_unsequenced_mod_mod
9876 : diag::warn_unsequenced_mod_use)
9877 << O << SourceRange(ModOrUse->getExprLoc());
9878 UI.Diagnosed = true;
9879 }
9880
9881 void notePreUse(Object O, Expr *Use) {
9882 UsageInfo &U = UsageMap[O];
9883 // Uses conflict with other modifications.
9884 checkUsage(O, U, Use, UK_ModAsValue, false);
9885 }
9886 void notePostUse(Object O, Expr *Use) {
9887 UsageInfo &U = UsageMap[O];
9888 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9889 addUsage(U, O, Use, UK_Use);
9890 }
9891
9892 void notePreMod(Object O, Expr *Mod) {
9893 UsageInfo &U = UsageMap[O];
9894 // Modifications conflict with other modifications and with uses.
9895 checkUsage(O, U, Mod, UK_ModAsValue, true);
9896 checkUsage(O, U, Mod, UK_Use, false);
9897 }
9898 void notePostMod(Object O, Expr *Use, UsageKind UK) {
9899 UsageInfo &U = UsageMap[O];
9900 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9901 addUsage(U, O, Use, UK);
9902 }
9903
9904public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009905 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00009906 : Base(S.Context), SemaRef(S), Region(Tree.root()),
9907 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009908 Visit(E);
9909 }
9910
9911 void VisitStmt(Stmt *S) {
9912 // Skip all statements which aren't expressions for now.
9913 }
9914
9915 void VisitExpr(Expr *E) {
9916 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00009917 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00009918 }
9919
9920 void VisitCastExpr(CastExpr *E) {
9921 Object O = Object();
9922 if (E->getCastKind() == CK_LValueToRValue)
9923 O = getObject(E->getSubExpr(), false);
9924
9925 if (O)
9926 notePreUse(O, E);
9927 VisitExpr(E);
9928 if (O)
9929 notePostUse(O, E);
9930 }
9931
9932 void VisitBinComma(BinaryOperator *BO) {
9933 // C++11 [expr.comma]p1:
9934 // Every value computation and side effect associated with the left
9935 // expression is sequenced before every value computation and side
9936 // effect associated with the right expression.
9937 SequenceTree::Seq LHS = Tree.allocate(Region);
9938 SequenceTree::Seq RHS = Tree.allocate(Region);
9939 SequenceTree::Seq OldRegion = Region;
9940
9941 {
9942 SequencedSubexpression SeqLHS(*this);
9943 Region = LHS;
9944 Visit(BO->getLHS());
9945 }
9946
9947 Region = RHS;
9948 Visit(BO->getRHS());
9949
9950 Region = OldRegion;
9951
9952 // Forget that LHS and RHS are sequenced. They are both unsequenced
9953 // with respect to other stuff.
9954 Tree.merge(LHS);
9955 Tree.merge(RHS);
9956 }
9957
9958 void VisitBinAssign(BinaryOperator *BO) {
9959 // The modification is sequenced after the value computation of the LHS
9960 // and RHS, so check it before inspecting the operands and update the
9961 // map afterwards.
9962 Object O = getObject(BO->getLHS(), true);
9963 if (!O)
9964 return VisitExpr(BO);
9965
9966 notePreMod(O, BO);
9967
9968 // C++11 [expr.ass]p7:
9969 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
9970 // only once.
9971 //
9972 // Therefore, for a compound assignment operator, O is considered used
9973 // everywhere except within the evaluation of E1 itself.
9974 if (isa<CompoundAssignOperator>(BO))
9975 notePreUse(O, BO);
9976
9977 Visit(BO->getLHS());
9978
9979 if (isa<CompoundAssignOperator>(BO))
9980 notePostUse(O, BO);
9981
9982 Visit(BO->getRHS());
9983
Richard Smith83e37bee2013-06-26 23:16:51 +00009984 // C++11 [expr.ass]p1:
9985 // the assignment is sequenced [...] before the value computation of the
9986 // assignment expression.
9987 // C11 6.5.16/3 has no such rule.
9988 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9989 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00009990 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009991
Richard Smithc406cb72013-01-17 01:17:56 +00009992 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
9993 VisitBinAssign(CAO);
9994 }
9995
9996 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9997 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9998 void VisitUnaryPreIncDec(UnaryOperator *UO) {
9999 Object O = getObject(UO->getSubExpr(), true);
10000 if (!O)
10001 return VisitExpr(UO);
10002
10003 notePreMod(O, UO);
10004 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000010005 // C++11 [expr.pre.incr]p1:
10006 // the expression ++x is equivalent to x+=1
10007 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10008 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010009 }
10010
10011 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10012 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10013 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10014 Object O = getObject(UO->getSubExpr(), true);
10015 if (!O)
10016 return VisitExpr(UO);
10017
10018 notePreMod(O, UO);
10019 Visit(UO->getSubExpr());
10020 notePostMod(O, UO, UK_ModAsSideEffect);
10021 }
10022
10023 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10024 void VisitBinLOr(BinaryOperator *BO) {
10025 // The side-effects of the LHS of an '&&' are sequenced before the
10026 // value computation of the RHS, and hence before the value computation
10027 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10028 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000010029 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010030 {
10031 SequencedSubexpression Sequenced(*this);
10032 Visit(BO->getLHS());
10033 }
10034
10035 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010036 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010037 if (!Result)
10038 Visit(BO->getRHS());
10039 } else {
10040 // Check for unsequenced operations in the RHS, treating it as an
10041 // entirely separate evaluation.
10042 //
10043 // FIXME: If there are operations in the RHS which are unsequenced
10044 // with respect to operations outside the RHS, and those operations
10045 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000010046 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010047 }
Richard Smithc406cb72013-01-17 01:17:56 +000010048 }
10049 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000010050 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010051 {
10052 SequencedSubexpression Sequenced(*this);
10053 Visit(BO->getLHS());
10054 }
10055
10056 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010057 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010058 if (Result)
10059 Visit(BO->getRHS());
10060 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000010061 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010062 }
Richard Smithc406cb72013-01-17 01:17:56 +000010063 }
10064
10065 // Only visit the condition, unless we can be sure which subexpression will
10066 // be chosen.
10067 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000010068 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000010069 {
10070 SequencedSubexpression Sequenced(*this);
10071 Visit(CO->getCond());
10072 }
Richard Smithc406cb72013-01-17 01:17:56 +000010073
10074 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010075 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000010076 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010077 else {
Richard Smithd33f5202013-01-17 23:18:09 +000010078 WorkList.push_back(CO->getTrueExpr());
10079 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010080 }
Richard Smithc406cb72013-01-17 01:17:56 +000010081 }
10082
Richard Smithe3dbfe02013-06-30 10:40:20 +000010083 void VisitCallExpr(CallExpr *CE) {
10084 // C++11 [intro.execution]p15:
10085 // When calling a function [...], every value computation and side effect
10086 // associated with any argument expression, or with the postfix expression
10087 // designating the called function, is sequenced before execution of every
10088 // expression or statement in the body of the function [and thus before
10089 // the value computation of its result].
10090 SequencedSubexpression Sequenced(*this);
10091 Base::VisitCallExpr(CE);
10092
10093 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10094 }
10095
Richard Smithc406cb72013-01-17 01:17:56 +000010096 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010097 // This is a call, so all subexpressions are sequenced before the result.
10098 SequencedSubexpression Sequenced(*this);
10099
Richard Smithc406cb72013-01-17 01:17:56 +000010100 if (!CCE->isListInitialization())
10101 return VisitExpr(CCE);
10102
10103 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010104 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010105 SequenceTree::Seq Parent = Region;
10106 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10107 E = CCE->arg_end();
10108 I != E; ++I) {
10109 Region = Tree.allocate(Parent);
10110 Elts.push_back(Region);
10111 Visit(*I);
10112 }
10113
10114 // Forget that the initializers are sequenced.
10115 Region = Parent;
10116 for (unsigned I = 0; I < Elts.size(); ++I)
10117 Tree.merge(Elts[I]);
10118 }
10119
10120 void VisitInitListExpr(InitListExpr *ILE) {
10121 if (!SemaRef.getLangOpts().CPlusPlus11)
10122 return VisitExpr(ILE);
10123
10124 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010125 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010126 SequenceTree::Seq Parent = Region;
10127 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10128 Expr *E = ILE->getInit(I);
10129 if (!E) continue;
10130 Region = Tree.allocate(Parent);
10131 Elts.push_back(Region);
10132 Visit(E);
10133 }
10134
10135 // Forget that the initializers are sequenced.
10136 Region = Parent;
10137 for (unsigned I = 0; I < Elts.size(); ++I)
10138 Tree.merge(Elts[I]);
10139 }
10140};
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010141} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +000010142
10143void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010144 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000010145 WorkList.push_back(E);
10146 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000010147 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000010148 SequenceChecker(*this, Item, WorkList);
10149 }
Richard Smithc406cb72013-01-17 01:17:56 +000010150}
10151
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010152void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10153 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010154 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000010155 if (!E->isInstantiationDependent())
10156 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010157 if (!IsConstexpr && !E->isValueDependent())
10158 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010159 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000010160}
10161
John McCall1f425642010-11-11 03:21:53 +000010162void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10163 FieldDecl *BitField,
10164 Expr *Init) {
10165 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10166}
10167
David Majnemer61a5bbf2015-04-07 22:08:51 +000010168static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10169 SourceLocation Loc) {
10170 if (!PType->isVariablyModifiedType())
10171 return;
10172 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10173 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10174 return;
10175 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000010176 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10177 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10178 return;
10179 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000010180 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10181 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10182 return;
10183 }
10184
10185 const ArrayType *AT = S.Context.getAsArrayType(PType);
10186 if (!AT)
10187 return;
10188
10189 if (AT->getSizeModifier() != ArrayType::Star) {
10190 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10191 return;
10192 }
10193
10194 S.Diag(Loc, diag::err_array_star_in_function_definition);
10195}
10196
Mike Stump0c2ec772010-01-21 03:59:47 +000010197/// CheckParmsForFunctionDef - Check that the parameters of the given
10198/// function are appropriate for the definition of a function. This
10199/// takes care of any checks that cannot be performed on the
10200/// declaration itself, e.g., that the types of each of the function
10201/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000010202bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000010203 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010204 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000010205 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010206 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10207 // function declarator that is part of a function definition of
10208 // that function shall not have incomplete type.
10209 //
10210 // This is also C++ [dcl.fct]p6.
10211 if (!Param->isInvalidDecl() &&
10212 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010213 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010214 Param->setInvalidDecl();
10215 HasInvalidParm = true;
10216 }
10217
10218 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10219 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000010220 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000010221 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000010222 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000010223 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000010224 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000010225
10226 // C99 6.7.5.3p12:
10227 // If the function declarator is not part of a definition of that
10228 // function, parameters may have incomplete type and may use the [*]
10229 // notation in their sequences of declarator specifiers to specify
10230 // variable length array types.
10231 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000010232 // FIXME: This diagnostic should point the '[*]' if source-location
10233 // information is added for it.
10234 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010235
10236 // MSVC destroys objects passed by value in the callee. Therefore a
10237 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010238 // object's destructor. However, we don't perform any direct access check
10239 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +000010240 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10241 .getCXXABI()
10242 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +000010243 if (!Param->isInvalidDecl()) {
10244 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10245 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10246 if (!ClassDecl->isInvalidDecl() &&
10247 !ClassDecl->hasIrrelevantDestructor() &&
10248 !ClassDecl->isDependentContext()) {
10249 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10250 MarkFunctionReferenced(Param->getLocation(), Destructor);
10251 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10252 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010253 }
10254 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010255 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010256
10257 // Parameters with the pass_object_size attribute only need to be marked
10258 // constant at function definitions. Because we lack information about
10259 // whether we're on a declaration or definition when we're instantiating the
10260 // attribute, we need to check for constness here.
10261 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10262 if (!Param->getType().isConstQualified())
10263 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10264 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000010265 }
10266
10267 return HasInvalidParm;
10268}
John McCall2b5c1b22010-08-12 21:44:57 +000010269
10270/// CheckCastAlign - Implements -Wcast-align, which warns when a
10271/// pointer cast increases the alignment requirements.
10272void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10273 // This is actually a lot of work to potentially be doing on every
10274 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010275 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000010276 return;
10277
10278 // Ignore dependent types.
10279 if (T->isDependentType() || Op->getType()->isDependentType())
10280 return;
10281
10282 // Require that the destination be a pointer type.
10283 const PointerType *DestPtr = T->getAs<PointerType>();
10284 if (!DestPtr) return;
10285
10286 // If the destination has alignment 1, we're done.
10287 QualType DestPointee = DestPtr->getPointeeType();
10288 if (DestPointee->isIncompleteType()) return;
10289 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10290 if (DestAlign.isOne()) return;
10291
10292 // Require that the source be a pointer type.
10293 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10294 if (!SrcPtr) return;
10295 QualType SrcPointee = SrcPtr->getPointeeType();
10296
10297 // Whitelist casts from cv void*. We already implicitly
10298 // whitelisted casts to cv void*, since they have alignment 1.
10299 // Also whitelist casts involving incomplete types, which implicitly
10300 // includes 'void'.
10301 if (SrcPointee->isIncompleteType()) return;
10302
10303 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
10304 if (SrcAlign >= DestAlign) return;
10305
10306 Diag(TRange.getBegin(), diag::warn_cast_align)
10307 << Op->getType() << T
10308 << static_cast<unsigned>(SrcAlign.getQuantity())
10309 << static_cast<unsigned>(DestAlign.getQuantity())
10310 << TRange << Op->getSourceRange();
10311}
10312
Chandler Carruth28389f02011-08-05 09:10:50 +000010313/// \brief Check whether this array fits the idiom of a size-one tail padded
10314/// array member of a struct.
10315///
10316/// We avoid emitting out-of-bounds access warnings for such arrays as they are
10317/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000010318static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000010319 const NamedDecl *ND) {
10320 if (Size != 1 || !ND) return false;
10321
10322 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10323 if (!FD) return false;
10324
10325 // Don't consider sizes resulting from macro expansions or template argument
10326 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000010327
10328 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010329 while (TInfo) {
10330 TypeLoc TL = TInfo->getTypeLoc();
10331 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000010332 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10333 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010334 TInfo = TDL->getTypeSourceInfo();
10335 continue;
10336 }
David Blaikie6adc78e2013-02-18 22:06:02 +000010337 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10338 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000010339 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10340 return false;
10341 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010342 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000010343 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010344
10345 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000010346 if (!RD) return false;
10347 if (RD->isUnion()) return false;
10348 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10349 if (!CRD->isStandardLayout()) return false;
10350 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010351
Benjamin Kramer8c543672011-08-06 03:04:42 +000010352 // See if this is the last field decl in the record.
10353 const Decl *D = FD;
10354 while ((D = D->getNextDeclInContext()))
10355 if (isa<FieldDecl>(D))
10356 return false;
10357 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000010358}
10359
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010360void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010361 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000010362 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010363 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010364 if (IndexExpr->isValueDependent())
10365 return;
10366
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010367 const Type *EffectiveType =
10368 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010369 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010370 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010371 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010372 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000010373 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000010374
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010375 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000010376 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000010377 return;
Richard Smith13f67182011-12-16 19:31:14 +000010378 if (IndexNegated)
10379 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000010380
Craig Topperc3ec1492014-05-26 06:22:03 +000010381 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000010382 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10383 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +000010384 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +000010385 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +000010386
Ted Kremeneke4b316c2011-02-23 23:06:04 +000010387 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010388 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000010389 if (!size.isStrictlyPositive())
10390 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010391
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010392 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000010393 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010394 // Make sure we're comparing apples to apples when comparing index to size
10395 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10396 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000010397 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000010398 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010399 if (ptrarith_typesize != array_typesize) {
10400 // There's a cast to a different size type involved
10401 uint64_t ratio = array_typesize / ptrarith_typesize;
10402 // TODO: Be smarter about handling cases where array_typesize is not a
10403 // multiple of ptrarith_typesize
10404 if (ptrarith_typesize * ratio == array_typesize)
10405 size *= llvm::APInt(size.getBitWidth(), ratio);
10406 }
10407 }
10408
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010409 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010410 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010411 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010412 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010413
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010414 // For array subscripting the index must be less than size, but for pointer
10415 // arithmetic also allow the index (offset) to be equal to size since
10416 // computing the next address after the end of the array is legal and
10417 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010418 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000010419 return;
10420
10421 // Also don't warn for arrays of size 1 which are members of some
10422 // structure. These are often used to approximate flexible arrays in C89
10423 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010424 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000010425 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010426
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010427 // Suppress the warning if the subscript expression (as identified by the
10428 // ']' location) and the index expression are both from macro expansions
10429 // within a system header.
10430 if (ASE) {
10431 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10432 ASE->getRBracketLoc());
10433 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10434 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10435 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000010436 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010437 return;
10438 }
10439 }
10440
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010441 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010442 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010443 DiagID = diag::warn_array_index_exceeds_bounds;
10444
10445 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10446 PDiag(DiagID) << index.toString(10, true)
10447 << size.toString(10, true)
10448 << (unsigned)size.getLimitedValue(~0U)
10449 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010450 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010451 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010452 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010453 DiagID = diag::warn_ptr_arith_precedes_bounds;
10454 if (index.isNegative()) index = -index;
10455 }
10456
10457 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10458 PDiag(DiagID) << index.toString(10, true)
10459 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000010460 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000010461
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000010462 if (!ND) {
10463 // Try harder to find a NamedDecl to point at in the note.
10464 while (const ArraySubscriptExpr *ASE =
10465 dyn_cast<ArraySubscriptExpr>(BaseExpr))
10466 BaseExpr = ASE->getBase()->IgnoreParenCasts();
10467 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10468 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10469 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10470 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10471 }
10472
Chandler Carruth1af88f12011-02-17 21:10:52 +000010473 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010474 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10475 PDiag(diag::note_array_index_out_of_bounds)
10476 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000010477}
10478
Ted Kremenekdf26df72011-03-01 18:41:00 +000010479void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010480 int AllowOnePastEnd = 0;
10481 while (expr) {
10482 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000010483 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010484 case Stmt::ArraySubscriptExprClass: {
10485 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010486 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010487 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +000010488 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010489 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010490 case Stmt::OMPArraySectionExprClass: {
10491 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10492 if (ASE->getLowerBound())
10493 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10494 /*ASE=*/nullptr, AllowOnePastEnd > 0);
10495 return;
10496 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010497 case Stmt::UnaryOperatorClass: {
10498 // Only unwrap the * and & unary operators
10499 const UnaryOperator *UO = cast<UnaryOperator>(expr);
10500 expr = UO->getSubExpr();
10501 switch (UO->getOpcode()) {
10502 case UO_AddrOf:
10503 AllowOnePastEnd++;
10504 break;
10505 case UO_Deref:
10506 AllowOnePastEnd--;
10507 break;
10508 default:
10509 return;
10510 }
10511 break;
10512 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010513 case Stmt::ConditionalOperatorClass: {
10514 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10515 if (const Expr *lhs = cond->getLHS())
10516 CheckArrayAccess(lhs);
10517 if (const Expr *rhs = cond->getRHS())
10518 CheckArrayAccess(rhs);
10519 return;
10520 }
10521 default:
10522 return;
10523 }
Peter Collingbourne91147592011-04-15 00:35:48 +000010524 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010525}
John McCall31168b02011-06-15 23:02:42 +000010526
10527//===--- CHECK: Objective-C retain cycles ----------------------------------//
10528
10529namespace {
10530 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +000010531 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +000010532 VarDecl *Variable;
10533 SourceRange Range;
10534 SourceLocation Loc;
10535 bool Indirect;
10536
10537 void setLocsFrom(Expr *e) {
10538 Loc = e->getExprLoc();
10539 Range = e->getSourceRange();
10540 }
10541 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010542} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010543
10544/// Consider whether capturing the given variable can possibly lead to
10545/// a retain cycle.
10546static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010547 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000010548 // lifetime. In MRR, it's captured strongly if the variable is
10549 // __block and has an appropriate type.
10550 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10551 return false;
10552
10553 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010554 if (ref)
10555 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000010556 return true;
10557}
10558
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010559static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000010560 while (true) {
10561 e = e->IgnoreParens();
10562 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10563 switch (cast->getCastKind()) {
10564 case CK_BitCast:
10565 case CK_LValueBitCast:
10566 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000010567 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000010568 e = cast->getSubExpr();
10569 continue;
10570
John McCall31168b02011-06-15 23:02:42 +000010571 default:
10572 return false;
10573 }
10574 }
10575
10576 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10577 ObjCIvarDecl *ivar = ref->getDecl();
10578 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10579 return false;
10580
10581 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010582 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000010583 return false;
10584
10585 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10586 owner.Indirect = true;
10587 return true;
10588 }
10589
10590 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10591 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10592 if (!var) return false;
10593 return considerVariable(var, ref, owner);
10594 }
10595
John McCall31168b02011-06-15 23:02:42 +000010596 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10597 if (member->isArrow()) return false;
10598
10599 // Don't count this as an indirect ownership.
10600 e = member->getBase();
10601 continue;
10602 }
10603
John McCallfe96e0b2011-11-06 09:01:30 +000010604 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10605 // Only pay attention to pseudo-objects on property references.
10606 ObjCPropertyRefExpr *pre
10607 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10608 ->IgnoreParens());
10609 if (!pre) return false;
10610 if (pre->isImplicitProperty()) return false;
10611 ObjCPropertyDecl *property = pre->getExplicitProperty();
10612 if (!property->isRetaining() &&
10613 !(property->getPropertyIvarDecl() &&
10614 property->getPropertyIvarDecl()->getType()
10615 .getObjCLifetime() == Qualifiers::OCL_Strong))
10616 return false;
10617
10618 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010619 if (pre->isSuperReceiver()) {
10620 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10621 if (!owner.Variable)
10622 return false;
10623 owner.Loc = pre->getLocation();
10624 owner.Range = pre->getSourceRange();
10625 return true;
10626 }
John McCallfe96e0b2011-11-06 09:01:30 +000010627 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10628 ->getSourceExpr());
10629 continue;
10630 }
10631
John McCall31168b02011-06-15 23:02:42 +000010632 // Array ivars?
10633
10634 return false;
10635 }
10636}
10637
10638namespace {
10639 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10640 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10641 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010642 Context(Context), Variable(variable), Capturer(nullptr),
10643 VarWillBeReased(false) {}
10644 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000010645 VarDecl *Variable;
10646 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010647 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +000010648
10649 void VisitDeclRefExpr(DeclRefExpr *ref) {
10650 if (ref->getDecl() == Variable && !Capturer)
10651 Capturer = ref;
10652 }
10653
John McCall31168b02011-06-15 23:02:42 +000010654 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10655 if (Capturer) return;
10656 Visit(ref->getBase());
10657 if (Capturer && ref->isFreeIvar())
10658 Capturer = ref;
10659 }
10660
10661 void VisitBlockExpr(BlockExpr *block) {
10662 // Look inside nested blocks
10663 if (block->getBlockDecl()->capturesVariable(Variable))
10664 Visit(block->getBlockDecl()->getBody());
10665 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000010666
10667 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
10668 if (Capturer) return;
10669 if (OVE->getSourceExpr())
10670 Visit(OVE->getSourceExpr());
10671 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010672 void VisitBinaryOperator(BinaryOperator *BinOp) {
10673 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
10674 return;
10675 Expr *LHS = BinOp->getLHS();
10676 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
10677 if (DRE->getDecl() != Variable)
10678 return;
10679 if (Expr *RHS = BinOp->getRHS()) {
10680 RHS = RHS->IgnoreParenCasts();
10681 llvm::APSInt Value;
10682 VarWillBeReased =
10683 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
10684 }
10685 }
10686 }
John McCall31168b02011-06-15 23:02:42 +000010687 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010688} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010689
10690/// Check whether the given argument is a block which captures a
10691/// variable.
10692static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
10693 assert(owner.Variable && owner.Loc.isValid());
10694
10695 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000010696
10697 // Look through [^{...} copy] and Block_copy(^{...}).
10698 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
10699 Selector Cmd = ME->getSelector();
10700 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
10701 e = ME->getInstanceReceiver();
10702 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000010703 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000010704 e = e->IgnoreParenCasts();
10705 }
10706 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
10707 if (CE->getNumArgs() == 1) {
10708 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000010709 if (Fn) {
10710 const IdentifierInfo *FnI = Fn->getIdentifier();
10711 if (FnI && FnI->isStr("_Block_copy")) {
10712 e = CE->getArg(0)->IgnoreParenCasts();
10713 }
10714 }
Jordan Rose67e887c2012-09-17 17:54:30 +000010715 }
10716 }
10717
John McCall31168b02011-06-15 23:02:42 +000010718 BlockExpr *block = dyn_cast<BlockExpr>(e);
10719 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000010720 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000010721
10722 FindCaptureVisitor visitor(S.Context, owner.Variable);
10723 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010724 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000010725}
10726
10727static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10728 RetainCycleOwner &owner) {
10729 assert(capturer);
10730 assert(owner.Variable && owner.Loc.isValid());
10731
10732 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10733 << owner.Variable << capturer->getSourceRange();
10734 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10735 << owner.Indirect << owner.Range;
10736}
10737
10738/// Check for a keyword selector that starts with the word 'add' or
10739/// 'set'.
10740static bool isSetterLikeSelector(Selector sel) {
10741 if (sel.isUnarySelector()) return false;
10742
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010743 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000010744 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010745 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000010746 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010747 else if (str.startswith("add")) {
10748 // Specially whitelist 'addOperationWithBlock:'.
10749 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
10750 return false;
10751 str = str.substr(3);
10752 }
John McCall31168b02011-06-15 23:02:42 +000010753 else
10754 return false;
10755
10756 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000010757 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000010758}
10759
Benjamin Kramer3a743452015-03-09 15:03:32 +000010760static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
10761 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010762 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
10763 Message->getReceiverInterface(),
10764 NSAPI::ClassId_NSMutableArray);
10765 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010766 return None;
10767 }
10768
10769 Selector Sel = Message->getSelector();
10770
10771 Optional<NSAPI::NSArrayMethodKind> MKOpt =
10772 S.NSAPIObj->getNSArrayMethodKind(Sel);
10773 if (!MKOpt) {
10774 return None;
10775 }
10776
10777 NSAPI::NSArrayMethodKind MK = *MKOpt;
10778
10779 switch (MK) {
10780 case NSAPI::NSMutableArr_addObject:
10781 case NSAPI::NSMutableArr_insertObjectAtIndex:
10782 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
10783 return 0;
10784 case NSAPI::NSMutableArr_replaceObjectAtIndex:
10785 return 1;
10786
10787 default:
10788 return None;
10789 }
10790
10791 return None;
10792}
10793
10794static
10795Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10796 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010797 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10798 Message->getReceiverInterface(),
10799 NSAPI::ClassId_NSMutableDictionary);
10800 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010801 return None;
10802 }
10803
10804 Selector Sel = Message->getSelector();
10805
10806 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10807 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10808 if (!MKOpt) {
10809 return None;
10810 }
10811
10812 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10813
10814 switch (MK) {
10815 case NSAPI::NSMutableDict_setObjectForKey:
10816 case NSAPI::NSMutableDict_setValueForKey:
10817 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10818 return 0;
10819
10820 default:
10821 return None;
10822 }
10823
10824 return None;
10825}
10826
10827static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010828 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10829 Message->getReceiverInterface(),
10830 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000010831
Alex Denisov5dfac812015-08-06 04:51:14 +000010832 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10833 Message->getReceiverInterface(),
10834 NSAPI::ClassId_NSMutableOrderedSet);
10835 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010836 return None;
10837 }
10838
10839 Selector Sel = Message->getSelector();
10840
10841 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10842 if (!MKOpt) {
10843 return None;
10844 }
10845
10846 NSAPI::NSSetMethodKind MK = *MKOpt;
10847
10848 switch (MK) {
10849 case NSAPI::NSMutableSet_addObject:
10850 case NSAPI::NSOrderedSet_setObjectAtIndex:
10851 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10852 case NSAPI::NSOrderedSet_insertObjectAtIndex:
10853 return 0;
10854 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10855 return 1;
10856 }
10857
10858 return None;
10859}
10860
10861void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10862 if (!Message->isInstanceMessage()) {
10863 return;
10864 }
10865
10866 Optional<int> ArgOpt;
10867
10868 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10869 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10870 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10871 return;
10872 }
10873
10874 int ArgIndex = *ArgOpt;
10875
Alex Denisove1d882c2015-03-04 17:55:52 +000010876 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10877 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10878 Arg = OE->getSourceExpr()->IgnoreImpCasts();
10879 }
10880
Alex Denisov5dfac812015-08-06 04:51:14 +000010881 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010882 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010883 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010884 Diag(Message->getSourceRange().getBegin(),
10885 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000010886 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000010887 }
10888 }
Alex Denisov5dfac812015-08-06 04:51:14 +000010889 } else {
10890 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10891
10892 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10893 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10894 }
10895
10896 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10897 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10898 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10899 ValueDecl *Decl = ReceiverRE->getDecl();
10900 Diag(Message->getSourceRange().getBegin(),
10901 diag::warn_objc_circular_container)
10902 << Decl->getName() << Decl->getName();
10903 if (!ArgRE->isObjCSelfExpr()) {
10904 Diag(Decl->getLocation(),
10905 diag::note_objc_circular_container_declared_here)
10906 << Decl->getName();
10907 }
10908 }
10909 }
10910 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
10911 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
10912 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
10913 ObjCIvarDecl *Decl = IvarRE->getDecl();
10914 Diag(Message->getSourceRange().getBegin(),
10915 diag::warn_objc_circular_container)
10916 << Decl->getName() << Decl->getName();
10917 Diag(Decl->getLocation(),
10918 diag::note_objc_circular_container_declared_here)
10919 << Decl->getName();
10920 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010921 }
10922 }
10923 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010924}
10925
John McCall31168b02011-06-15 23:02:42 +000010926/// Check a message send to see if it's likely to cause a retain cycle.
10927void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
10928 // Only check instance methods whose selector looks like a setter.
10929 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
10930 return;
10931
10932 // Try to find a variable that the receiver is strongly owned by.
10933 RetainCycleOwner owner;
10934 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010935 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000010936 return;
10937 } else {
10938 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
10939 owner.Variable = getCurMethodDecl()->getSelfDecl();
10940 owner.Loc = msg->getSuperLoc();
10941 owner.Range = msg->getSuperLoc();
10942 }
10943
10944 // Check whether the receiver is captured by any of the arguments.
10945 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
10946 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
10947 return diagnoseRetainCycle(*this, capturer, owner);
10948}
10949
10950/// Check a property assign to see if it's likely to cause a retain cycle.
10951void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
10952 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010953 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000010954 return;
10955
10956 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
10957 diagnoseRetainCycle(*this, capturer, owner);
10958}
10959
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010960void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
10961 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000010962 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010963 return;
10964
10965 // Because we don't have an expression for the variable, we have to set the
10966 // location explicitly here.
10967 Owner.Loc = Var->getLocation();
10968 Owner.Range = Var->getSourceRange();
10969
10970 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
10971 diagnoseRetainCycle(*this, Capturer, Owner);
10972}
10973
Ted Kremenek9304da92012-12-21 08:04:28 +000010974static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
10975 Expr *RHS, bool isProperty) {
10976 // Check if RHS is an Objective-C object literal, which also can get
10977 // immediately zapped in a weak reference. Note that we explicitly
10978 // allow ObjCStringLiterals, since those are designed to never really die.
10979 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010980
Ted Kremenek64873352012-12-21 22:46:35 +000010981 // This enum needs to match with the 'select' in
10982 // warn_objc_arc_literal_assign (off-by-1).
10983 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
10984 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
10985 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010986
10987 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000010988 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000010989 << (isProperty ? 0 : 1)
10990 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010991
10992 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000010993}
10994
Ted Kremenekc1f014a2012-12-21 19:45:30 +000010995static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
10996 Qualifiers::ObjCLifetime LT,
10997 Expr *RHS, bool isProperty) {
10998 // Strip off any implicit cast added to get to the one ARC-specific.
10999 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11000 if (cast->getCastKind() == CK_ARCConsumeObject) {
11001 S.Diag(Loc, diag::warn_arc_retained_assign)
11002 << (LT == Qualifiers::OCL_ExplicitNone)
11003 << (isProperty ? 0 : 1)
11004 << RHS->getSourceRange();
11005 return true;
11006 }
11007 RHS = cast->getSubExpr();
11008 }
11009
11010 if (LT == Qualifiers::OCL_Weak &&
11011 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11012 return true;
11013
11014 return false;
11015}
11016
Ted Kremenekb36234d2012-12-21 08:04:20 +000011017bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11018 QualType LHS, Expr *RHS) {
11019 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11020
11021 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11022 return false;
11023
11024 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11025 return true;
11026
11027 return false;
11028}
11029
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011030void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11031 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011032 QualType LHSType;
11033 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011034 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011035 ObjCPropertyRefExpr *PRE
11036 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11037 if (PRE && !PRE->isImplicitProperty()) {
11038 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11039 if (PD)
11040 LHSType = PD->getType();
11041 }
11042
11043 if (LHSType.isNull())
11044 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000011045
11046 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11047
11048 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011049 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000011050 getCurFunction()->markSafeWeakUse(LHS);
11051 }
11052
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011053 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11054 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000011055
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011056 // FIXME. Check for other life times.
11057 if (LT != Qualifiers::OCL_None)
11058 return;
11059
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011060 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011061 if (PRE->isImplicitProperty())
11062 return;
11063 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11064 if (!PD)
11065 return;
11066
Bill Wendling44426052012-12-20 19:22:21 +000011067 unsigned Attributes = PD->getPropertyAttributes();
11068 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011069 // when 'assign' attribute was not explicitly specified
11070 // by user, ignore it and rely on property type itself
11071 // for lifetime info.
11072 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11073 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11074 LHSType->isObjCRetainableType())
11075 return;
11076
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011077 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000011078 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011079 Diag(Loc, diag::warn_arc_retained_property_assign)
11080 << RHS->getSourceRange();
11081 return;
11082 }
11083 RHS = cast->getSubExpr();
11084 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011085 }
Bill Wendling44426052012-12-20 19:22:21 +000011086 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000011087 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11088 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000011089 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011090 }
11091}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011092
11093//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11094
11095namespace {
11096bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11097 SourceLocation StmtLoc,
11098 const NullStmt *Body) {
11099 // Do not warn if the body is a macro that expands to nothing, e.g:
11100 //
11101 // #define CALL(x)
11102 // if (condition)
11103 // CALL(0);
11104 //
11105 if (Body->hasLeadingEmptyMacro())
11106 return false;
11107
11108 // Get line numbers of statement and body.
11109 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000011110 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011111 &StmtLineInvalid);
11112 if (StmtLineInvalid)
11113 return false;
11114
11115 bool BodyLineInvalid;
11116 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11117 &BodyLineInvalid);
11118 if (BodyLineInvalid)
11119 return false;
11120
11121 // Warn if null statement and body are on the same line.
11122 if (StmtLine != BodyLine)
11123 return false;
11124
11125 return true;
11126}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011127} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011128
11129void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11130 const Stmt *Body,
11131 unsigned DiagID) {
11132 // Since this is a syntactic check, don't emit diagnostic for template
11133 // instantiations, this just adds noise.
11134 if (CurrentInstantiationScope)
11135 return;
11136
11137 // The body should be a null statement.
11138 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11139 if (!NBody)
11140 return;
11141
11142 // Do the usual checks.
11143 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11144 return;
11145
11146 Diag(NBody->getSemiLoc(), DiagID);
11147 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11148}
11149
11150void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11151 const Stmt *PossibleBody) {
11152 assert(!CurrentInstantiationScope); // Ensured by caller
11153
11154 SourceLocation StmtLoc;
11155 const Stmt *Body;
11156 unsigned DiagID;
11157 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11158 StmtLoc = FS->getRParenLoc();
11159 Body = FS->getBody();
11160 DiagID = diag::warn_empty_for_body;
11161 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11162 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11163 Body = WS->getBody();
11164 DiagID = diag::warn_empty_while_body;
11165 } else
11166 return; // Neither `for' nor `while'.
11167
11168 // The body should be a null statement.
11169 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11170 if (!NBody)
11171 return;
11172
11173 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011174 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011175 return;
11176
11177 // Do the usual checks.
11178 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11179 return;
11180
11181 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11182 // noise level low, emit diagnostics only if for/while is followed by a
11183 // CompoundStmt, e.g.:
11184 // for (int i = 0; i < n; i++);
11185 // {
11186 // a(i);
11187 // }
11188 // or if for/while is followed by a statement with more indentation
11189 // than for/while itself:
11190 // for (int i = 0; i < n; i++);
11191 // a(i);
11192 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11193 if (!ProbableTypo) {
11194 bool BodyColInvalid;
11195 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11196 PossibleBody->getLocStart(),
11197 &BodyColInvalid);
11198 if (BodyColInvalid)
11199 return;
11200
11201 bool StmtColInvalid;
11202 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11203 S->getLocStart(),
11204 &StmtColInvalid);
11205 if (StmtColInvalid)
11206 return;
11207
11208 if (BodyCol > StmtCol)
11209 ProbableTypo = true;
11210 }
11211
11212 if (ProbableTypo) {
11213 Diag(NBody->getSemiLoc(), DiagID);
11214 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11215 }
11216}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011217
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011218//===--- CHECK: Warn on self move with std::move. -------------------------===//
11219
11220/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11221void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11222 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011223 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11224 return;
11225
11226 if (!ActiveTemplateInstantiations.empty())
11227 return;
11228
11229 // Strip parens and casts away.
11230 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11231 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11232
11233 // Check for a call expression
11234 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11235 if (!CE || CE->getNumArgs() != 1)
11236 return;
11237
11238 // Check for a call to std::move
11239 const FunctionDecl *FD = CE->getDirectCallee();
11240 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11241 !FD->getIdentifier()->isStr("move"))
11242 return;
11243
11244 // Get argument from std::move
11245 RHSExpr = CE->getArg(0);
11246
11247 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11248 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11249
11250 // Two DeclRefExpr's, check that the decls are the same.
11251 if (LHSDeclRef && RHSDeclRef) {
11252 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11253 return;
11254 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11255 RHSDeclRef->getDecl()->getCanonicalDecl())
11256 return;
11257
11258 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11259 << LHSExpr->getSourceRange()
11260 << RHSExpr->getSourceRange();
11261 return;
11262 }
11263
11264 // Member variables require a different approach to check for self moves.
11265 // MemberExpr's are the same if every nested MemberExpr refers to the same
11266 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11267 // the base Expr's are CXXThisExpr's.
11268 const Expr *LHSBase = LHSExpr;
11269 const Expr *RHSBase = RHSExpr;
11270 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11271 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11272 if (!LHSME || !RHSME)
11273 return;
11274
11275 while (LHSME && RHSME) {
11276 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11277 RHSME->getMemberDecl()->getCanonicalDecl())
11278 return;
11279
11280 LHSBase = LHSME->getBase();
11281 RHSBase = RHSME->getBase();
11282 LHSME = dyn_cast<MemberExpr>(LHSBase);
11283 RHSME = dyn_cast<MemberExpr>(RHSBase);
11284 }
11285
11286 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11287 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11288 if (LHSDeclRef && RHSDeclRef) {
11289 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11290 return;
11291 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11292 RHSDeclRef->getDecl()->getCanonicalDecl())
11293 return;
11294
11295 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11296 << LHSExpr->getSourceRange()
11297 << RHSExpr->getSourceRange();
11298 return;
11299 }
11300
11301 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11302 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11303 << LHSExpr->getSourceRange()
11304 << RHSExpr->getSourceRange();
11305}
11306
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011307//===--- Layout compatibility ----------------------------------------------//
11308
11309namespace {
11310
11311bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11312
11313/// \brief Check if two enumeration types are layout-compatible.
11314bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11315 // C++11 [dcl.enum] p8:
11316 // Two enumeration types are layout-compatible if they have the same
11317 // underlying type.
11318 return ED1->isComplete() && ED2->isComplete() &&
11319 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11320}
11321
11322/// \brief Check if two fields are layout-compatible.
11323bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11324 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11325 return false;
11326
11327 if (Field1->isBitField() != Field2->isBitField())
11328 return false;
11329
11330 if (Field1->isBitField()) {
11331 // Make sure that the bit-fields are the same length.
11332 unsigned Bits1 = Field1->getBitWidthValue(C);
11333 unsigned Bits2 = Field2->getBitWidthValue(C);
11334
11335 if (Bits1 != Bits2)
11336 return false;
11337 }
11338
11339 return true;
11340}
11341
11342/// \brief Check if two standard-layout structs are layout-compatible.
11343/// (C++11 [class.mem] p17)
11344bool isLayoutCompatibleStruct(ASTContext &C,
11345 RecordDecl *RD1,
11346 RecordDecl *RD2) {
11347 // If both records are C++ classes, check that base classes match.
11348 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11349 // If one of records is a CXXRecordDecl we are in C++ mode,
11350 // thus the other one is a CXXRecordDecl, too.
11351 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11352 // Check number of base classes.
11353 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11354 return false;
11355
11356 // Check the base classes.
11357 for (CXXRecordDecl::base_class_const_iterator
11358 Base1 = D1CXX->bases_begin(),
11359 BaseEnd1 = D1CXX->bases_end(),
11360 Base2 = D2CXX->bases_begin();
11361 Base1 != BaseEnd1;
11362 ++Base1, ++Base2) {
11363 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11364 return false;
11365 }
11366 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11367 // If only RD2 is a C++ class, it should have zero base classes.
11368 if (D2CXX->getNumBases() > 0)
11369 return false;
11370 }
11371
11372 // Check the fields.
11373 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11374 Field2End = RD2->field_end(),
11375 Field1 = RD1->field_begin(),
11376 Field1End = RD1->field_end();
11377 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11378 if (!isLayoutCompatible(C, *Field1, *Field2))
11379 return false;
11380 }
11381 if (Field1 != Field1End || Field2 != Field2End)
11382 return false;
11383
11384 return true;
11385}
11386
11387/// \brief Check if two standard-layout unions are layout-compatible.
11388/// (C++11 [class.mem] p18)
11389bool isLayoutCompatibleUnion(ASTContext &C,
11390 RecordDecl *RD1,
11391 RecordDecl *RD2) {
11392 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011393 for (auto *Field2 : RD2->fields())
11394 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011395
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011396 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011397 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11398 I = UnmatchedFields.begin(),
11399 E = UnmatchedFields.end();
11400
11401 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011402 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011403 bool Result = UnmatchedFields.erase(*I);
11404 (void) Result;
11405 assert(Result);
11406 break;
11407 }
11408 }
11409 if (I == E)
11410 return false;
11411 }
11412
11413 return UnmatchedFields.empty();
11414}
11415
11416bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11417 if (RD1->isUnion() != RD2->isUnion())
11418 return false;
11419
11420 if (RD1->isUnion())
11421 return isLayoutCompatibleUnion(C, RD1, RD2);
11422 else
11423 return isLayoutCompatibleStruct(C, RD1, RD2);
11424}
11425
11426/// \brief Check if two types are layout-compatible in C++11 sense.
11427bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11428 if (T1.isNull() || T2.isNull())
11429 return false;
11430
11431 // C++11 [basic.types] p11:
11432 // If two types T1 and T2 are the same type, then T1 and T2 are
11433 // layout-compatible types.
11434 if (C.hasSameType(T1, T2))
11435 return true;
11436
11437 T1 = T1.getCanonicalType().getUnqualifiedType();
11438 T2 = T2.getCanonicalType().getUnqualifiedType();
11439
11440 const Type::TypeClass TC1 = T1->getTypeClass();
11441 const Type::TypeClass TC2 = T2->getTypeClass();
11442
11443 if (TC1 != TC2)
11444 return false;
11445
11446 if (TC1 == Type::Enum) {
11447 return isLayoutCompatible(C,
11448 cast<EnumType>(T1)->getDecl(),
11449 cast<EnumType>(T2)->getDecl());
11450 } else if (TC1 == Type::Record) {
11451 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11452 return false;
11453
11454 return isLayoutCompatible(C,
11455 cast<RecordType>(T1)->getDecl(),
11456 cast<RecordType>(T2)->getDecl());
11457 }
11458
11459 return false;
11460}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011461} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011462
11463//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11464
11465namespace {
11466/// \brief Given a type tag expression find the type tag itself.
11467///
11468/// \param TypeExpr Type tag expression, as it appears in user's code.
11469///
11470/// \param VD Declaration of an identifier that appears in a type tag.
11471///
11472/// \param MagicValue Type tag magic value.
11473bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11474 const ValueDecl **VD, uint64_t *MagicValue) {
11475 while(true) {
11476 if (!TypeExpr)
11477 return false;
11478
11479 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11480
11481 switch (TypeExpr->getStmtClass()) {
11482 case Stmt::UnaryOperatorClass: {
11483 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11484 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11485 TypeExpr = UO->getSubExpr();
11486 continue;
11487 }
11488 return false;
11489 }
11490
11491 case Stmt::DeclRefExprClass: {
11492 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11493 *VD = DRE->getDecl();
11494 return true;
11495 }
11496
11497 case Stmt::IntegerLiteralClass: {
11498 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11499 llvm::APInt MagicValueAPInt = IL->getValue();
11500 if (MagicValueAPInt.getActiveBits() <= 64) {
11501 *MagicValue = MagicValueAPInt.getZExtValue();
11502 return true;
11503 } else
11504 return false;
11505 }
11506
11507 case Stmt::BinaryConditionalOperatorClass:
11508 case Stmt::ConditionalOperatorClass: {
11509 const AbstractConditionalOperator *ACO =
11510 cast<AbstractConditionalOperator>(TypeExpr);
11511 bool Result;
11512 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11513 if (Result)
11514 TypeExpr = ACO->getTrueExpr();
11515 else
11516 TypeExpr = ACO->getFalseExpr();
11517 continue;
11518 }
11519 return false;
11520 }
11521
11522 case Stmt::BinaryOperatorClass: {
11523 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11524 if (BO->getOpcode() == BO_Comma) {
11525 TypeExpr = BO->getRHS();
11526 continue;
11527 }
11528 return false;
11529 }
11530
11531 default:
11532 return false;
11533 }
11534 }
11535}
11536
11537/// \brief Retrieve the C type corresponding to type tag TypeExpr.
11538///
11539/// \param TypeExpr Expression that specifies a type tag.
11540///
11541/// \param MagicValues Registered magic values.
11542///
11543/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11544/// kind.
11545///
11546/// \param TypeInfo Information about the corresponding C type.
11547///
11548/// \returns true if the corresponding C type was found.
11549bool GetMatchingCType(
11550 const IdentifierInfo *ArgumentKind,
11551 const Expr *TypeExpr, const ASTContext &Ctx,
11552 const llvm::DenseMap<Sema::TypeTagMagicValue,
11553 Sema::TypeTagData> *MagicValues,
11554 bool &FoundWrongKind,
11555 Sema::TypeTagData &TypeInfo) {
11556 FoundWrongKind = false;
11557
11558 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000011559 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011560
11561 uint64_t MagicValue;
11562
11563 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11564 return false;
11565
11566 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000011567 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011568 if (I->getArgumentKind() != ArgumentKind) {
11569 FoundWrongKind = true;
11570 return false;
11571 }
11572 TypeInfo.Type = I->getMatchingCType();
11573 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11574 TypeInfo.MustBeNull = I->getMustBeNull();
11575 return true;
11576 }
11577 return false;
11578 }
11579
11580 if (!MagicValues)
11581 return false;
11582
11583 llvm::DenseMap<Sema::TypeTagMagicValue,
11584 Sema::TypeTagData>::const_iterator I =
11585 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11586 if (I == MagicValues->end())
11587 return false;
11588
11589 TypeInfo = I->second;
11590 return true;
11591}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011592} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011593
11594void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11595 uint64_t MagicValue, QualType Type,
11596 bool LayoutCompatible,
11597 bool MustBeNull) {
11598 if (!TypeTagForDatatypeMagicValues)
11599 TypeTagForDatatypeMagicValues.reset(
11600 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11601
11602 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11603 (*TypeTagForDatatypeMagicValues)[Magic] =
11604 TypeTagData(Type, LayoutCompatible, MustBeNull);
11605}
11606
11607namespace {
11608bool IsSameCharType(QualType T1, QualType T2) {
11609 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11610 if (!BT1)
11611 return false;
11612
11613 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11614 if (!BT2)
11615 return false;
11616
11617 BuiltinType::Kind T1Kind = BT1->getKind();
11618 BuiltinType::Kind T2Kind = BT2->getKind();
11619
11620 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
11621 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
11622 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11623 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11624}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011625} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011626
11627void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11628 const Expr * const *ExprArgs) {
11629 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11630 bool IsPointerAttr = Attr->getIsPointer();
11631
11632 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11633 bool FoundWrongKind;
11634 TypeTagData TypeInfo;
11635 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11636 TypeTagForDatatypeMagicValues.get(),
11637 FoundWrongKind, TypeInfo)) {
11638 if (FoundWrongKind)
11639 Diag(TypeTagExpr->getExprLoc(),
11640 diag::warn_type_tag_for_datatype_wrong_kind)
11641 << TypeTagExpr->getSourceRange();
11642 return;
11643 }
11644
11645 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11646 if (IsPointerAttr) {
11647 // Skip implicit cast of pointer to `void *' (as a function argument).
11648 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000011649 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000011650 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011651 ArgumentExpr = ICE->getSubExpr();
11652 }
11653 QualType ArgumentType = ArgumentExpr->getType();
11654
11655 // Passing a `void*' pointer shouldn't trigger a warning.
11656 if (IsPointerAttr && ArgumentType->isVoidPointerType())
11657 return;
11658
11659 if (TypeInfo.MustBeNull) {
11660 // Type tag with matching void type requires a null pointer.
11661 if (!ArgumentExpr->isNullPointerConstant(Context,
11662 Expr::NPC_ValueDependentIsNotNull)) {
11663 Diag(ArgumentExpr->getExprLoc(),
11664 diag::warn_type_safety_null_pointer_required)
11665 << ArgumentKind->getName()
11666 << ArgumentExpr->getSourceRange()
11667 << TypeTagExpr->getSourceRange();
11668 }
11669 return;
11670 }
11671
11672 QualType RequiredType = TypeInfo.Type;
11673 if (IsPointerAttr)
11674 RequiredType = Context.getPointerType(RequiredType);
11675
11676 bool mismatch = false;
11677 if (!TypeInfo.LayoutCompatible) {
11678 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
11679
11680 // C++11 [basic.fundamental] p1:
11681 // Plain char, signed char, and unsigned char are three distinct types.
11682 //
11683 // But we treat plain `char' as equivalent to `signed char' or `unsigned
11684 // char' depending on the current char signedness mode.
11685 if (mismatch)
11686 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
11687 RequiredType->getPointeeType())) ||
11688 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
11689 mismatch = false;
11690 } else
11691 if (IsPointerAttr)
11692 mismatch = !isLayoutCompatible(Context,
11693 ArgumentType->getPointeeType(),
11694 RequiredType->getPointeeType());
11695 else
11696 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
11697
11698 if (mismatch)
11699 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000011700 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011701 << TypeInfo.LayoutCompatible << RequiredType
11702 << ArgumentExpr->getSourceRange()
11703 << TypeTagExpr->getSourceRange();
11704}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011705
11706void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11707 CharUnits Alignment) {
11708 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
11709}
11710
11711void Sema::DiagnoseMisalignedMembers() {
11712 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000011713 const NamedDecl *ND = m.RD;
11714 if (ND->getName().empty()) {
11715 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
11716 ND = TD;
11717 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011718 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000011719 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011720 }
11721 MisalignedMembers.clear();
11722}
11723
11724void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011725 E = E->IgnoreParens();
11726 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011727 return;
11728 if (isa<UnaryOperator>(E) &&
11729 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
11730 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11731 if (isa<MemberExpr>(Op)) {
11732 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
11733 MisalignedMember(Op));
11734 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011735 (T->isIntegerType() ||
11736 (T->isPointerType() &&
11737 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011738 MisalignedMembers.erase(MA);
11739 }
11740 }
11741}
11742
11743void Sema::RefersToMemberWithReducedAlignment(
11744 Expr *E,
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011745 std::function<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011746 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011747 if (!ME)
11748 return;
11749
11750 // For a chain of MemberExpr like "a.b.c.d" this list
11751 // will keep FieldDecl's like [d, c, b].
11752 SmallVector<FieldDecl *, 4> ReverseMemberChain;
11753 const MemberExpr *TopME = nullptr;
11754 bool AnyIsPacked = false;
11755 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011756 QualType BaseType = ME->getBase()->getType();
11757 if (ME->isArrow())
11758 BaseType = BaseType->getPointeeType();
11759 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
11760
11761 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011762 auto *FD = dyn_cast<FieldDecl>(MD);
11763 // We do not care about non-data members.
11764 if (!FD || FD->isInvalidDecl())
11765 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011766
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011767 AnyIsPacked =
11768 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
11769 ReverseMemberChain.push_back(FD);
11770
11771 TopME = ME;
11772 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
11773 } while (ME);
11774 assert(TopME && "We did not compute a topmost MemberExpr!");
11775
11776 // Not the scope of this diagnostic.
11777 if (!AnyIsPacked)
11778 return;
11779
11780 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
11781 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
11782 // TODO: The innermost base of the member expression may be too complicated.
11783 // For now, just disregard these cases. This is left for future
11784 // improvement.
11785 if (!DRE && !isa<CXXThisExpr>(TopBase))
11786 return;
11787
11788 // Alignment expected by the whole expression.
11789 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
11790
11791 // No need to do anything else with this case.
11792 if (ExpectedAlignment.isOne())
11793 return;
11794
11795 // Synthesize offset of the whole access.
11796 CharUnits Offset;
11797 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
11798 I++) {
11799 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
11800 }
11801
11802 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
11803 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
11804 ReverseMemberChain.back()->getParent()->getTypeForDecl());
11805
11806 // The base expression of the innermost MemberExpr may give
11807 // stronger guarantees than the class containing the member.
11808 if (DRE && !TopME->isArrow()) {
11809 const ValueDecl *VD = DRE->getDecl();
11810 if (!VD->getType()->isReferenceType())
11811 CompleteObjectAlignment =
11812 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
11813 }
11814
11815 // Check if the synthesized offset fulfills the alignment.
11816 if (Offset % ExpectedAlignment != 0 ||
11817 // It may fulfill the offset it but the effective alignment may still be
11818 // lower than the expected expression alignment.
11819 CompleteObjectAlignment < ExpectedAlignment) {
11820 // If this happens, we want to determine a sensible culprit of this.
11821 // Intuitively, watching the chain of member expressions from right to
11822 // left, we start with the required alignment (as required by the field
11823 // type) but some packed attribute in that chain has reduced the alignment.
11824 // It may happen that another packed structure increases it again. But if
11825 // we are here such increase has not been enough. So pointing the first
11826 // FieldDecl that either is packed or else its RecordDecl is,
11827 // seems reasonable.
11828 FieldDecl *FD = nullptr;
11829 CharUnits Alignment;
11830 for (FieldDecl *FDI : ReverseMemberChain) {
11831 if (FDI->hasAttr<PackedAttr>() ||
11832 FDI->getParent()->hasAttr<PackedAttr>()) {
11833 FD = FDI;
11834 Alignment = std::min(
11835 Context.getTypeAlignInChars(FD->getType()),
11836 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
11837 break;
11838 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011839 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011840 assert(FD && "We did not find a packed FieldDecl!");
11841 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011842 }
11843}
11844
11845void Sema::CheckAddressOfPackedMember(Expr *rhs) {
11846 using namespace std::placeholders;
11847 RefersToMemberWithReducedAlignment(
11848 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
11849 _2, _3, _4));
11850}
11851