blob: 5973a5ffde4c68aec49d8d13af4c98e7814f8f78 [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.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000247 if (SemaRef.inTemplateInstantiation())
Reid Kleckner1d59f992015-01-22 01:36:17 +0000248 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
Simon Pilgrim2c518802017-03-30 14:13:19 +0000318/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000319static 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.
Anastasia Stulovab42f3c02017-04-21 15:13:24 +0000411 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000412 S.Diag(TheCall->getArg(2)->getLocStart(),
413 diag::err_opencl_enqueue_kernel_expected_type)
Anastasia Stulova58984e72017-02-16 12:27:47 +0000414 << "'ndrange_t'";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000415 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:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000762 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000763 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:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000773 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000774 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();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001245 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1246 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001247 bool IsInt64Long =
1248 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1249 QualType EltTy =
1250 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001251 if (HasConstPtr)
1252 EltTy = EltTy.withConst();
1253 QualType LHSTy = Context.getPointerType(EltTy);
1254 AssignConvertType ConvTy;
1255 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1256 if (RHS.isInvalid())
1257 return true;
1258 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1259 RHS.get(), AA_Assigning))
1260 return true;
1261 }
1262
1263 // For NEON intrinsics which take an immediate value as part of the
1264 // instruction, range check them here.
1265 unsigned i = 0, l = 0, u = 0;
1266 switch (BuiltinID) {
1267 default:
1268 return false;
Tim Northover12670412014-02-19 10:37:05 +00001269#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001270#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001271#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001272 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001273
Richard Sandiford28940af2014-04-16 08:47:51 +00001274 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001275}
1276
Tim Northovera2ee4332014-03-29 15:09:45 +00001277bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1278 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001279 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001280 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001281 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001282 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001283 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001284 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1285 BuiltinID == AArch64::BI__builtin_arm_strex ||
1286 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001287 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001288 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001289 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1290 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1291 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001292
1293 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1294
1295 // Ensure that we have the proper number of arguments.
1296 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1297 return true;
1298
1299 // Inspect the pointer argument of the atomic builtin. This should always be
1300 // a pointer type, whose element is an integral scalar or pointer type.
1301 // Because it is a pointer type, we don't have to worry about any implicit
1302 // casts here.
1303 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1304 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1305 if (PointerArgRes.isInvalid())
1306 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001307 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001308
1309 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1310 if (!pointerType) {
1311 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1312 << PointerArg->getType() << PointerArg->getSourceRange();
1313 return true;
1314 }
1315
1316 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1317 // task is to insert the appropriate casts into the AST. First work out just
1318 // what the appropriate type is.
1319 QualType ValType = pointerType->getPointeeType();
1320 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1321 if (IsLdrex)
1322 AddrType.addConst();
1323
1324 // Issue a warning if the cast is dodgy.
1325 CastKind CastNeeded = CK_NoOp;
1326 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1327 CastNeeded = CK_BitCast;
1328 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1329 << PointerArg->getType()
1330 << Context.getPointerType(AddrType)
1331 << AA_Passing << PointerArg->getSourceRange();
1332 }
1333
1334 // Finally, do the cast and replace the argument with the corrected version.
1335 AddrType = Context.getPointerType(AddrType);
1336 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1337 if (PointerArgRes.isInvalid())
1338 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001339 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001340
1341 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1342
1343 // In general, we allow ints, floats and pointers to be loaded and stored.
1344 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1345 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1346 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1347 << PointerArg->getType() << PointerArg->getSourceRange();
1348 return true;
1349 }
1350
1351 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001352 if (Context.getTypeSize(ValType) > MaxWidth) {
1353 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001354 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1355 << PointerArg->getType() << PointerArg->getSourceRange();
1356 return true;
1357 }
1358
1359 switch (ValType.getObjCLifetime()) {
1360 case Qualifiers::OCL_None:
1361 case Qualifiers::OCL_ExplicitNone:
1362 // okay
1363 break;
1364
1365 case Qualifiers::OCL_Weak:
1366 case Qualifiers::OCL_Strong:
1367 case Qualifiers::OCL_Autoreleasing:
1368 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1369 << ValType << PointerArg->getSourceRange();
1370 return true;
1371 }
1372
Tim Northover6aacd492013-07-16 09:47:53 +00001373 if (IsLdrex) {
1374 TheCall->setType(ValType);
1375 return false;
1376 }
1377
1378 // Initialize the argument to be stored.
1379 ExprResult ValArg = TheCall->getArg(0);
1380 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1381 Context, ValType, /*consume*/ false);
1382 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1383 if (ValArg.isInvalid())
1384 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001385 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001386
1387 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1388 // but the custom checker bypasses all default analysis.
1389 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001390 return false;
1391}
1392
Nate Begeman4904e322010-06-08 02:47:44 +00001393bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover6aacd492013-07-16 09:47:53 +00001394 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001395 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1396 BuiltinID == ARM::BI__builtin_arm_strex ||
1397 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001398 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001399 }
1400
Yi Kong26d104a2014-08-13 19:18:14 +00001401 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1402 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1403 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1404 }
1405
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001406 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1407 BuiltinID == ARM::BI__builtin_arm_wsr64)
1408 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1409
1410 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1411 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1412 BuiltinID == ARM::BI__builtin_arm_wsr ||
1413 BuiltinID == ARM::BI__builtin_arm_wsrp)
1414 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1415
Tim Northover12670412014-02-19 10:37:05 +00001416 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1417 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001418
Yi Kong4efadfb2014-07-03 16:01:25 +00001419 // For intrinsics which take an immediate value as part of the instruction,
1420 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001421 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001422 switch (BuiltinID) {
1423 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001424 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1425 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001426 case ARM::BI__builtin_arm_vcvtr_f:
1427 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001428 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001429 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001430 case ARM::BI__builtin_arm_isb:
1431 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001432 }
Nate Begemand773fe62010-06-13 04:47:52 +00001433
Nate Begemanf568b072010-08-03 21:32:34 +00001434 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001435 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001436}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001437
Tim Northover573cbee2014-05-24 12:52:07 +00001438bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001439 CallExpr *TheCall) {
Tim Northover573cbee2014-05-24 12:52:07 +00001440 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001441 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1442 BuiltinID == AArch64::BI__builtin_arm_strex ||
1443 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001444 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1445 }
1446
Yi Konga5548432014-08-13 19:18:20 +00001447 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1448 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1449 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1450 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1451 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1452 }
1453
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001454 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1455 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001456 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001457
1458 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1459 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1460 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1461 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1462 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1463
Tim Northovera2ee4332014-03-29 15:09:45 +00001464 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1465 return true;
1466
Yi Kong19a29ac2014-07-17 10:52:06 +00001467 // For intrinsics which take an immediate value as part of the instruction,
1468 // range check them here.
1469 unsigned i = 0, l = 0, u = 0;
1470 switch (BuiltinID) {
1471 default: return false;
1472 case AArch64::BI__builtin_arm_dmb:
1473 case AArch64::BI__builtin_arm_dsb:
1474 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1475 }
1476
Yi Kong19a29ac2014-07-17 10:52:06 +00001477 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001478}
1479
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001480// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1481// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1482// ordering for DSP is unspecified. MSA is ordered by the data format used
1483// by the underlying instruction i.e., df/m, df/n and then by size.
1484//
1485// FIXME: The size tests here should instead be tablegen'd along with the
1486// definitions from include/clang/Basic/BuiltinsMips.def.
1487// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1488// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001489bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001490 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001491 switch (BuiltinID) {
1492 default: return false;
1493 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1494 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001495 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1496 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1497 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1498 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1499 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001500 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1501 // df/m field.
1502 // These intrinsics take an unsigned 3 bit immediate.
1503 case Mips::BI__builtin_msa_bclri_b:
1504 case Mips::BI__builtin_msa_bnegi_b:
1505 case Mips::BI__builtin_msa_bseti_b:
1506 case Mips::BI__builtin_msa_sat_s_b:
1507 case Mips::BI__builtin_msa_sat_u_b:
1508 case Mips::BI__builtin_msa_slli_b:
1509 case Mips::BI__builtin_msa_srai_b:
1510 case Mips::BI__builtin_msa_srari_b:
1511 case Mips::BI__builtin_msa_srli_b:
1512 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1513 case Mips::BI__builtin_msa_binsli_b:
1514 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1515 // These intrinsics take an unsigned 4 bit immediate.
1516 case Mips::BI__builtin_msa_bclri_h:
1517 case Mips::BI__builtin_msa_bnegi_h:
1518 case Mips::BI__builtin_msa_bseti_h:
1519 case Mips::BI__builtin_msa_sat_s_h:
1520 case Mips::BI__builtin_msa_sat_u_h:
1521 case Mips::BI__builtin_msa_slli_h:
1522 case Mips::BI__builtin_msa_srai_h:
1523 case Mips::BI__builtin_msa_srari_h:
1524 case Mips::BI__builtin_msa_srli_h:
1525 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1526 case Mips::BI__builtin_msa_binsli_h:
1527 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1528 // These intrinsics take an unsigned 5 bit immedate.
1529 // The first block of intrinsics actually have an unsigned 5 bit field,
1530 // not a df/n field.
1531 case Mips::BI__builtin_msa_clei_u_b:
1532 case Mips::BI__builtin_msa_clei_u_h:
1533 case Mips::BI__builtin_msa_clei_u_w:
1534 case Mips::BI__builtin_msa_clei_u_d:
1535 case Mips::BI__builtin_msa_clti_u_b:
1536 case Mips::BI__builtin_msa_clti_u_h:
1537 case Mips::BI__builtin_msa_clti_u_w:
1538 case Mips::BI__builtin_msa_clti_u_d:
1539 case Mips::BI__builtin_msa_maxi_u_b:
1540 case Mips::BI__builtin_msa_maxi_u_h:
1541 case Mips::BI__builtin_msa_maxi_u_w:
1542 case Mips::BI__builtin_msa_maxi_u_d:
1543 case Mips::BI__builtin_msa_mini_u_b:
1544 case Mips::BI__builtin_msa_mini_u_h:
1545 case Mips::BI__builtin_msa_mini_u_w:
1546 case Mips::BI__builtin_msa_mini_u_d:
1547 case Mips::BI__builtin_msa_addvi_b:
1548 case Mips::BI__builtin_msa_addvi_h:
1549 case Mips::BI__builtin_msa_addvi_w:
1550 case Mips::BI__builtin_msa_addvi_d:
1551 case Mips::BI__builtin_msa_bclri_w:
1552 case Mips::BI__builtin_msa_bnegi_w:
1553 case Mips::BI__builtin_msa_bseti_w:
1554 case Mips::BI__builtin_msa_sat_s_w:
1555 case Mips::BI__builtin_msa_sat_u_w:
1556 case Mips::BI__builtin_msa_slli_w:
1557 case Mips::BI__builtin_msa_srai_w:
1558 case Mips::BI__builtin_msa_srari_w:
1559 case Mips::BI__builtin_msa_srli_w:
1560 case Mips::BI__builtin_msa_srlri_w:
1561 case Mips::BI__builtin_msa_subvi_b:
1562 case Mips::BI__builtin_msa_subvi_h:
1563 case Mips::BI__builtin_msa_subvi_w:
1564 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1565 case Mips::BI__builtin_msa_binsli_w:
1566 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1567 // These intrinsics take an unsigned 6 bit immediate.
1568 case Mips::BI__builtin_msa_bclri_d:
1569 case Mips::BI__builtin_msa_bnegi_d:
1570 case Mips::BI__builtin_msa_bseti_d:
1571 case Mips::BI__builtin_msa_sat_s_d:
1572 case Mips::BI__builtin_msa_sat_u_d:
1573 case Mips::BI__builtin_msa_slli_d:
1574 case Mips::BI__builtin_msa_srai_d:
1575 case Mips::BI__builtin_msa_srari_d:
1576 case Mips::BI__builtin_msa_srli_d:
1577 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1578 case Mips::BI__builtin_msa_binsli_d:
1579 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1580 // These intrinsics take a signed 5 bit immediate.
1581 case Mips::BI__builtin_msa_ceqi_b:
1582 case Mips::BI__builtin_msa_ceqi_h:
1583 case Mips::BI__builtin_msa_ceqi_w:
1584 case Mips::BI__builtin_msa_ceqi_d:
1585 case Mips::BI__builtin_msa_clti_s_b:
1586 case Mips::BI__builtin_msa_clti_s_h:
1587 case Mips::BI__builtin_msa_clti_s_w:
1588 case Mips::BI__builtin_msa_clti_s_d:
1589 case Mips::BI__builtin_msa_clei_s_b:
1590 case Mips::BI__builtin_msa_clei_s_h:
1591 case Mips::BI__builtin_msa_clei_s_w:
1592 case Mips::BI__builtin_msa_clei_s_d:
1593 case Mips::BI__builtin_msa_maxi_s_b:
1594 case Mips::BI__builtin_msa_maxi_s_h:
1595 case Mips::BI__builtin_msa_maxi_s_w:
1596 case Mips::BI__builtin_msa_maxi_s_d:
1597 case Mips::BI__builtin_msa_mini_s_b:
1598 case Mips::BI__builtin_msa_mini_s_h:
1599 case Mips::BI__builtin_msa_mini_s_w:
1600 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1601 // These intrinsics take an unsigned 8 bit immediate.
1602 case Mips::BI__builtin_msa_andi_b:
1603 case Mips::BI__builtin_msa_nori_b:
1604 case Mips::BI__builtin_msa_ori_b:
1605 case Mips::BI__builtin_msa_shf_b:
1606 case Mips::BI__builtin_msa_shf_h:
1607 case Mips::BI__builtin_msa_shf_w:
1608 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1609 case Mips::BI__builtin_msa_bseli_b:
1610 case Mips::BI__builtin_msa_bmnzi_b:
1611 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1612 // df/n format
1613 // These intrinsics take an unsigned 4 bit immediate.
1614 case Mips::BI__builtin_msa_copy_s_b:
1615 case Mips::BI__builtin_msa_copy_u_b:
1616 case Mips::BI__builtin_msa_insve_b:
1617 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001618 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1619 // These intrinsics take an unsigned 3 bit immediate.
1620 case Mips::BI__builtin_msa_copy_s_h:
1621 case Mips::BI__builtin_msa_copy_u_h:
1622 case Mips::BI__builtin_msa_insve_h:
1623 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001624 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1625 // These intrinsics take an unsigned 2 bit immediate.
1626 case Mips::BI__builtin_msa_copy_s_w:
1627 case Mips::BI__builtin_msa_copy_u_w:
1628 case Mips::BI__builtin_msa_insve_w:
1629 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001630 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1631 // These intrinsics take an unsigned 1 bit immediate.
1632 case Mips::BI__builtin_msa_copy_s_d:
1633 case Mips::BI__builtin_msa_copy_u_d:
1634 case Mips::BI__builtin_msa_insve_d:
1635 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001636 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1637 // Memory offsets and immediate loads.
1638 // These intrinsics take a signed 10 bit immediate.
Petar Jovanovic9b8b9e82017-03-31 16:16:43 +00001639 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001640 case Mips::BI__builtin_msa_ldi_h:
1641 case Mips::BI__builtin_msa_ldi_w:
1642 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1643 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1644 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1645 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1646 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1647 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1648 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1649 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1650 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001651 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001652
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001653 if (!m)
1654 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1655
1656 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1657 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001658}
1659
Kit Bartone50adcb2015-03-30 19:40:59 +00001660bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1661 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001662 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1663 BuiltinID == PPC::BI__builtin_divdeu ||
1664 BuiltinID == PPC::BI__builtin_bpermd;
1665 bool IsTarget64Bit = Context.getTargetInfo()
1666 .getTypeWidth(Context
1667 .getTargetInfo()
1668 .getIntPtrType()) == 64;
1669 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1670 BuiltinID == PPC::BI__builtin_divweu ||
1671 BuiltinID == PPC::BI__builtin_divde ||
1672 BuiltinID == PPC::BI__builtin_divdeu;
1673
1674 if (Is64BitBltin && !IsTarget64Bit)
1675 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1676 << TheCall->getSourceRange();
1677
1678 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1679 (BuiltinID == PPC::BI__builtin_bpermd &&
1680 !Context.getTargetInfo().hasFeature("bpermd")))
1681 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1682 << TheCall->getSourceRange();
1683
Kit Bartone50adcb2015-03-30 19:40:59 +00001684 switch (BuiltinID) {
1685 default: return false;
1686 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1687 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1688 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1689 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1690 case PPC::BI__builtin_tbegin:
1691 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1692 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1693 case PPC::BI__builtin_tabortwc:
1694 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1695 case PPC::BI__builtin_tabortwci:
1696 case PPC::BI__builtin_tabortdci:
1697 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1698 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
Tony Jiangbbc48e92017-05-24 15:13:32 +00001699 case PPC::BI__builtin_vsx_xxpermdi:
1700 return SemaBuiltinVSX(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00001701 }
1702 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1703}
1704
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001705bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1706 CallExpr *TheCall) {
1707 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1708 Expr *Arg = TheCall->getArg(0);
1709 llvm::APSInt AbortCode(32);
1710 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1711 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1712 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1713 << Arg->getSourceRange();
1714 }
1715
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001716 // For intrinsics which take an immediate value as part of the instruction,
1717 // range check them here.
1718 unsigned i = 0, l = 0, u = 0;
1719 switch (BuiltinID) {
1720 default: return false;
1721 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1722 case SystemZ::BI__builtin_s390_verimb:
1723 case SystemZ::BI__builtin_s390_verimh:
1724 case SystemZ::BI__builtin_s390_verimf:
1725 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1726 case SystemZ::BI__builtin_s390_vfaeb:
1727 case SystemZ::BI__builtin_s390_vfaeh:
1728 case SystemZ::BI__builtin_s390_vfaef:
1729 case SystemZ::BI__builtin_s390_vfaebs:
1730 case SystemZ::BI__builtin_s390_vfaehs:
1731 case SystemZ::BI__builtin_s390_vfaefs:
1732 case SystemZ::BI__builtin_s390_vfaezb:
1733 case SystemZ::BI__builtin_s390_vfaezh:
1734 case SystemZ::BI__builtin_s390_vfaezf:
1735 case SystemZ::BI__builtin_s390_vfaezbs:
1736 case SystemZ::BI__builtin_s390_vfaezhs:
1737 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1738 case SystemZ::BI__builtin_s390_vfidb:
1739 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1740 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1741 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1742 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1743 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1744 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1745 case SystemZ::BI__builtin_s390_vstrcb:
1746 case SystemZ::BI__builtin_s390_vstrch:
1747 case SystemZ::BI__builtin_s390_vstrcf:
1748 case SystemZ::BI__builtin_s390_vstrczb:
1749 case SystemZ::BI__builtin_s390_vstrczh:
1750 case SystemZ::BI__builtin_s390_vstrczf:
1751 case SystemZ::BI__builtin_s390_vstrcbs:
1752 case SystemZ::BI__builtin_s390_vstrchs:
1753 case SystemZ::BI__builtin_s390_vstrcfs:
1754 case SystemZ::BI__builtin_s390_vstrczbs:
1755 case SystemZ::BI__builtin_s390_vstrczhs:
1756 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1757 }
1758 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001759}
1760
Craig Topper5ba2c502015-11-07 08:08:31 +00001761/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1762/// This checks that the target supports __builtin_cpu_supports and
1763/// that the string argument is constant and valid.
1764static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1765 Expr *Arg = TheCall->getArg(0);
1766
1767 // Check if the argument is a string literal.
1768 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1769 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1770 << Arg->getSourceRange();
1771
1772 // Check the contents of the string.
1773 StringRef Feature =
1774 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1775 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1776 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1777 << Arg->getSourceRange();
1778 return false;
1779}
1780
Craig Toppera7e253e2016-09-23 04:48:31 +00001781// Check if the rounding mode is legal.
1782bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1783 // Indicates if this instruction has rounding control or just SAE.
1784 bool HasRC = false;
1785
1786 unsigned ArgNum = 0;
1787 switch (BuiltinID) {
1788 default:
1789 return false;
1790 case X86::BI__builtin_ia32_vcvttsd2si32:
1791 case X86::BI__builtin_ia32_vcvttsd2si64:
1792 case X86::BI__builtin_ia32_vcvttsd2usi32:
1793 case X86::BI__builtin_ia32_vcvttsd2usi64:
1794 case X86::BI__builtin_ia32_vcvttss2si32:
1795 case X86::BI__builtin_ia32_vcvttss2si64:
1796 case X86::BI__builtin_ia32_vcvttss2usi32:
1797 case X86::BI__builtin_ia32_vcvttss2usi64:
1798 ArgNum = 1;
1799 break;
1800 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1801 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1802 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1803 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1804 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1805 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1806 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1807 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1808 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1809 case X86::BI__builtin_ia32_exp2pd_mask:
1810 case X86::BI__builtin_ia32_exp2ps_mask:
1811 case X86::BI__builtin_ia32_getexppd512_mask:
1812 case X86::BI__builtin_ia32_getexpps512_mask:
1813 case X86::BI__builtin_ia32_rcp28pd_mask:
1814 case X86::BI__builtin_ia32_rcp28ps_mask:
1815 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1816 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1817 case X86::BI__builtin_ia32_vcomisd:
1818 case X86::BI__builtin_ia32_vcomiss:
1819 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1820 ArgNum = 3;
1821 break;
1822 case X86::BI__builtin_ia32_cmppd512_mask:
1823 case X86::BI__builtin_ia32_cmpps512_mask:
1824 case X86::BI__builtin_ia32_cmpsd_mask:
1825 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001826 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001827 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1828 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001829 case X86::BI__builtin_ia32_maxpd512_mask:
1830 case X86::BI__builtin_ia32_maxps512_mask:
1831 case X86::BI__builtin_ia32_maxsd_round_mask:
1832 case X86::BI__builtin_ia32_maxss_round_mask:
1833 case X86::BI__builtin_ia32_minpd512_mask:
1834 case X86::BI__builtin_ia32_minps512_mask:
1835 case X86::BI__builtin_ia32_minsd_round_mask:
1836 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001837 case X86::BI__builtin_ia32_rcp28sd_round_mask:
1838 case X86::BI__builtin_ia32_rcp28ss_round_mask:
1839 case X86::BI__builtin_ia32_reducepd512_mask:
1840 case X86::BI__builtin_ia32_reduceps512_mask:
1841 case X86::BI__builtin_ia32_rndscalepd_mask:
1842 case X86::BI__builtin_ia32_rndscaleps_mask:
1843 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1844 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1845 ArgNum = 4;
1846 break;
1847 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001848 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001849 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001850 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001851 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001852 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001853 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001854 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001855 case X86::BI__builtin_ia32_rangepd512_mask:
1856 case X86::BI__builtin_ia32_rangeps512_mask:
1857 case X86::BI__builtin_ia32_rangesd128_round_mask:
1858 case X86::BI__builtin_ia32_rangess128_round_mask:
1859 case X86::BI__builtin_ia32_reducesd_mask:
1860 case X86::BI__builtin_ia32_reducess_mask:
1861 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1862 case X86::BI__builtin_ia32_rndscaless_round_mask:
1863 ArgNum = 5;
1864 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00001865 case X86::BI__builtin_ia32_vcvtsd2si64:
1866 case X86::BI__builtin_ia32_vcvtsd2si32:
1867 case X86::BI__builtin_ia32_vcvtsd2usi32:
1868 case X86::BI__builtin_ia32_vcvtsd2usi64:
1869 case X86::BI__builtin_ia32_vcvtss2si32:
1870 case X86::BI__builtin_ia32_vcvtss2si64:
1871 case X86::BI__builtin_ia32_vcvtss2usi32:
1872 case X86::BI__builtin_ia32_vcvtss2usi64:
1873 ArgNum = 1;
1874 HasRC = true;
1875 break;
Craig Topper8e066312016-11-07 07:01:09 +00001876 case X86::BI__builtin_ia32_cvtsi2sd64:
1877 case X86::BI__builtin_ia32_cvtsi2ss32:
1878 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00001879 case X86::BI__builtin_ia32_cvtusi2sd64:
1880 case X86::BI__builtin_ia32_cvtusi2ss32:
1881 case X86::BI__builtin_ia32_cvtusi2ss64:
1882 ArgNum = 2;
1883 HasRC = true;
1884 break;
1885 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1886 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1887 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1888 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1889 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1890 case X86::BI__builtin_ia32_cvtps2qq512_mask:
1891 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1892 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1893 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1894 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1895 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001896 case X86::BI__builtin_ia32_sqrtpd512_mask:
1897 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001898 ArgNum = 3;
1899 HasRC = true;
1900 break;
1901 case X86::BI__builtin_ia32_addpd512_mask:
1902 case X86::BI__builtin_ia32_addps512_mask:
1903 case X86::BI__builtin_ia32_divpd512_mask:
1904 case X86::BI__builtin_ia32_divps512_mask:
1905 case X86::BI__builtin_ia32_mulpd512_mask:
1906 case X86::BI__builtin_ia32_mulps512_mask:
1907 case X86::BI__builtin_ia32_subpd512_mask:
1908 case X86::BI__builtin_ia32_subps512_mask:
1909 case X86::BI__builtin_ia32_addss_round_mask:
1910 case X86::BI__builtin_ia32_addsd_round_mask:
1911 case X86::BI__builtin_ia32_divss_round_mask:
1912 case X86::BI__builtin_ia32_divsd_round_mask:
1913 case X86::BI__builtin_ia32_mulss_round_mask:
1914 case X86::BI__builtin_ia32_mulsd_round_mask:
1915 case X86::BI__builtin_ia32_subss_round_mask:
1916 case X86::BI__builtin_ia32_subsd_round_mask:
1917 case X86::BI__builtin_ia32_scalefpd512_mask:
1918 case X86::BI__builtin_ia32_scalefps512_mask:
1919 case X86::BI__builtin_ia32_scalefsd_round_mask:
1920 case X86::BI__builtin_ia32_scalefss_round_mask:
1921 case X86::BI__builtin_ia32_getmantpd512_mask:
1922 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001923 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
1924 case X86::BI__builtin_ia32_sqrtsd_round_mask:
1925 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001926 case X86::BI__builtin_ia32_vfmaddpd512_mask:
1927 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1928 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1929 case X86::BI__builtin_ia32_vfmaddps512_mask:
1930 case X86::BI__builtin_ia32_vfmaddps512_mask3:
1931 case X86::BI__builtin_ia32_vfmaddps512_maskz:
1932 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1933 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1934 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1935 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1936 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1937 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1938 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1939 case X86::BI__builtin_ia32_vfmsubps512_mask3:
1940 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1941 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1942 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1943 case X86::BI__builtin_ia32_vfnmaddps512_mask:
1944 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1945 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1946 case X86::BI__builtin_ia32_vfnmsubps512_mask:
1947 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1948 case X86::BI__builtin_ia32_vfmaddsd3_mask:
1949 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1950 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1951 case X86::BI__builtin_ia32_vfmaddss3_mask:
1952 case X86::BI__builtin_ia32_vfmaddss3_maskz:
1953 case X86::BI__builtin_ia32_vfmaddss3_mask3:
1954 ArgNum = 4;
1955 HasRC = true;
1956 break;
1957 case X86::BI__builtin_ia32_getmantsd_round_mask:
1958 case X86::BI__builtin_ia32_getmantss_round_mask:
1959 ArgNum = 5;
1960 HasRC = true;
1961 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00001962 }
1963
1964 llvm::APSInt Result;
1965
1966 // We can't check the value of a dependent argument.
1967 Expr *Arg = TheCall->getArg(ArgNum);
1968 if (Arg->isTypeDependent() || Arg->isValueDependent())
1969 return false;
1970
1971 // Check constant-ness first.
1972 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1973 return true;
1974
1975 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1976 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1977 // combined with ROUND_NO_EXC.
1978 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1979 Result == 8/*ROUND_NO_EXC*/ ||
1980 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1981 return false;
1982
1983 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1984 << Arg->getSourceRange();
1985}
1986
Craig Topperdf5beb22017-03-13 17:16:50 +00001987// Check if the gather/scatter scale is legal.
1988bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
1989 CallExpr *TheCall) {
1990 unsigned ArgNum = 0;
1991 switch (BuiltinID) {
1992 default:
1993 return false;
1994 case X86::BI__builtin_ia32_gatherpfdpd:
1995 case X86::BI__builtin_ia32_gatherpfdps:
1996 case X86::BI__builtin_ia32_gatherpfqpd:
1997 case X86::BI__builtin_ia32_gatherpfqps:
1998 case X86::BI__builtin_ia32_scatterpfdpd:
1999 case X86::BI__builtin_ia32_scatterpfdps:
2000 case X86::BI__builtin_ia32_scatterpfqpd:
2001 case X86::BI__builtin_ia32_scatterpfqps:
2002 ArgNum = 3;
2003 break;
2004 case X86::BI__builtin_ia32_gatherd_pd:
2005 case X86::BI__builtin_ia32_gatherd_pd256:
2006 case X86::BI__builtin_ia32_gatherq_pd:
2007 case X86::BI__builtin_ia32_gatherq_pd256:
2008 case X86::BI__builtin_ia32_gatherd_ps:
2009 case X86::BI__builtin_ia32_gatherd_ps256:
2010 case X86::BI__builtin_ia32_gatherq_ps:
2011 case X86::BI__builtin_ia32_gatherq_ps256:
2012 case X86::BI__builtin_ia32_gatherd_q:
2013 case X86::BI__builtin_ia32_gatherd_q256:
2014 case X86::BI__builtin_ia32_gatherq_q:
2015 case X86::BI__builtin_ia32_gatherq_q256:
2016 case X86::BI__builtin_ia32_gatherd_d:
2017 case X86::BI__builtin_ia32_gatherd_d256:
2018 case X86::BI__builtin_ia32_gatherq_d:
2019 case X86::BI__builtin_ia32_gatherq_d256:
2020 case X86::BI__builtin_ia32_gather3div2df:
2021 case X86::BI__builtin_ia32_gather3div2di:
2022 case X86::BI__builtin_ia32_gather3div4df:
2023 case X86::BI__builtin_ia32_gather3div4di:
2024 case X86::BI__builtin_ia32_gather3div4sf:
2025 case X86::BI__builtin_ia32_gather3div4si:
2026 case X86::BI__builtin_ia32_gather3div8sf:
2027 case X86::BI__builtin_ia32_gather3div8si:
2028 case X86::BI__builtin_ia32_gather3siv2df:
2029 case X86::BI__builtin_ia32_gather3siv2di:
2030 case X86::BI__builtin_ia32_gather3siv4df:
2031 case X86::BI__builtin_ia32_gather3siv4di:
2032 case X86::BI__builtin_ia32_gather3siv4sf:
2033 case X86::BI__builtin_ia32_gather3siv4si:
2034 case X86::BI__builtin_ia32_gather3siv8sf:
2035 case X86::BI__builtin_ia32_gather3siv8si:
2036 case X86::BI__builtin_ia32_gathersiv8df:
2037 case X86::BI__builtin_ia32_gathersiv16sf:
2038 case X86::BI__builtin_ia32_gatherdiv8df:
2039 case X86::BI__builtin_ia32_gatherdiv16sf:
2040 case X86::BI__builtin_ia32_gathersiv8di:
2041 case X86::BI__builtin_ia32_gathersiv16si:
2042 case X86::BI__builtin_ia32_gatherdiv8di:
2043 case X86::BI__builtin_ia32_gatherdiv16si:
2044 case X86::BI__builtin_ia32_scatterdiv2df:
2045 case X86::BI__builtin_ia32_scatterdiv2di:
2046 case X86::BI__builtin_ia32_scatterdiv4df:
2047 case X86::BI__builtin_ia32_scatterdiv4di:
2048 case X86::BI__builtin_ia32_scatterdiv4sf:
2049 case X86::BI__builtin_ia32_scatterdiv4si:
2050 case X86::BI__builtin_ia32_scatterdiv8sf:
2051 case X86::BI__builtin_ia32_scatterdiv8si:
2052 case X86::BI__builtin_ia32_scattersiv2df:
2053 case X86::BI__builtin_ia32_scattersiv2di:
2054 case X86::BI__builtin_ia32_scattersiv4df:
2055 case X86::BI__builtin_ia32_scattersiv4di:
2056 case X86::BI__builtin_ia32_scattersiv4sf:
2057 case X86::BI__builtin_ia32_scattersiv4si:
2058 case X86::BI__builtin_ia32_scattersiv8sf:
2059 case X86::BI__builtin_ia32_scattersiv8si:
2060 case X86::BI__builtin_ia32_scattersiv8df:
2061 case X86::BI__builtin_ia32_scattersiv16sf:
2062 case X86::BI__builtin_ia32_scatterdiv8df:
2063 case X86::BI__builtin_ia32_scatterdiv16sf:
2064 case X86::BI__builtin_ia32_scattersiv8di:
2065 case X86::BI__builtin_ia32_scattersiv16si:
2066 case X86::BI__builtin_ia32_scatterdiv8di:
2067 case X86::BI__builtin_ia32_scatterdiv16si:
2068 ArgNum = 4;
2069 break;
2070 }
2071
2072 llvm::APSInt Result;
2073
2074 // We can't check the value of a dependent argument.
2075 Expr *Arg = TheCall->getArg(ArgNum);
2076 if (Arg->isTypeDependent() || Arg->isValueDependent())
2077 return false;
2078
2079 // Check constant-ness first.
2080 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2081 return true;
2082
2083 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2084 return false;
2085
2086 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2087 << Arg->getSourceRange();
2088}
2089
Craig Topperf0ddc892016-09-23 04:48:27 +00002090bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2091 if (BuiltinID == X86::BI__builtin_cpu_supports)
2092 return SemaBuiltinCpuSupports(*this, TheCall);
2093
2094 if (BuiltinID == X86::BI__builtin_ms_va_start)
Reid Kleckner2b0fa122017-05-02 20:10:03 +00002095 return SemaBuiltinVAStart(BuiltinID, TheCall);
Craig Topperf0ddc892016-09-23 04:48:27 +00002096
Craig Toppera7e253e2016-09-23 04:48:31 +00002097 // If the intrinsic has rounding or SAE make sure its valid.
2098 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2099 return true;
2100
Craig Topperdf5beb22017-03-13 17:16:50 +00002101 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2102 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2103 return true;
2104
Craig Topperf0ddc892016-09-23 04:48:27 +00002105 // For intrinsics which take an immediate value as part of the instruction,
2106 // range check them here.
2107 int i = 0, l = 0, u = 0;
2108 switch (BuiltinID) {
2109 default:
2110 return false;
Richard Trieucc3949d2016-02-18 22:34:54 +00002111 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00002112 i = 1; l = 0; u = 3;
2113 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002114 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00002115 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2116 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2117 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2118 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002119 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002120 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002121 case X86::BI__builtin_ia32_vpermil2pd:
2122 case X86::BI__builtin_ia32_vpermil2pd256:
2123 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002124 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002125 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002126 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002127 case X86::BI__builtin_ia32_cmpb128_mask:
2128 case X86::BI__builtin_ia32_cmpw128_mask:
2129 case X86::BI__builtin_ia32_cmpd128_mask:
2130 case X86::BI__builtin_ia32_cmpq128_mask:
2131 case X86::BI__builtin_ia32_cmpb256_mask:
2132 case X86::BI__builtin_ia32_cmpw256_mask:
2133 case X86::BI__builtin_ia32_cmpd256_mask:
2134 case X86::BI__builtin_ia32_cmpq256_mask:
2135 case X86::BI__builtin_ia32_cmpb512_mask:
2136 case X86::BI__builtin_ia32_cmpw512_mask:
2137 case X86::BI__builtin_ia32_cmpd512_mask:
2138 case X86::BI__builtin_ia32_cmpq512_mask:
2139 case X86::BI__builtin_ia32_ucmpb128_mask:
2140 case X86::BI__builtin_ia32_ucmpw128_mask:
2141 case X86::BI__builtin_ia32_ucmpd128_mask:
2142 case X86::BI__builtin_ia32_ucmpq128_mask:
2143 case X86::BI__builtin_ia32_ucmpb256_mask:
2144 case X86::BI__builtin_ia32_ucmpw256_mask:
2145 case X86::BI__builtin_ia32_ucmpd256_mask:
2146 case X86::BI__builtin_ia32_ucmpq256_mask:
2147 case X86::BI__builtin_ia32_ucmpb512_mask:
2148 case X86::BI__builtin_ia32_ucmpw512_mask:
2149 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002150 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002151 case X86::BI__builtin_ia32_vpcomub:
2152 case X86::BI__builtin_ia32_vpcomuw:
2153 case X86::BI__builtin_ia32_vpcomud:
2154 case X86::BI__builtin_ia32_vpcomuq:
2155 case X86::BI__builtin_ia32_vpcomb:
2156 case X86::BI__builtin_ia32_vpcomw:
2157 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002158 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00002159 i = 2; l = 0; u = 7;
2160 break;
2161 case X86::BI__builtin_ia32_roundps:
2162 case X86::BI__builtin_ia32_roundpd:
2163 case X86::BI__builtin_ia32_roundps256:
2164 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002165 i = 1; l = 0; u = 15;
2166 break;
2167 case X86::BI__builtin_ia32_roundss:
2168 case X86::BI__builtin_ia32_roundsd:
2169 case X86::BI__builtin_ia32_rangepd128_mask:
2170 case X86::BI__builtin_ia32_rangepd256_mask:
2171 case X86::BI__builtin_ia32_rangepd512_mask:
2172 case X86::BI__builtin_ia32_rangeps128_mask:
2173 case X86::BI__builtin_ia32_rangeps256_mask:
2174 case X86::BI__builtin_ia32_rangeps512_mask:
2175 case X86::BI__builtin_ia32_getmantsd_round_mask:
2176 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002177 i = 2; l = 0; u = 15;
2178 break;
2179 case X86::BI__builtin_ia32_cmpps:
2180 case X86::BI__builtin_ia32_cmpss:
2181 case X86::BI__builtin_ia32_cmppd:
2182 case X86::BI__builtin_ia32_cmpsd:
2183 case X86::BI__builtin_ia32_cmpps256:
2184 case X86::BI__builtin_ia32_cmppd256:
2185 case X86::BI__builtin_ia32_cmpps128_mask:
2186 case X86::BI__builtin_ia32_cmppd128_mask:
2187 case X86::BI__builtin_ia32_cmpps256_mask:
2188 case X86::BI__builtin_ia32_cmppd256_mask:
2189 case X86::BI__builtin_ia32_cmpps512_mask:
2190 case X86::BI__builtin_ia32_cmppd512_mask:
2191 case X86::BI__builtin_ia32_cmpsd_mask:
2192 case X86::BI__builtin_ia32_cmpss_mask:
2193 i = 2; l = 0; u = 31;
2194 break;
2195 case X86::BI__builtin_ia32_xabort:
2196 i = 0; l = -128; u = 255;
2197 break;
2198 case X86::BI__builtin_ia32_pshufw:
2199 case X86::BI__builtin_ia32_aeskeygenassist128:
2200 i = 1; l = -128; u = 255;
2201 break;
2202 case X86::BI__builtin_ia32_vcvtps2ph:
2203 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper39c87102016-05-18 03:18:12 +00002204 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2205 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2206 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2207 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2208 case X86::BI__builtin_ia32_rndscaleps_mask:
2209 case X86::BI__builtin_ia32_rndscalepd_mask:
2210 case X86::BI__builtin_ia32_reducepd128_mask:
2211 case X86::BI__builtin_ia32_reducepd256_mask:
2212 case X86::BI__builtin_ia32_reducepd512_mask:
2213 case X86::BI__builtin_ia32_reduceps128_mask:
2214 case X86::BI__builtin_ia32_reduceps256_mask:
2215 case X86::BI__builtin_ia32_reduceps512_mask:
2216 case X86::BI__builtin_ia32_prold512_mask:
2217 case X86::BI__builtin_ia32_prolq512_mask:
2218 case X86::BI__builtin_ia32_prold128_mask:
2219 case X86::BI__builtin_ia32_prold256_mask:
2220 case X86::BI__builtin_ia32_prolq128_mask:
2221 case X86::BI__builtin_ia32_prolq256_mask:
2222 case X86::BI__builtin_ia32_prord128_mask:
2223 case X86::BI__builtin_ia32_prord256_mask:
2224 case X86::BI__builtin_ia32_prorq128_mask:
2225 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002226 case X86::BI__builtin_ia32_fpclasspd128_mask:
2227 case X86::BI__builtin_ia32_fpclasspd256_mask:
2228 case X86::BI__builtin_ia32_fpclassps128_mask:
2229 case X86::BI__builtin_ia32_fpclassps256_mask:
2230 case X86::BI__builtin_ia32_fpclassps512_mask:
2231 case X86::BI__builtin_ia32_fpclasspd512_mask:
2232 case X86::BI__builtin_ia32_fpclasssd_mask:
2233 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002234 i = 1; l = 0; u = 255;
2235 break;
2236 case X86::BI__builtin_ia32_palignr:
2237 case X86::BI__builtin_ia32_insertps128:
2238 case X86::BI__builtin_ia32_dpps:
2239 case X86::BI__builtin_ia32_dppd:
2240 case X86::BI__builtin_ia32_dpps256:
2241 case X86::BI__builtin_ia32_mpsadbw128:
2242 case X86::BI__builtin_ia32_mpsadbw256:
2243 case X86::BI__builtin_ia32_pcmpistrm128:
2244 case X86::BI__builtin_ia32_pcmpistri128:
2245 case X86::BI__builtin_ia32_pcmpistria128:
2246 case X86::BI__builtin_ia32_pcmpistric128:
2247 case X86::BI__builtin_ia32_pcmpistrio128:
2248 case X86::BI__builtin_ia32_pcmpistris128:
2249 case X86::BI__builtin_ia32_pcmpistriz128:
2250 case X86::BI__builtin_ia32_pclmulqdq128:
2251 case X86::BI__builtin_ia32_vperm2f128_pd256:
2252 case X86::BI__builtin_ia32_vperm2f128_ps256:
2253 case X86::BI__builtin_ia32_vperm2f128_si256:
2254 case X86::BI__builtin_ia32_permti256:
2255 i = 2; l = -128; u = 255;
2256 break;
2257 case X86::BI__builtin_ia32_palignr128:
2258 case X86::BI__builtin_ia32_palignr256:
Craig Topper39c87102016-05-18 03:18:12 +00002259 case X86::BI__builtin_ia32_palignr512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002260 case X86::BI__builtin_ia32_vcomisd:
2261 case X86::BI__builtin_ia32_vcomiss:
2262 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2263 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2264 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2265 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002266 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2267 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2268 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2269 i = 2; l = 0; u = 255;
2270 break;
2271 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2272 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2273 case X86::BI__builtin_ia32_fixupimmps512_mask:
2274 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2275 case X86::BI__builtin_ia32_fixupimmsd_mask:
2276 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2277 case X86::BI__builtin_ia32_fixupimmss_mask:
2278 case X86::BI__builtin_ia32_fixupimmss_maskz:
2279 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2280 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2281 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2282 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2283 case X86::BI__builtin_ia32_fixupimmps128_mask:
2284 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2285 case X86::BI__builtin_ia32_fixupimmps256_mask:
2286 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2287 case X86::BI__builtin_ia32_pternlogd512_mask:
2288 case X86::BI__builtin_ia32_pternlogd512_maskz:
2289 case X86::BI__builtin_ia32_pternlogq512_mask:
2290 case X86::BI__builtin_ia32_pternlogq512_maskz:
2291 case X86::BI__builtin_ia32_pternlogd128_mask:
2292 case X86::BI__builtin_ia32_pternlogd128_maskz:
2293 case X86::BI__builtin_ia32_pternlogd256_mask:
2294 case X86::BI__builtin_ia32_pternlogd256_maskz:
2295 case X86::BI__builtin_ia32_pternlogq128_mask:
2296 case X86::BI__builtin_ia32_pternlogq128_maskz:
2297 case X86::BI__builtin_ia32_pternlogq256_mask:
2298 case X86::BI__builtin_ia32_pternlogq256_maskz:
2299 i = 3; l = 0; u = 255;
2300 break;
Craig Topper9625db02017-03-12 22:19:10 +00002301 case X86::BI__builtin_ia32_gatherpfdpd:
2302 case X86::BI__builtin_ia32_gatherpfdps:
2303 case X86::BI__builtin_ia32_gatherpfqpd:
2304 case X86::BI__builtin_ia32_gatherpfqps:
2305 case X86::BI__builtin_ia32_scatterpfdpd:
2306 case X86::BI__builtin_ia32_scatterpfdps:
2307 case X86::BI__builtin_ia32_scatterpfqpd:
2308 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00002309 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00002310 break;
Craig Topper39c87102016-05-18 03:18:12 +00002311 case X86::BI__builtin_ia32_pcmpestrm128:
2312 case X86::BI__builtin_ia32_pcmpestri128:
2313 case X86::BI__builtin_ia32_pcmpestria128:
2314 case X86::BI__builtin_ia32_pcmpestric128:
2315 case X86::BI__builtin_ia32_pcmpestrio128:
2316 case X86::BI__builtin_ia32_pcmpestris128:
2317 case X86::BI__builtin_ia32_pcmpestriz128:
2318 i = 4; l = -128; u = 255;
2319 break;
2320 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2321 case X86::BI__builtin_ia32_rndscaless_round_mask:
2322 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002323 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002324 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002325 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002326}
2327
Richard Smith55ce3522012-06-25 20:30:08 +00002328/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2329/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2330/// Returns true when the format fits the function and the FormatStringInfo has
2331/// been populated.
2332bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2333 FormatStringInfo *FSI) {
2334 FSI->HasVAListArg = Format->getFirstArg() == 0;
2335 FSI->FormatIdx = Format->getFormatIdx() - 1;
2336 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002337
Richard Smith55ce3522012-06-25 20:30:08 +00002338 // The way the format attribute works in GCC, the implicit this argument
2339 // of member functions is counted. However, it doesn't appear in our own
2340 // lists, so decrement format_idx in that case.
2341 if (IsCXXMember) {
2342 if(FSI->FormatIdx == 0)
2343 return false;
2344 --FSI->FormatIdx;
2345 if (FSI->FirstDataArg != 0)
2346 --FSI->FirstDataArg;
2347 }
2348 return true;
2349}
Mike Stump11289f42009-09-09 15:08:12 +00002350
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002351/// Checks if a the given expression evaluates to null.
2352///
2353/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002354static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002355 // If the expression has non-null type, it doesn't evaluate to null.
2356 if (auto nullability
2357 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2358 if (*nullability == NullabilityKind::NonNull)
2359 return false;
2360 }
2361
Ted Kremeneka146db32014-01-17 06:24:47 +00002362 // As a special case, transparent unions initialized with zero are
2363 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002364 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002365 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2366 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002367 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002368 if (const InitListExpr *ILE =
2369 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002370 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002371 }
2372
2373 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002374 return (!Expr->isValueDependent() &&
2375 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2376 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002377}
2378
2379static void CheckNonNullArgument(Sema &S,
2380 const Expr *ArgExpr,
2381 SourceLocation CallSiteLoc) {
2382 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002383 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2384 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002385}
2386
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002387bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2388 FormatStringInfo FSI;
2389 if ((GetFormatStringType(Format) == FST_NSString) &&
2390 getFormatStringInfo(Format, false, &FSI)) {
2391 Idx = FSI.FormatIdx;
2392 return true;
2393 }
2394 return false;
2395}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002396/// \brief Diagnose use of %s directive in an NSString which is being passed
2397/// as formatting string to formatting method.
2398static void
2399DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2400 const NamedDecl *FDecl,
2401 Expr **Args,
2402 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002403 unsigned Idx = 0;
2404 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002405 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2406 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002407 Idx = 2;
2408 Format = true;
2409 }
2410 else
2411 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2412 if (S.GetFormatNSStringIdx(I, Idx)) {
2413 Format = true;
2414 break;
2415 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002416 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002417 if (!Format || NumArgs <= Idx)
2418 return;
2419 const Expr *FormatExpr = Args[Idx];
2420 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2421 FormatExpr = CSCE->getSubExpr();
2422 const StringLiteral *FormatString;
2423 if (const ObjCStringLiteral *OSL =
2424 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2425 FormatString = OSL->getString();
2426 else
2427 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2428 if (!FormatString)
2429 return;
2430 if (S.FormatStringHasSArg(FormatString)) {
2431 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2432 << "%s" << 1 << 1;
2433 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2434 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002435 }
2436}
2437
Douglas Gregorb4866e82015-06-19 18:13:19 +00002438/// Determine whether the given type has a non-null nullability annotation.
2439static bool isNonNullType(ASTContext &ctx, QualType type) {
2440 if (auto nullability = type->getNullability(ctx))
2441 return *nullability == NullabilityKind::NonNull;
2442
2443 return false;
2444}
2445
Ted Kremenek2bc73332014-01-17 06:24:43 +00002446static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002447 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002448 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002449 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002450 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002451 assert((FDecl || Proto) && "Need a function declaration or prototype");
2452
Ted Kremenek9aedc152014-01-17 06:24:56 +00002453 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002454 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002455 if (FDecl) {
2456 // Handle the nonnull attribute on the function/method declaration itself.
2457 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2458 if (!NonNull->args_size()) {
2459 // Easy case: all pointer arguments are nonnull.
2460 for (const auto *Arg : Args)
2461 if (S.isValidPointerAttrType(Arg->getType()))
2462 CheckNonNullArgument(S, Arg, CallSiteLoc);
2463 return;
2464 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002465
Douglas Gregorb4866e82015-06-19 18:13:19 +00002466 for (unsigned Val : NonNull->args()) {
2467 if (Val >= Args.size())
2468 continue;
2469 if (NonNullArgs.empty())
2470 NonNullArgs.resize(Args.size());
2471 NonNullArgs.set(Val);
2472 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002473 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002474 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002475
Douglas Gregorb4866e82015-06-19 18:13:19 +00002476 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2477 // Handle the nonnull attribute on the parameters of the
2478 // function/method.
2479 ArrayRef<ParmVarDecl*> parms;
2480 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2481 parms = FD->parameters();
2482 else
2483 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2484
2485 unsigned ParamIndex = 0;
2486 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2487 I != E; ++I, ++ParamIndex) {
2488 const ParmVarDecl *PVD = *I;
2489 if (PVD->hasAttr<NonNullAttr>() ||
2490 isNonNullType(S.Context, PVD->getType())) {
2491 if (NonNullArgs.empty())
2492 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002493
Douglas Gregorb4866e82015-06-19 18:13:19 +00002494 NonNullArgs.set(ParamIndex);
2495 }
2496 }
2497 } else {
2498 // If we have a non-function, non-method declaration but no
2499 // function prototype, try to dig out the function prototype.
2500 if (!Proto) {
2501 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2502 QualType type = VD->getType().getNonReferenceType();
2503 if (auto pointerType = type->getAs<PointerType>())
2504 type = pointerType->getPointeeType();
2505 else if (auto blockType = type->getAs<BlockPointerType>())
2506 type = blockType->getPointeeType();
2507 // FIXME: data member pointers?
2508
2509 // Dig out the function prototype, if there is one.
2510 Proto = type->getAs<FunctionProtoType>();
2511 }
2512 }
2513
2514 // Fill in non-null argument information from the nullability
2515 // information on the parameter types (if we have them).
2516 if (Proto) {
2517 unsigned Index = 0;
2518 for (auto paramType : Proto->getParamTypes()) {
2519 if (isNonNullType(S.Context, paramType)) {
2520 if (NonNullArgs.empty())
2521 NonNullArgs.resize(Args.size());
2522
2523 NonNullArgs.set(Index);
2524 }
2525
2526 ++Index;
2527 }
2528 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002529 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002530
Douglas Gregorb4866e82015-06-19 18:13:19 +00002531 // Check for non-null arguments.
2532 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2533 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002534 if (NonNullArgs[ArgIndex])
2535 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002536 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002537}
2538
Richard Smith55ce3522012-06-25 20:30:08 +00002539/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00002540/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2541/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002542void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00002543 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2544 bool IsMemberFunction, SourceLocation Loc,
2545 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002546 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002547 if (CurContext->isDependentContext())
2548 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002549
Ted Kremenekb8176da2010-09-09 04:33:05 +00002550 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002551 llvm::SmallBitVector CheckedVarArgs;
2552 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002553 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002554 // Only create vector if there are format attributes.
2555 CheckedVarArgs.resize(Args.size());
2556
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002557 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002558 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002559 }
Richard Smithd7293d72013-08-05 18:49:43 +00002560 }
Richard Smith55ce3522012-06-25 20:30:08 +00002561
2562 // Refuse POD arguments that weren't caught by the format string
2563 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00002564 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2565 if (CallType != VariadicDoesNotApply &&
2566 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002567 unsigned NumParams = Proto ? Proto->getNumParams()
2568 : FDecl && isa<FunctionDecl>(FDecl)
2569 ? cast<FunctionDecl>(FDecl)->getNumParams()
2570 : FDecl && isa<ObjCMethodDecl>(FDecl)
2571 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2572 : 0;
2573
Alp Toker9cacbab2014-01-20 20:26:09 +00002574 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002575 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002576 if (const Expr *Arg = Args[ArgIdx]) {
2577 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2578 checkVariadicArgument(Arg, CallType);
2579 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002580 }
Richard Smithd7293d72013-08-05 18:49:43 +00002581 }
Mike Stump11289f42009-09-09 15:08:12 +00002582
Douglas Gregorb4866e82015-06-19 18:13:19 +00002583 if (FDecl || Proto) {
2584 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002585
Richard Trieu41bc0992013-06-22 00:20:41 +00002586 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002587 if (FDecl) {
2588 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2589 CheckArgumentWithTypeTag(I, Args.data());
2590 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002591 }
George Burgess IVce6284b2017-01-28 02:19:40 +00002592
2593 if (FD)
2594 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00002595}
2596
2597/// CheckConstructorCall - Check a constructor call for correctness and safety
2598/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002599void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2600 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002601 const FunctionProtoType *Proto,
2602 SourceLocation Loc) {
2603 VariadicCallType CallType =
2604 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00002605 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2606 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002607}
2608
2609/// CheckFunctionCall - Check a direct function call for various correctness
2610/// and safety properties not strictly enforced by the C type system.
2611bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2612 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002613 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2614 isa<CXXMethodDecl>(FDecl);
2615 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2616 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002617 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2618 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002619 Expr** Args = TheCall->getArgs();
2620 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00002621
2622 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00002623 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002624 // If this is a call to a member operator, hide the first argument
2625 // from checkCall.
2626 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00002627 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00002628 ++Args;
2629 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00002630 } else if (IsMemberFunction)
2631 ImplicitThis =
2632 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2633
2634 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002635 IsMemberFunction, TheCall->getRParenLoc(),
2636 TheCall->getCallee()->getSourceRange(), CallType);
2637
2638 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2639 // None of the checks below are needed for functions that don't have
2640 // simple names (e.g., C++ conversion functions).
2641 if (!FnInfo)
2642 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002643
Richard Trieua7f30b12016-12-06 01:42:28 +00002644 CheckAbsoluteValueFunction(TheCall, FDecl);
2645 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00002646
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002647 if (getLangOpts().ObjC1)
2648 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002649
Anna Zaks22122702012-01-17 00:37:07 +00002650 unsigned CMId = FDecl->getMemoryFunctionKind();
2651 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002652 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002653
Anna Zaks201d4892012-01-13 21:52:01 +00002654 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002655 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002656 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002657 else if (CMId == Builtin::BIstrncat)
2658 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002659 else
Anna Zaks22122702012-01-17 00:37:07 +00002660 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002661
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002662 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002663}
2664
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002665bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002666 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002667 VariadicCallType CallType =
2668 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002669
George Burgess IVce6284b2017-01-28 02:19:40 +00002670 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2671 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002672 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002673
2674 return false;
2675}
2676
Richard Trieu664c4c62013-06-20 21:03:13 +00002677bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2678 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002679 QualType Ty;
2680 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002681 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002682 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002683 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002684 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002685 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002686
Douglas Gregorb4866e82015-06-19 18:13:19 +00002687 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2688 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002689 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002690
Richard Trieu664c4c62013-06-20 21:03:13 +00002691 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002692 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002693 CallType = VariadicDoesNotApply;
2694 } else if (Ty->isBlockPointerType()) {
2695 CallType = VariadicBlock;
2696 } else { // Ty->isFunctionPointerType()
2697 CallType = VariadicFunction;
2698 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002699
George Burgess IVce6284b2017-01-28 02:19:40 +00002700 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002701 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2702 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002703 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002704
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002705 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002706}
2707
Richard Trieu41bc0992013-06-22 00:20:41 +00002708/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2709/// such as function pointers returned from functions.
2710bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002711 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002712 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00002713 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002714 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002715 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002716 TheCall->getCallee()->getSourceRange(), CallType);
2717
2718 return false;
2719}
2720
Tim Northovere94a34c2014-03-11 10:49:14 +00002721static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002722 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002723 return false;
2724
JF Bastiendda2cb12016-04-18 18:01:49 +00002725 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002726 switch (Op) {
2727 case AtomicExpr::AO__c11_atomic_init:
2728 llvm_unreachable("There is no ordering argument for an init");
2729
2730 case AtomicExpr::AO__c11_atomic_load:
2731 case AtomicExpr::AO__atomic_load_n:
2732 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002733 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2734 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002735
2736 case AtomicExpr::AO__c11_atomic_store:
2737 case AtomicExpr::AO__atomic_store:
2738 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002739 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2740 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2741 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002742
2743 default:
2744 return true;
2745 }
2746}
2747
Richard Smithfeea8832012-04-12 05:08:17 +00002748ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2749 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002750 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2751 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002752
Richard Smithfeea8832012-04-12 05:08:17 +00002753 // All these operations take one of the following forms:
2754 enum {
2755 // C __c11_atomic_init(A *, C)
2756 Init,
2757 // C __c11_atomic_load(A *, int)
2758 Load,
2759 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002760 LoadCopy,
2761 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002762 Copy,
2763 // C __c11_atomic_add(A *, M, int)
2764 Arithmetic,
2765 // C __atomic_exchange_n(A *, CP, int)
2766 Xchg,
2767 // void __atomic_exchange(A *, C *, CP, int)
2768 GNUXchg,
2769 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2770 C11CmpXchg,
2771 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2772 GNUCmpXchg
2773 } Form = Init;
Eric Fiselier8d662442016-03-30 23:39:56 +00002774 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2775 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002776 // where:
2777 // C is an appropriate type,
2778 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2779 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2780 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2781 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002782
Gabor Horvath98bd0982015-03-16 09:59:54 +00002783 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2784 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2785 AtomicExpr::AO__atomic_load,
2786 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00002787 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2788 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2789 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2790 Op == AtomicExpr::AO__atomic_store_n ||
2791 Op == AtomicExpr::AO__atomic_exchange_n ||
2792 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2793 bool IsAddSub = false;
2794
2795 switch (Op) {
2796 case AtomicExpr::AO__c11_atomic_init:
2797 Form = Init;
2798 break;
2799
2800 case AtomicExpr::AO__c11_atomic_load:
2801 case AtomicExpr::AO__atomic_load_n:
2802 Form = Load;
2803 break;
2804
Richard Smithfeea8832012-04-12 05:08:17 +00002805 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002806 Form = LoadCopy;
2807 break;
2808
2809 case AtomicExpr::AO__c11_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002810 case AtomicExpr::AO__atomic_store:
2811 case AtomicExpr::AO__atomic_store_n:
2812 Form = Copy;
2813 break;
2814
2815 case AtomicExpr::AO__c11_atomic_fetch_add:
2816 case AtomicExpr::AO__c11_atomic_fetch_sub:
2817 case AtomicExpr::AO__atomic_fetch_add:
2818 case AtomicExpr::AO__atomic_fetch_sub:
2819 case AtomicExpr::AO__atomic_add_fetch:
2820 case AtomicExpr::AO__atomic_sub_fetch:
2821 IsAddSub = true;
2822 // Fall through.
2823 case AtomicExpr::AO__c11_atomic_fetch_and:
2824 case AtomicExpr::AO__c11_atomic_fetch_or:
2825 case AtomicExpr::AO__c11_atomic_fetch_xor:
2826 case AtomicExpr::AO__atomic_fetch_and:
2827 case AtomicExpr::AO__atomic_fetch_or:
2828 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00002829 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00002830 case AtomicExpr::AO__atomic_and_fetch:
2831 case AtomicExpr::AO__atomic_or_fetch:
2832 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00002833 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00002834 Form = Arithmetic;
2835 break;
2836
2837 case AtomicExpr::AO__c11_atomic_exchange:
2838 case AtomicExpr::AO__atomic_exchange_n:
2839 Form = Xchg;
2840 break;
2841
2842 case AtomicExpr::AO__atomic_exchange:
2843 Form = GNUXchg;
2844 break;
2845
2846 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2847 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2848 Form = C11CmpXchg;
2849 break;
2850
2851 case AtomicExpr::AO__atomic_compare_exchange:
2852 case AtomicExpr::AO__atomic_compare_exchange_n:
2853 Form = GNUCmpXchg;
2854 break;
2855 }
2856
2857 // Check we have the right number of arguments.
2858 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002859 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002860 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002861 << TheCall->getCallee()->getSourceRange();
2862 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00002863 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2864 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002865 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002866 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002867 << TheCall->getCallee()->getSourceRange();
2868 return ExprError();
2869 }
2870
Richard Smithfeea8832012-04-12 05:08:17 +00002871 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002872 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00002873 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2874 if (ConvertedPtr.isInvalid())
2875 return ExprError();
2876
2877 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002878 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2879 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00002880 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002881 << Ptr->getType() << Ptr->getSourceRange();
2882 return ExprError();
2883 }
2884
Richard Smithfeea8832012-04-12 05:08:17 +00002885 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2886 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2887 QualType ValType = AtomTy; // 'C'
2888 if (IsC11) {
2889 if (!AtomTy->isAtomicType()) {
2890 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2891 << Ptr->getType() << Ptr->getSourceRange();
2892 return ExprError();
2893 }
Richard Smithe00921a2012-09-15 06:09:58 +00002894 if (AtomTy.isConstQualified()) {
2895 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2896 << Ptr->getType() << Ptr->getSourceRange();
2897 return ExprError();
2898 }
Richard Smithfeea8832012-04-12 05:08:17 +00002899 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00002900 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002901 if (ValType.isConstQualified()) {
2902 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2903 << Ptr->getType() << Ptr->getSourceRange();
2904 return ExprError();
2905 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002906 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002907
Richard Smithfeea8832012-04-12 05:08:17 +00002908 // For an arithmetic operation, the implied arithmetic must be well-formed.
2909 if (Form == Arithmetic) {
2910 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2911 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2912 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2913 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2914 return ExprError();
2915 }
2916 if (!IsAddSub && !ValType->isIntegerType()) {
2917 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2918 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2919 return ExprError();
2920 }
David Majnemere85cff82015-01-28 05:48:06 +00002921 if (IsC11 && ValType->isPointerType() &&
2922 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2923 diag::err_incomplete_type)) {
2924 return ExprError();
2925 }
Richard Smithfeea8832012-04-12 05:08:17 +00002926 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2927 // For __atomic_*_n operations, the value type must be a scalar integral or
2928 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002929 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00002930 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2931 return ExprError();
2932 }
2933
Eli Friedmanaa769812013-09-11 03:49:34 +00002934 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2935 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00002936 // For GNU atomics, require a trivially-copyable type. This is not part of
2937 // the GNU atomics specification, but we enforce it for sanity.
2938 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002939 << Ptr->getType() << Ptr->getSourceRange();
2940 return ExprError();
2941 }
2942
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002943 switch (ValType.getObjCLifetime()) {
2944 case Qualifiers::OCL_None:
2945 case Qualifiers::OCL_ExplicitNone:
2946 // okay
2947 break;
2948
2949 case Qualifiers::OCL_Weak:
2950 case Qualifiers::OCL_Strong:
2951 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002952 // FIXME: Can this happen? By this point, ValType should be known
2953 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002954 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2955 << ValType << Ptr->getSourceRange();
2956 return ExprError();
2957 }
2958
David Majnemerc6eb6502015-06-03 00:26:35 +00002959 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2960 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00002961 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00002962 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00002963 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002964 QualType ResultType = ValType;
Eric Fiselier8d662442016-03-30 23:39:56 +00002965 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002966 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002967 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002968 ResultType = Context.BoolTy;
2969
Richard Smithfeea8832012-04-12 05:08:17 +00002970 // The type of a parameter passed 'by value'. In the GNU atomics, such
2971 // arguments are actually passed as pointers.
2972 QualType ByValType = ValType; // 'CP'
2973 if (!IsC11 && !IsN)
2974 ByValType = Ptr->getType();
2975
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002976 // The first argument --- the pointer --- has a fixed type; we
2977 // deduce the types of the rest of the arguments accordingly. Walk
2978 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002979 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002980 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002981 if (i < NumVals[Form] + 1) {
2982 switch (i) {
2983 case 1:
2984 // The second argument is the non-atomic operand. For arithmetic, this
2985 // is always passed by value, and for a compare_exchange it is always
2986 // passed by address. For the rest, GNU uses by-address and C11 uses
2987 // by-value.
2988 assert(Form != Load);
2989 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2990 Ty = ValType;
2991 else if (Form == Copy || Form == Xchg)
2992 Ty = ByValType;
2993 else if (Form == Arithmetic)
2994 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002995 else {
2996 Expr *ValArg = TheCall->getArg(i);
Alex Lorenz67522152016-11-23 16:57:03 +00002997 // Treat this argument as _Nonnull as we want to show a warning if
2998 // NULL is passed into it.
2999 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003000 unsigned AS = 0;
3001 // Keep address space of non-atomic pointer type.
3002 if (const PointerType *PtrTy =
3003 ValArg->getType()->getAs<PointerType>()) {
3004 AS = PtrTy->getPointeeType().getAddressSpace();
3005 }
3006 Ty = Context.getPointerType(
3007 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3008 }
Richard Smithfeea8832012-04-12 05:08:17 +00003009 break;
3010 case 2:
3011 // The third argument to compare_exchange / GNU exchange is a
3012 // (pointer to a) desired value.
3013 Ty = ByValType;
3014 break;
3015 case 3:
3016 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3017 Ty = Context.BoolTy;
3018 break;
3019 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003020 } else {
3021 // The order(s) are always converted to int.
3022 Ty = Context.IntTy;
3023 }
Richard Smithfeea8832012-04-12 05:08:17 +00003024
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003025 InitializedEntity Entity =
3026 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00003027 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003028 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3029 if (Arg.isInvalid())
3030 return true;
3031 TheCall->setArg(i, Arg.get());
3032 }
3033
Richard Smithfeea8832012-04-12 05:08:17 +00003034 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003035 SmallVector<Expr*, 5> SubExprs;
3036 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00003037 switch (Form) {
3038 case Init:
3039 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00003040 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003041 break;
3042 case Load:
3043 SubExprs.push_back(TheCall->getArg(1)); // Order
3044 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00003045 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00003046 case Copy:
3047 case Arithmetic:
3048 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003049 SubExprs.push_back(TheCall->getArg(2)); // Order
3050 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003051 break;
3052 case GNUXchg:
3053 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3054 SubExprs.push_back(TheCall->getArg(3)); // Order
3055 SubExprs.push_back(TheCall->getArg(1)); // Val1
3056 SubExprs.push_back(TheCall->getArg(2)); // Val2
3057 break;
3058 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003059 SubExprs.push_back(TheCall->getArg(3)); // Order
3060 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003061 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00003062 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00003063 break;
3064 case GNUCmpXchg:
3065 SubExprs.push_back(TheCall->getArg(4)); // Order
3066 SubExprs.push_back(TheCall->getArg(1)); // Val1
3067 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3068 SubExprs.push_back(TheCall->getArg(2)); // Val2
3069 SubExprs.push_back(TheCall->getArg(3)); // Weak
3070 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003071 }
Tim Northovere94a34c2014-03-11 10:49:14 +00003072
3073 if (SubExprs.size() >= 2 && Form != Init) {
3074 llvm::APSInt Result(32);
3075 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3076 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00003077 Diag(SubExprs[1]->getLocStart(),
3078 diag::warn_atomic_op_has_invalid_memory_order)
3079 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00003080 }
3081
Fariborz Jahanian615de762013-05-28 17:37:39 +00003082 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3083 SubExprs, ResultType, Op,
3084 TheCall->getRParenLoc());
3085
3086 if ((Op == AtomicExpr::AO__c11_atomic_load ||
3087 (Op == AtomicExpr::AO__c11_atomic_store)) &&
3088 Context.AtomicUsesUnsupportedLibcall(AE))
3089 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
3090 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003091
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003092 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003093}
3094
John McCall29ad95b2011-08-27 01:09:30 +00003095/// checkBuiltinArgument - Given a call to a builtin function, perform
3096/// normal type-checking on the given argument, updating the call in
3097/// place. This is useful when a builtin function requires custom
3098/// type-checking for some of its arguments but not necessarily all of
3099/// them.
3100///
3101/// Returns true on error.
3102static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3103 FunctionDecl *Fn = E->getDirectCallee();
3104 assert(Fn && "builtin call without direct callee!");
3105
3106 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3107 InitializedEntity Entity =
3108 InitializedEntity::InitializeParameter(S.Context, Param);
3109
3110 ExprResult Arg = E->getArg(0);
3111 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3112 if (Arg.isInvalid())
3113 return true;
3114
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003115 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003116 return false;
3117}
3118
Chris Lattnerdc046542009-05-08 06:58:22 +00003119/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3120/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3121/// type of its first argument. The main ActOnCallExpr routines have already
3122/// promoted the types of arguments because all of these calls are prototyped as
3123/// void(...).
3124///
3125/// This function goes through and does final semantic checking for these
3126/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003127ExprResult
3128Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003129 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003130 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3131 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3132
3133 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003134 if (TheCall->getNumArgs() < 1) {
3135 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3136 << 0 << 1 << TheCall->getNumArgs()
3137 << TheCall->getCallee()->getSourceRange();
3138 return ExprError();
3139 }
Mike Stump11289f42009-09-09 15:08:12 +00003140
Chris Lattnerdc046542009-05-08 06:58:22 +00003141 // Inspect the first argument of the atomic builtin. This should always be
3142 // a pointer type, whose element is an integral scalar or pointer type.
3143 // Because it is a pointer type, we don't have to worry about any implicit
3144 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003145 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003146 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003147 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3148 if (FirstArgResult.isInvalid())
3149 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003150 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003151 TheCall->setArg(0, FirstArg);
3152
John McCall31168b02011-06-15 23:02:42 +00003153 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3154 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003155 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3156 << FirstArg->getType() << FirstArg->getSourceRange();
3157 return ExprError();
3158 }
Mike Stump11289f42009-09-09 15:08:12 +00003159
John McCall31168b02011-06-15 23:02:42 +00003160 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003161 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003162 !ValType->isBlockPointerType()) {
3163 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3164 << FirstArg->getType() << FirstArg->getSourceRange();
3165 return ExprError();
3166 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003167
John McCall31168b02011-06-15 23:02:42 +00003168 switch (ValType.getObjCLifetime()) {
3169 case Qualifiers::OCL_None:
3170 case Qualifiers::OCL_ExplicitNone:
3171 // okay
3172 break;
3173
3174 case Qualifiers::OCL_Weak:
3175 case Qualifiers::OCL_Strong:
3176 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003177 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003178 << ValType << FirstArg->getSourceRange();
3179 return ExprError();
3180 }
3181
John McCallb50451a2011-10-05 07:41:44 +00003182 // Strip any qualifiers off ValType.
3183 ValType = ValType.getUnqualifiedType();
3184
Chandler Carruth3973af72010-07-18 20:54:12 +00003185 // The majority of builtins return a value, but a few have special return
3186 // types, so allow them to override appropriately below.
3187 QualType ResultType = ValType;
3188
Chris Lattnerdc046542009-05-08 06:58:22 +00003189 // We need to figure out which concrete builtin this maps onto. For example,
3190 // __sync_fetch_and_add with a 2 byte object turns into
3191 // __sync_fetch_and_add_2.
3192#define BUILTIN_ROW(x) \
3193 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3194 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003195
Chris Lattnerdc046542009-05-08 06:58:22 +00003196 static const unsigned BuiltinIndices[][5] = {
3197 BUILTIN_ROW(__sync_fetch_and_add),
3198 BUILTIN_ROW(__sync_fetch_and_sub),
3199 BUILTIN_ROW(__sync_fetch_and_or),
3200 BUILTIN_ROW(__sync_fetch_and_and),
3201 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003202 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003203
Chris Lattnerdc046542009-05-08 06:58:22 +00003204 BUILTIN_ROW(__sync_add_and_fetch),
3205 BUILTIN_ROW(__sync_sub_and_fetch),
3206 BUILTIN_ROW(__sync_and_and_fetch),
3207 BUILTIN_ROW(__sync_or_and_fetch),
3208 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003209 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003210
Chris Lattnerdc046542009-05-08 06:58:22 +00003211 BUILTIN_ROW(__sync_val_compare_and_swap),
3212 BUILTIN_ROW(__sync_bool_compare_and_swap),
3213 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003214 BUILTIN_ROW(__sync_lock_release),
3215 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003216 };
Mike Stump11289f42009-09-09 15:08:12 +00003217#undef BUILTIN_ROW
3218
Chris Lattnerdc046542009-05-08 06:58:22 +00003219 // Determine the index of the size.
3220 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003221 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003222 case 1: SizeIndex = 0; break;
3223 case 2: SizeIndex = 1; break;
3224 case 4: SizeIndex = 2; break;
3225 case 8: SizeIndex = 3; break;
3226 case 16: SizeIndex = 4; break;
3227 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003228 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3229 << FirstArg->getType() << FirstArg->getSourceRange();
3230 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003231 }
Mike Stump11289f42009-09-09 15:08:12 +00003232
Chris Lattnerdc046542009-05-08 06:58:22 +00003233 // Each of these builtins has one pointer argument, followed by some number of
3234 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3235 // that we ignore. Find out which row of BuiltinIndices to read from as well
3236 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003237 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003238 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003239 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003240 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003241 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003242 case Builtin::BI__sync_fetch_and_add:
3243 case Builtin::BI__sync_fetch_and_add_1:
3244 case Builtin::BI__sync_fetch_and_add_2:
3245 case Builtin::BI__sync_fetch_and_add_4:
3246 case Builtin::BI__sync_fetch_and_add_8:
3247 case Builtin::BI__sync_fetch_and_add_16:
3248 BuiltinIndex = 0;
3249 break;
3250
3251 case Builtin::BI__sync_fetch_and_sub:
3252 case Builtin::BI__sync_fetch_and_sub_1:
3253 case Builtin::BI__sync_fetch_and_sub_2:
3254 case Builtin::BI__sync_fetch_and_sub_4:
3255 case Builtin::BI__sync_fetch_and_sub_8:
3256 case Builtin::BI__sync_fetch_and_sub_16:
3257 BuiltinIndex = 1;
3258 break;
3259
3260 case Builtin::BI__sync_fetch_and_or:
3261 case Builtin::BI__sync_fetch_and_or_1:
3262 case Builtin::BI__sync_fetch_and_or_2:
3263 case Builtin::BI__sync_fetch_and_or_4:
3264 case Builtin::BI__sync_fetch_and_or_8:
3265 case Builtin::BI__sync_fetch_and_or_16:
3266 BuiltinIndex = 2;
3267 break;
3268
3269 case Builtin::BI__sync_fetch_and_and:
3270 case Builtin::BI__sync_fetch_and_and_1:
3271 case Builtin::BI__sync_fetch_and_and_2:
3272 case Builtin::BI__sync_fetch_and_and_4:
3273 case Builtin::BI__sync_fetch_and_and_8:
3274 case Builtin::BI__sync_fetch_and_and_16:
3275 BuiltinIndex = 3;
3276 break;
Mike Stump11289f42009-09-09 15:08:12 +00003277
Douglas Gregor73722482011-11-28 16:30:08 +00003278 case Builtin::BI__sync_fetch_and_xor:
3279 case Builtin::BI__sync_fetch_and_xor_1:
3280 case Builtin::BI__sync_fetch_and_xor_2:
3281 case Builtin::BI__sync_fetch_and_xor_4:
3282 case Builtin::BI__sync_fetch_and_xor_8:
3283 case Builtin::BI__sync_fetch_and_xor_16:
3284 BuiltinIndex = 4;
3285 break;
3286
Hal Finkeld2208b52014-10-02 20:53:50 +00003287 case Builtin::BI__sync_fetch_and_nand:
3288 case Builtin::BI__sync_fetch_and_nand_1:
3289 case Builtin::BI__sync_fetch_and_nand_2:
3290 case Builtin::BI__sync_fetch_and_nand_4:
3291 case Builtin::BI__sync_fetch_and_nand_8:
3292 case Builtin::BI__sync_fetch_and_nand_16:
3293 BuiltinIndex = 5;
3294 WarnAboutSemanticsChange = true;
3295 break;
3296
Douglas Gregor73722482011-11-28 16:30:08 +00003297 case Builtin::BI__sync_add_and_fetch:
3298 case Builtin::BI__sync_add_and_fetch_1:
3299 case Builtin::BI__sync_add_and_fetch_2:
3300 case Builtin::BI__sync_add_and_fetch_4:
3301 case Builtin::BI__sync_add_and_fetch_8:
3302 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003303 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003304 break;
3305
3306 case Builtin::BI__sync_sub_and_fetch:
3307 case Builtin::BI__sync_sub_and_fetch_1:
3308 case Builtin::BI__sync_sub_and_fetch_2:
3309 case Builtin::BI__sync_sub_and_fetch_4:
3310 case Builtin::BI__sync_sub_and_fetch_8:
3311 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003312 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003313 break;
3314
3315 case Builtin::BI__sync_and_and_fetch:
3316 case Builtin::BI__sync_and_and_fetch_1:
3317 case Builtin::BI__sync_and_and_fetch_2:
3318 case Builtin::BI__sync_and_and_fetch_4:
3319 case Builtin::BI__sync_and_and_fetch_8:
3320 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003321 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003322 break;
3323
3324 case Builtin::BI__sync_or_and_fetch:
3325 case Builtin::BI__sync_or_and_fetch_1:
3326 case Builtin::BI__sync_or_and_fetch_2:
3327 case Builtin::BI__sync_or_and_fetch_4:
3328 case Builtin::BI__sync_or_and_fetch_8:
3329 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003330 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003331 break;
3332
3333 case Builtin::BI__sync_xor_and_fetch:
3334 case Builtin::BI__sync_xor_and_fetch_1:
3335 case Builtin::BI__sync_xor_and_fetch_2:
3336 case Builtin::BI__sync_xor_and_fetch_4:
3337 case Builtin::BI__sync_xor_and_fetch_8:
3338 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003339 BuiltinIndex = 10;
3340 break;
3341
3342 case Builtin::BI__sync_nand_and_fetch:
3343 case Builtin::BI__sync_nand_and_fetch_1:
3344 case Builtin::BI__sync_nand_and_fetch_2:
3345 case Builtin::BI__sync_nand_and_fetch_4:
3346 case Builtin::BI__sync_nand_and_fetch_8:
3347 case Builtin::BI__sync_nand_and_fetch_16:
3348 BuiltinIndex = 11;
3349 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003350 break;
Mike Stump11289f42009-09-09 15:08:12 +00003351
Chris Lattnerdc046542009-05-08 06:58:22 +00003352 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003353 case Builtin::BI__sync_val_compare_and_swap_1:
3354 case Builtin::BI__sync_val_compare_and_swap_2:
3355 case Builtin::BI__sync_val_compare_and_swap_4:
3356 case Builtin::BI__sync_val_compare_and_swap_8:
3357 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003358 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003359 NumFixed = 2;
3360 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003361
Chris Lattnerdc046542009-05-08 06:58:22 +00003362 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003363 case Builtin::BI__sync_bool_compare_and_swap_1:
3364 case Builtin::BI__sync_bool_compare_and_swap_2:
3365 case Builtin::BI__sync_bool_compare_and_swap_4:
3366 case Builtin::BI__sync_bool_compare_and_swap_8:
3367 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003368 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003369 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003370 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003371 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003372
3373 case Builtin::BI__sync_lock_test_and_set:
3374 case Builtin::BI__sync_lock_test_and_set_1:
3375 case Builtin::BI__sync_lock_test_and_set_2:
3376 case Builtin::BI__sync_lock_test_and_set_4:
3377 case Builtin::BI__sync_lock_test_and_set_8:
3378 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003379 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003380 break;
3381
Chris Lattnerdc046542009-05-08 06:58:22 +00003382 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003383 case Builtin::BI__sync_lock_release_1:
3384 case Builtin::BI__sync_lock_release_2:
3385 case Builtin::BI__sync_lock_release_4:
3386 case Builtin::BI__sync_lock_release_8:
3387 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003388 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003389 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003390 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003391 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003392
3393 case Builtin::BI__sync_swap:
3394 case Builtin::BI__sync_swap_1:
3395 case Builtin::BI__sync_swap_2:
3396 case Builtin::BI__sync_swap_4:
3397 case Builtin::BI__sync_swap_8:
3398 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003399 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003400 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003401 }
Mike Stump11289f42009-09-09 15:08:12 +00003402
Chris Lattnerdc046542009-05-08 06:58:22 +00003403 // Now that we know how many fixed arguments we expect, first check that we
3404 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003405 if (TheCall->getNumArgs() < 1+NumFixed) {
3406 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3407 << 0 << 1+NumFixed << TheCall->getNumArgs()
3408 << TheCall->getCallee()->getSourceRange();
3409 return ExprError();
3410 }
Mike Stump11289f42009-09-09 15:08:12 +00003411
Hal Finkeld2208b52014-10-02 20:53:50 +00003412 if (WarnAboutSemanticsChange) {
3413 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3414 << TheCall->getCallee()->getSourceRange();
3415 }
3416
Chris Lattner5b9241b2009-05-08 15:36:58 +00003417 // Get the decl for the concrete builtin from this, we can tell what the
3418 // concrete integer type we should convert to is.
3419 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003420 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003421 FunctionDecl *NewBuiltinDecl;
3422 if (NewBuiltinID == BuiltinID)
3423 NewBuiltinDecl = FDecl;
3424 else {
3425 // Perform builtin lookup to avoid redeclaring it.
3426 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3427 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3428 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3429 assert(Res.getFoundDecl());
3430 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003431 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003432 return ExprError();
3433 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003434
John McCallcf142162010-08-07 06:22:56 +00003435 // The first argument --- the pointer --- has a fixed type; we
3436 // deduce the types of the rest of the arguments accordingly. Walk
3437 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003438 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003439 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003440
Chris Lattnerdc046542009-05-08 06:58:22 +00003441 // GCC does an implicit conversion to the pointer or integer ValType. This
3442 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003443 // Initialize the argument.
3444 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3445 ValType, /*consume*/ false);
3446 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003447 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003448 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003449
Chris Lattnerdc046542009-05-08 06:58:22 +00003450 // Okay, we have something that *can* be converted to the right type. Check
3451 // to see if there is a potentially weird extension going on here. This can
3452 // happen when you do an atomic operation on something like an char* and
3453 // pass in 42. The 42 gets converted to char. This is even more strange
3454 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003455 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003456 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003457 }
Mike Stump11289f42009-09-09 15:08:12 +00003458
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003459 ASTContext& Context = this->getASTContext();
3460
3461 // Create a new DeclRefExpr to refer to the new decl.
3462 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3463 Context,
3464 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003465 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003466 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003467 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003468 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003469 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003470 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003471
Chris Lattnerdc046542009-05-08 06:58:22 +00003472 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003473 // FIXME: This loses syntactic information.
3474 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3475 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3476 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003477 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003478
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003479 // Change the result type of the call to match the original value type. This
3480 // is arbitrary, but the codegen for these builtins ins design to handle it
3481 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003482 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003483
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003484 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003485}
3486
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003487/// SemaBuiltinNontemporalOverloaded - We have a call to
3488/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3489/// overloaded function based on the pointer type of its last argument.
3490///
3491/// This function goes through and does final semantic checking for these
3492/// builtins.
3493ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3494 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3495 DeclRefExpr *DRE =
3496 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3497 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3498 unsigned BuiltinID = FDecl->getBuiltinID();
3499 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3500 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3501 "Unexpected nontemporal load/store builtin!");
3502 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3503 unsigned numArgs = isStore ? 2 : 1;
3504
3505 // Ensure that we have the proper number of arguments.
3506 if (checkArgCount(*this, TheCall, numArgs))
3507 return ExprError();
3508
3509 // Inspect the last argument of the nontemporal builtin. This should always
3510 // be a pointer type, from which we imply the type of the memory access.
3511 // Because it is a pointer type, we don't have to worry about any implicit
3512 // casts here.
3513 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3514 ExprResult PointerArgResult =
3515 DefaultFunctionArrayLvalueConversion(PointerArg);
3516
3517 if (PointerArgResult.isInvalid())
3518 return ExprError();
3519 PointerArg = PointerArgResult.get();
3520 TheCall->setArg(numArgs - 1, PointerArg);
3521
3522 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3523 if (!pointerType) {
3524 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3525 << PointerArg->getType() << PointerArg->getSourceRange();
3526 return ExprError();
3527 }
3528
3529 QualType ValType = pointerType->getPointeeType();
3530
3531 // Strip any qualifiers off ValType.
3532 ValType = ValType.getUnqualifiedType();
3533 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3534 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3535 !ValType->isVectorType()) {
3536 Diag(DRE->getLocStart(),
3537 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3538 << PointerArg->getType() << PointerArg->getSourceRange();
3539 return ExprError();
3540 }
3541
3542 if (!isStore) {
3543 TheCall->setType(ValType);
3544 return TheCallResult;
3545 }
3546
3547 ExprResult ValArg = TheCall->getArg(0);
3548 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3549 Context, ValType, /*consume*/ false);
3550 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3551 if (ValArg.isInvalid())
3552 return ExprError();
3553
3554 TheCall->setArg(0, ValArg.get());
3555 TheCall->setType(Context.VoidTy);
3556 return TheCallResult;
3557}
3558
Chris Lattner6436fb62009-02-18 06:01:06 +00003559/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003560/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003561/// Note: It might also make sense to do the UTF-16 conversion here (would
3562/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003563bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003564 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003565 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3566
Douglas Gregorfb65e592011-07-27 05:40:30 +00003567 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003568 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3569 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003570 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003571 }
Mike Stump11289f42009-09-09 15:08:12 +00003572
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003573 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003574 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003575 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00003576 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3577 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3578 llvm::UTF16 *ToPtr = &ToBuf[0];
3579
3580 llvm::ConversionResult Result =
3581 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3582 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003583 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00003584 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003585 Diag(Arg->getLocStart(),
3586 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3587 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003588 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003589}
3590
Mehdi Amini06d367c2016-10-24 20:39:34 +00003591/// CheckObjCString - Checks that the format string argument to the os_log()
3592/// and os_trace() functions is correct, and converts it to const char *.
3593ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3594 Arg = Arg->IgnoreParenCasts();
3595 auto *Literal = dyn_cast<StringLiteral>(Arg);
3596 if (!Literal) {
3597 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3598 Literal = ObjcLiteral->getString();
3599 }
3600 }
3601
3602 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3603 return ExprError(
3604 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3605 << Arg->getSourceRange());
3606 }
3607
3608 ExprResult Result(Literal);
3609 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3610 InitializedEntity Entity =
3611 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3612 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3613 return Result;
3614}
3615
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003616/// Check that the user is calling the appropriate va_start builtin for the
3617/// target and calling convention.
3618static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3619 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3620 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
3621 bool IsWindows = TT.isOSWindows();
3622 bool IsMSVAStart = BuiltinID == X86::BI__builtin_ms_va_start;
3623 if (IsX64) {
3624 clang::CallingConv CC = CC_C;
3625 if (const FunctionDecl *FD = S.getCurFunctionDecl())
3626 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3627 if (IsMSVAStart) {
3628 // Don't allow this in System V ABI functions.
3629 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_X86_64Win64))
3630 return S.Diag(Fn->getLocStart(),
3631 diag::err_ms_va_start_used_in_sysv_function);
3632 } else {
3633 // On x86-64 Unix, don't allow this in Win64 ABI functions.
3634 // On x64 Windows, don't allow this in System V ABI functions.
3635 // (Yes, that means there's no corresponding way to support variadic
3636 // System V ABI functions on Windows.)
3637 if ((IsWindows && CC == CC_X86_64SysV) ||
3638 (!IsWindows && CC == CC_X86_64Win64))
3639 return S.Diag(Fn->getLocStart(),
3640 diag::err_va_start_used_in_wrong_abi_function)
3641 << !IsWindows;
3642 }
3643 return false;
3644 }
3645
3646 if (IsMSVAStart)
3647 return S.Diag(Fn->getLocStart(), diag::err_x86_builtin_64_only);
3648 return false;
3649}
3650
3651static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3652 ParmVarDecl **LastParam = nullptr) {
3653 // Determine whether the current function, block, or obj-c method is variadic
3654 // and get its parameter list.
3655 bool IsVariadic = false;
3656 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00003657 DeclContext *Caller = S.CurContext;
3658 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3659 IsVariadic = Block->isVariadic();
3660 Params = Block->parameters();
3661 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003662 IsVariadic = FD->isVariadic();
3663 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003664 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003665 IsVariadic = MD->isVariadic();
3666 // FIXME: This isn't correct for methods (results in bogus warning).
3667 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003668 } else if (isa<CapturedDecl>(Caller)) {
3669 // We don't support va_start in a CapturedDecl.
3670 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3671 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003672 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003673 // This must be some other declcontext that parses exprs.
3674 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3675 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003676 }
3677
3678 if (!IsVariadic) {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003679 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003680 return true;
3681 }
3682
3683 if (LastParam)
3684 *LastParam = Params.empty() ? nullptr : Params.back();
3685
3686 return false;
3687}
3688
Charles Davisc7d5c942015-09-17 20:55:33 +00003689/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3690/// for validity. Emit an error and return true on failure; return false
3691/// on success.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003692bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003693 Expr *Fn = TheCall->getCallee();
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003694
3695 if (checkVAStartABI(*this, BuiltinID, Fn))
3696 return true;
3697
Chris Lattner08464942007-12-28 05:29:59 +00003698 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003699 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003700 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003701 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3702 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003703 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003704 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003705 return true;
3706 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003707
3708 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003709 return Diag(TheCall->getLocEnd(),
3710 diag::err_typecheck_call_too_few_args_at_least)
3711 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003712 }
3713
John McCall29ad95b2011-08-27 01:09:30 +00003714 // Type-check the first argument normally.
3715 if (checkBuiltinArgument(*this, TheCall, 0))
3716 return true;
3717
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003718 // Check that the current function is variadic, and get its last parameter.
3719 ParmVarDecl *LastParam;
3720 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
Chris Lattner43be2e62007-12-19 23:59:04 +00003721 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003722
Chris Lattner43be2e62007-12-19 23:59:04 +00003723 // Verify that the second argument to the builtin is the last argument of the
3724 // current function or method.
3725 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003726 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003727
Nico Weber9eea7642013-05-24 23:31:57 +00003728 // These are valid if SecondArgIsLastNamedArgument is false after the next
3729 // block.
3730 QualType Type;
3731 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003732 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003733
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003734 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3735 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003736 SecondArgIsLastNamedArgument = PV == LastParam;
Nico Weber9eea7642013-05-24 23:31:57 +00003737
3738 Type = PV->getType();
3739 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003740 IsCRegister =
3741 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003742 }
3743 }
Mike Stump11289f42009-09-09 15:08:12 +00003744
Chris Lattner43be2e62007-12-19 23:59:04 +00003745 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003746 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003747 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003748 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00003749 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3750 // Promotable integers are UB, but enumerations need a bit of
3751 // extra checking to see what their promotable type actually is.
3752 if (!Type->isPromotableIntegerType())
3753 return false;
3754 if (!Type->isEnumeralType())
3755 return true;
3756 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3757 return !(ED &&
3758 Context.typesAreCompatible(ED->getPromotionType(), Type));
3759 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00003760 unsigned Reason = 0;
3761 if (Type->isReferenceType()) Reason = 1;
3762 else if (IsCRegister) Reason = 2;
3763 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003764 Diag(ParamLoc, diag::note_parameter_type) << Type;
3765 }
3766
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003767 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003768 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003769}
Chris Lattner43be2e62007-12-19 23:59:04 +00003770
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003771bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3772 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3773 // const char *named_addr);
3774
3775 Expr *Func = Call->getCallee();
3776
3777 if (Call->getNumArgs() < 3)
3778 return Diag(Call->getLocEnd(),
3779 diag::err_typecheck_call_too_few_args_at_least)
3780 << 0 /*function call*/ << 3 << Call->getNumArgs();
3781
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003782 // Type-check the first argument normally.
3783 if (checkBuiltinArgument(*this, Call, 0))
3784 return true;
3785
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003786 // Check that the current function is variadic.
3787 if (checkVAStartIsInVariadicFunction(*this, Func))
3788 return true;
3789
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003790 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003791 unsigned ArgNo;
3792 QualType Type;
3793 } ArgumentTypes[] = {
3794 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3795 { 2, Context.getSizeType() },
3796 };
3797
3798 for (const auto &AT : ArgumentTypes) {
3799 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3800 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3801 continue;
3802 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3803 << Arg->getType() << AT.Type << 1 /* different class */
3804 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3805 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3806 }
3807
3808 return false;
3809}
3810
Chris Lattner2da14fb2007-12-20 00:26:33 +00003811/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3812/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003813bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3814 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003815 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003816 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003817 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003818 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003819 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003820 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003821 << SourceRange(TheCall->getArg(2)->getLocStart(),
3822 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003823
John Wiegley01296292011-04-08 18:41:53 +00003824 ExprResult OrigArg0 = TheCall->getArg(0);
3825 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003826
Chris Lattner2da14fb2007-12-20 00:26:33 +00003827 // Do standard promotions between the two arguments, returning their common
3828 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003829 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003830 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3831 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003832
3833 // Make sure any conversions are pushed back into the call; this is
3834 // type safe since unordered compare builtins are declared as "_Bool
3835 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003836 TheCall->setArg(0, OrigArg0.get());
3837 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003838
John Wiegley01296292011-04-08 18:41:53 +00003839 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003840 return false;
3841
Chris Lattner2da14fb2007-12-20 00:26:33 +00003842 // If the common type isn't a real floating type, then the arguments were
3843 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003844 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00003845 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003846 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00003847 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3848 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003849
Chris Lattner2da14fb2007-12-20 00:26:33 +00003850 return false;
3851}
3852
Benjamin Kramer634fc102010-02-15 22:42:31 +00003853/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3854/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00003855/// to check everything. We expect the last argument to be a floating point
3856/// value.
3857bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3858 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00003859 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003860 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00003861 if (TheCall->getNumArgs() > NumArgs)
3862 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003863 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003864 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00003865 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003866 (*(TheCall->arg_end()-1))->getLocEnd());
3867
Benjamin Kramer64aae502010-02-16 10:07:31 +00003868 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00003869
Eli Friedman7e4faac2009-08-31 20:06:00 +00003870 if (OrigArg->isTypeDependent())
3871 return false;
3872
Chris Lattner68784ef2010-05-06 05:50:07 +00003873 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00003874 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00003875 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003876 diag::err_typecheck_call_invalid_unary_fp)
3877 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003878
Neil Hickey88c0fac2016-12-13 16:22:50 +00003879 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00003880 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00003881 // Only remove standard FloatCasts, leaving other casts inplace
3882 if (Cast->getCastKind() == CK_FloatingCast) {
3883 Expr *CastArg = Cast->getSubExpr();
3884 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3885 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
3886 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
3887 "promotion from float to either float or double is the only expected cast here");
3888 Cast->setSubExpr(nullptr);
3889 TheCall->setArg(NumArgs-1, CastArg);
3890 }
Chris Lattner68784ef2010-05-06 05:50:07 +00003891 }
3892 }
3893
Eli Friedman7e4faac2009-08-31 20:06:00 +00003894 return false;
3895}
3896
Tony Jiangbbc48e92017-05-24 15:13:32 +00003897// Customized Sema Checking for VSX builtins that have the following signature:
3898// vector [...] builtinName(vector [...], vector [...], const int);
3899// Which takes the same type of vectors (any legal vector type) for the first
3900// two arguments and takes compile time constant for the third argument.
3901// Example builtins are :
3902// vector double vec_xxpermdi(vector double, vector double, int);
3903// vector short vec_xxsldwi(vector short, vector short, int);
3904bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
3905 unsigned ExpectedNumArgs = 3;
3906 if (TheCall->getNumArgs() < ExpectedNumArgs)
3907 return Diag(TheCall->getLocEnd(),
3908 diag::err_typecheck_call_too_few_args_at_least)
3909 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
3910 << TheCall->getSourceRange();
3911
3912 if (TheCall->getNumArgs() > ExpectedNumArgs)
3913 return Diag(TheCall->getLocEnd(),
3914 diag::err_typecheck_call_too_many_args_at_most)
3915 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
3916 << TheCall->getSourceRange();
3917
3918 // Check the third argument is a compile time constant
3919 llvm::APSInt Value;
3920 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
3921 return Diag(TheCall->getLocStart(),
3922 diag::err_vsx_builtin_nonconstant_argument)
3923 << 3 /* argument index */ << TheCall->getDirectCallee()
3924 << SourceRange(TheCall->getArg(2)->getLocStart(),
3925 TheCall->getArg(2)->getLocEnd());
3926
3927 QualType Arg1Ty = TheCall->getArg(0)->getType();
3928 QualType Arg2Ty = TheCall->getArg(1)->getType();
3929
3930 // Check the type of argument 1 and argument 2 are vectors.
3931 SourceLocation BuiltinLoc = TheCall->getLocStart();
3932 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
3933 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
3934 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
3935 << TheCall->getDirectCallee()
3936 << SourceRange(TheCall->getArg(0)->getLocStart(),
3937 TheCall->getArg(1)->getLocEnd());
3938 }
3939
3940 // Check the first two arguments are the same type.
3941 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
3942 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
3943 << TheCall->getDirectCallee()
3944 << SourceRange(TheCall->getArg(0)->getLocStart(),
3945 TheCall->getArg(1)->getLocEnd());
3946 }
3947
3948 // When default clang type checking is turned off and the customized type
3949 // checking is used, the returning type of the function must be explicitly
3950 // set. Otherwise it is _Bool by default.
3951 TheCall->setType(Arg1Ty);
3952
3953 return false;
3954}
3955
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003956/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3957// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00003958ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00003959 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003960 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00003961 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00003962 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3963 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003964
Nate Begemana0110022010-06-08 00:16:34 +00003965 // Determine which of the following types of shufflevector we're checking:
3966 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00003967 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00003968 QualType resType = TheCall->getArg(0)->getType();
3969 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00003970
Douglas Gregorc25f7662009-05-19 22:10:17 +00003971 if (!TheCall->getArg(0)->isTypeDependent() &&
3972 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00003973 QualType LHSType = TheCall->getArg(0)->getType();
3974 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00003975
Craig Topperbaca3892013-07-29 06:47:04 +00003976 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3977 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00003978 diag::err_vec_builtin_non_vector)
3979 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00003980 << SourceRange(TheCall->getArg(0)->getLocStart(),
3981 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003982
Nate Begemana0110022010-06-08 00:16:34 +00003983 numElements = LHSType->getAs<VectorType>()->getNumElements();
3984 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00003985
Nate Begemana0110022010-06-08 00:16:34 +00003986 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3987 // with mask. If so, verify that RHS is an integer vector type with the
3988 // same number of elts as lhs.
3989 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00003990 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00003991 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00003992 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00003993 diag::err_vec_builtin_incompatible_vector)
3994 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00003995 << SourceRange(TheCall->getArg(1)->getLocStart(),
3996 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003997 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00003998 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00003999 diag::err_vec_builtin_incompatible_vector)
4000 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004001 << SourceRange(TheCall->getArg(0)->getLocStart(),
4002 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00004003 } else if (numElements != numResElements) {
4004 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00004005 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00004006 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004007 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004008 }
4009
4010 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00004011 if (TheCall->getArg(i)->isTypeDependent() ||
4012 TheCall->getArg(i)->isValueDependent())
4013 continue;
4014
Nate Begemana0110022010-06-08 00:16:34 +00004015 llvm::APSInt Result(32);
4016 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4017 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004018 diag::err_shufflevector_nonconstant_argument)
4019 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004020
Craig Topper50ad5b72013-08-03 17:40:38 +00004021 // Allow -1 which will be translated to undef in the IR.
4022 if (Result.isSigned() && Result.isAllOnesValue())
4023 continue;
4024
Chris Lattner7ab824e2008-08-10 02:05:13 +00004025 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004026 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004027 diag::err_shufflevector_argument_too_large)
4028 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004029 }
4030
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004031 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004032
Chris Lattner7ab824e2008-08-10 02:05:13 +00004033 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004034 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00004035 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004036 }
4037
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004038 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4039 TheCall->getCallee()->getLocStart(),
4040 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004041}
Chris Lattner43be2e62007-12-19 23:59:04 +00004042
Hal Finkelc4d7c822013-09-18 03:29:45 +00004043/// SemaConvertVectorExpr - Handle __builtin_convertvector
4044ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4045 SourceLocation BuiltinLoc,
4046 SourceLocation RParenLoc) {
4047 ExprValueKind VK = VK_RValue;
4048 ExprObjectKind OK = OK_Ordinary;
4049 QualType DstTy = TInfo->getType();
4050 QualType SrcTy = E->getType();
4051
4052 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4053 return ExprError(Diag(BuiltinLoc,
4054 diag::err_convertvector_non_vector)
4055 << E->getSourceRange());
4056 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4057 return ExprError(Diag(BuiltinLoc,
4058 diag::err_convertvector_non_vector_type));
4059
4060 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4061 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4062 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4063 if (SrcElts != DstElts)
4064 return ExprError(Diag(BuiltinLoc,
4065 diag::err_convertvector_incompatible_vector)
4066 << E->getSourceRange());
4067 }
4068
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004069 return new (Context)
4070 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00004071}
4072
Daniel Dunbarb7257262008-07-21 22:59:13 +00004073/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4074// This is declared to take (const void*, ...) and can take two
4075// optional constant int args.
4076bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00004077 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004078
Chris Lattner3b054132008-11-19 05:08:23 +00004079 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004080 return Diag(TheCall->getLocEnd(),
4081 diag::err_typecheck_call_too_many_args_at_most)
4082 << 0 /*function call*/ << 3 << NumArgs
4083 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004084
4085 // Argument 0 is checked for us and the remaining arguments must be
4086 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00004087 for (unsigned i = 1; i != NumArgs; ++i)
4088 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004089 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004090
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004091 return false;
4092}
4093
Hal Finkelf0417332014-07-17 14:25:55 +00004094/// SemaBuiltinAssume - Handle __assume (MS Extension).
4095// __assume does not evaluate its arguments, and should warn if its argument
4096// has side effects.
4097bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4098 Expr *Arg = TheCall->getArg(0);
4099 if (Arg->isInstantiationDependent()) return false;
4100
4101 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00004102 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00004103 << Arg->getSourceRange()
4104 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4105
4106 return false;
4107}
4108
David Majnemer86b1bfa2016-10-31 18:07:57 +00004109/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00004110/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4111/// than 8.
4112bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4113 // The alignment must be a constant integer.
4114 Expr *Arg = TheCall->getArg(1);
4115
4116 // We can't check the value of a dependent argument.
4117 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00004118 if (const auto *UE =
4119 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4120 if (UE->getKind() == UETT_AlignOf)
4121 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4122 << Arg->getSourceRange();
4123
David Majnemer51169932016-10-31 05:37:48 +00004124 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4125
4126 if (!Result.isPowerOf2())
4127 return Diag(TheCall->getLocStart(),
4128 diag::err_alignment_not_power_of_two)
4129 << Arg->getSourceRange();
4130
4131 if (Result < Context.getCharWidth())
4132 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4133 << (unsigned)Context.getCharWidth()
4134 << Arg->getSourceRange();
4135
4136 if (Result > INT32_MAX)
4137 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4138 << INT32_MAX
4139 << Arg->getSourceRange();
4140 }
4141
4142 return false;
4143}
4144
4145/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00004146/// as (const void*, size_t, ...) and can take one optional constant int arg.
4147bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4148 unsigned NumArgs = TheCall->getNumArgs();
4149
4150 if (NumArgs > 3)
4151 return Diag(TheCall->getLocEnd(),
4152 diag::err_typecheck_call_too_many_args_at_most)
4153 << 0 /*function call*/ << 3 << NumArgs
4154 << TheCall->getSourceRange();
4155
4156 // The alignment must be a constant integer.
4157 Expr *Arg = TheCall->getArg(1);
4158
4159 // We can't check the value of a dependent argument.
4160 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4161 llvm::APSInt Result;
4162 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4163 return true;
4164
4165 if (!Result.isPowerOf2())
4166 return Diag(TheCall->getLocStart(),
4167 diag::err_alignment_not_power_of_two)
4168 << Arg->getSourceRange();
4169 }
4170
4171 if (NumArgs > 2) {
4172 ExprResult Arg(TheCall->getArg(2));
4173 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4174 Context.getSizeType(), false);
4175 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4176 if (Arg.isInvalid()) return true;
4177 TheCall->setArg(2, Arg.get());
4178 }
Hal Finkelf0417332014-07-17 14:25:55 +00004179
4180 return false;
4181}
4182
Mehdi Amini06d367c2016-10-24 20:39:34 +00004183bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4184 unsigned BuiltinID =
4185 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4186 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4187
4188 unsigned NumArgs = TheCall->getNumArgs();
4189 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4190 if (NumArgs < NumRequiredArgs) {
4191 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4192 << 0 /* function call */ << NumRequiredArgs << NumArgs
4193 << TheCall->getSourceRange();
4194 }
4195 if (NumArgs >= NumRequiredArgs + 0x100) {
4196 return Diag(TheCall->getLocEnd(),
4197 diag::err_typecheck_call_too_many_args_at_most)
4198 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4199 << TheCall->getSourceRange();
4200 }
4201 unsigned i = 0;
4202
4203 // For formatting call, check buffer arg.
4204 if (!IsSizeCall) {
4205 ExprResult Arg(TheCall->getArg(i));
4206 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4207 Context, Context.VoidPtrTy, false);
4208 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4209 if (Arg.isInvalid())
4210 return true;
4211 TheCall->setArg(i, Arg.get());
4212 i++;
4213 }
4214
4215 // Check string literal arg.
4216 unsigned FormatIdx = i;
4217 {
4218 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4219 if (Arg.isInvalid())
4220 return true;
4221 TheCall->setArg(i, Arg.get());
4222 i++;
4223 }
4224
4225 // Make sure variadic args are scalar.
4226 unsigned FirstDataArg = i;
4227 while (i < NumArgs) {
4228 ExprResult Arg = DefaultVariadicArgumentPromotion(
4229 TheCall->getArg(i), VariadicFunction, nullptr);
4230 if (Arg.isInvalid())
4231 return true;
4232 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4233 if (ArgSize.getQuantity() >= 0x100) {
4234 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4235 << i << (int)ArgSize.getQuantity() << 0xff
4236 << TheCall->getSourceRange();
4237 }
4238 TheCall->setArg(i, Arg.get());
4239 i++;
4240 }
4241
4242 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4243 // call to avoid duplicate diagnostics.
4244 if (!IsSizeCall) {
4245 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4246 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4247 bool Success = CheckFormatArguments(
4248 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4249 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4250 CheckedVarArgs);
4251 if (!Success)
4252 return true;
4253 }
4254
4255 if (IsSizeCall) {
4256 TheCall->setType(Context.getSizeType());
4257 } else {
4258 TheCall->setType(Context.VoidPtrTy);
4259 }
4260 return false;
4261}
4262
Eric Christopher8d0c6212010-04-17 02:26:23 +00004263/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4264/// TheCall is a constant expression.
4265bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4266 llvm::APSInt &Result) {
4267 Expr *Arg = TheCall->getArg(ArgNum);
4268 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4269 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4270
4271 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4272
4273 if (!Arg->isIntegerConstantExpr(Result, Context))
4274 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004275 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004276
Chris Lattnerd545ad12009-09-23 06:06:36 +00004277 return false;
4278}
4279
Richard Sandiford28940af2014-04-16 08:47:51 +00004280/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4281/// TheCall is a constant expression in the range [Low, High].
4282bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4283 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004284 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004285
4286 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004287 Expr *Arg = TheCall->getArg(ArgNum);
4288 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004289 return false;
4290
Eric Christopher8d0c6212010-04-17 02:26:23 +00004291 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004292 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004293 return true;
4294
Richard Sandiford28940af2014-04-16 08:47:51 +00004295 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004296 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004297 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004298
4299 return false;
4300}
4301
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004302/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4303/// TheCall is a constant expression is a multiple of Num..
4304bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4305 unsigned Num) {
4306 llvm::APSInt Result;
4307
4308 // We can't check the value of a dependent argument.
4309 Expr *Arg = TheCall->getArg(ArgNum);
4310 if (Arg->isTypeDependent() || Arg->isValueDependent())
4311 return false;
4312
4313 // Check constant-ness first.
4314 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4315 return true;
4316
4317 if (Result.getSExtValue() % Num != 0)
4318 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4319 << Num << Arg->getSourceRange();
4320
4321 return false;
4322}
4323
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004324/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4325/// TheCall is an ARM/AArch64 special register string literal.
4326bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4327 int ArgNum, unsigned ExpectedFieldNum,
4328 bool AllowName) {
4329 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4330 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4331 BuiltinID == ARM::BI__builtin_arm_rsr ||
4332 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4333 BuiltinID == ARM::BI__builtin_arm_wsr ||
4334 BuiltinID == ARM::BI__builtin_arm_wsrp;
4335 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4336 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4337 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4338 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4339 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4340 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4341 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4342
4343 // We can't check the value of a dependent argument.
4344 Expr *Arg = TheCall->getArg(ArgNum);
4345 if (Arg->isTypeDependent() || Arg->isValueDependent())
4346 return false;
4347
4348 // Check if the argument is a string literal.
4349 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4350 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4351 << Arg->getSourceRange();
4352
4353 // Check the type of special register given.
4354 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4355 SmallVector<StringRef, 6> Fields;
4356 Reg.split(Fields, ":");
4357
4358 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4359 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4360 << Arg->getSourceRange();
4361
4362 // If the string is the name of a register then we cannot check that it is
4363 // valid here but if the string is of one the forms described in ACLE then we
4364 // can check that the supplied fields are integers and within the valid
4365 // ranges.
4366 if (Fields.size() > 1) {
4367 bool FiveFields = Fields.size() == 5;
4368
4369 bool ValidString = true;
4370 if (IsARMBuiltin) {
4371 ValidString &= Fields[0].startswith_lower("cp") ||
4372 Fields[0].startswith_lower("p");
4373 if (ValidString)
4374 Fields[0] =
4375 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4376
4377 ValidString &= Fields[2].startswith_lower("c");
4378 if (ValidString)
4379 Fields[2] = Fields[2].drop_front(1);
4380
4381 if (FiveFields) {
4382 ValidString &= Fields[3].startswith_lower("c");
4383 if (ValidString)
4384 Fields[3] = Fields[3].drop_front(1);
4385 }
4386 }
4387
4388 SmallVector<int, 5> Ranges;
4389 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00004390 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004391 else
4392 Ranges.append({15, 7, 15});
4393
4394 for (unsigned i=0; i<Fields.size(); ++i) {
4395 int IntField;
4396 ValidString &= !Fields[i].getAsInteger(10, IntField);
4397 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4398 }
4399
4400 if (!ValidString)
4401 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4402 << Arg->getSourceRange();
4403
4404 } else if (IsAArch64Builtin && Fields.size() == 1) {
4405 // If the register name is one of those that appear in the condition below
4406 // and the special register builtin being used is one of the write builtins,
4407 // then we require that the argument provided for writing to the register
4408 // is an integer constant expression. This is because it will be lowered to
4409 // an MSR (immediate) instruction, so we need to know the immediate at
4410 // compile time.
4411 if (TheCall->getNumArgs() != 2)
4412 return false;
4413
4414 std::string RegLower = Reg.lower();
4415 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4416 RegLower != "pan" && RegLower != "uao")
4417 return false;
4418
4419 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4420 }
4421
4422 return false;
4423}
4424
Eli Friedmanc97d0142009-05-03 06:04:26 +00004425/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004426/// This checks that the target supports __builtin_longjmp and
4427/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004428bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004429 if (!Context.getTargetInfo().hasSjLjLowering())
4430 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4431 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4432
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004433 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004434 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004435
Eric Christopher8d0c6212010-04-17 02:26:23 +00004436 // TODO: This is less than ideal. Overload this to take a value.
4437 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4438 return true;
4439
4440 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004441 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4442 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4443
4444 return false;
4445}
4446
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004447/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4448/// This checks that the target supports __builtin_setjmp.
4449bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4450 if (!Context.getTargetInfo().hasSjLjLowering())
4451 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4452 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4453 return false;
4454}
4455
Richard Smithd7293d72013-08-05 18:49:43 +00004456namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004457class UncoveredArgHandler {
4458 enum { Unknown = -1, AllCovered = -2 };
4459 signed FirstUncoveredArg;
4460 SmallVector<const Expr *, 4> DiagnosticExprs;
4461
4462public:
4463 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4464
4465 bool hasUncoveredArg() const {
4466 return (FirstUncoveredArg >= 0);
4467 }
4468
4469 unsigned getUncoveredArg() const {
4470 assert(hasUncoveredArg() && "no uncovered argument");
4471 return FirstUncoveredArg;
4472 }
4473
4474 void setAllCovered() {
4475 // A string has been found with all arguments covered, so clear out
4476 // the diagnostics.
4477 DiagnosticExprs.clear();
4478 FirstUncoveredArg = AllCovered;
4479 }
4480
4481 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4482 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4483
4484 // Don't update if a previous string covers all arguments.
4485 if (FirstUncoveredArg == AllCovered)
4486 return;
4487
4488 // UncoveredArgHandler tracks the highest uncovered argument index
4489 // and with it all the strings that match this index.
4490 if (NewFirstUncoveredArg == FirstUncoveredArg)
4491 DiagnosticExprs.push_back(StrExpr);
4492 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4493 DiagnosticExprs.clear();
4494 DiagnosticExprs.push_back(StrExpr);
4495 FirstUncoveredArg = NewFirstUncoveredArg;
4496 }
4497 }
4498
4499 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4500};
4501
Richard Smithd7293d72013-08-05 18:49:43 +00004502enum StringLiteralCheckType {
4503 SLCT_NotALiteral,
4504 SLCT_UncheckedLiteral,
4505 SLCT_CheckedLiteral
4506};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004507} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00004508
Stephen Hines648c3692016-09-16 01:07:04 +00004509static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4510 BinaryOperatorKind BinOpKind,
4511 bool AddendIsRight) {
4512 unsigned BitWidth = Offset.getBitWidth();
4513 unsigned AddendBitWidth = Addend.getBitWidth();
4514 // There might be negative interim results.
4515 if (Addend.isUnsigned()) {
4516 Addend = Addend.zext(++AddendBitWidth);
4517 Addend.setIsSigned(true);
4518 }
4519 // Adjust the bit width of the APSInts.
4520 if (AddendBitWidth > BitWidth) {
4521 Offset = Offset.sext(AddendBitWidth);
4522 BitWidth = AddendBitWidth;
4523 } else if (BitWidth > AddendBitWidth) {
4524 Addend = Addend.sext(BitWidth);
4525 }
4526
4527 bool Ov = false;
4528 llvm::APSInt ResOffset = Offset;
4529 if (BinOpKind == BO_Add)
4530 ResOffset = Offset.sadd_ov(Addend, Ov);
4531 else {
4532 assert(AddendIsRight && BinOpKind == BO_Sub &&
4533 "operator must be add or sub with addend on the right");
4534 ResOffset = Offset.ssub_ov(Addend, Ov);
4535 }
4536
4537 // We add an offset to a pointer here so we should support an offset as big as
4538 // possible.
4539 if (Ov) {
4540 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00004541 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00004542 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4543 return;
4544 }
4545
4546 Offset = ResOffset;
4547}
4548
4549namespace {
4550// This is a wrapper class around StringLiteral to support offsetted string
4551// literals as format strings. It takes the offset into account when returning
4552// the string and its length or the source locations to display notes correctly.
4553class FormatStringLiteral {
4554 const StringLiteral *FExpr;
4555 int64_t Offset;
4556
4557 public:
4558 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4559 : FExpr(fexpr), Offset(Offset) {}
4560
4561 StringRef getString() const {
4562 return FExpr->getString().drop_front(Offset);
4563 }
4564
4565 unsigned getByteLength() const {
4566 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4567 }
4568 unsigned getLength() const { return FExpr->getLength() - Offset; }
4569 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4570
4571 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4572
4573 QualType getType() const { return FExpr->getType(); }
4574
4575 bool isAscii() const { return FExpr->isAscii(); }
4576 bool isWide() const { return FExpr->isWide(); }
4577 bool isUTF8() const { return FExpr->isUTF8(); }
4578 bool isUTF16() const { return FExpr->isUTF16(); }
4579 bool isUTF32() const { return FExpr->isUTF32(); }
4580 bool isPascal() const { return FExpr->isPascal(); }
4581
4582 SourceLocation getLocationOfByte(
4583 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4584 const TargetInfo &Target, unsigned *StartToken = nullptr,
4585 unsigned *StartTokenByteOffset = nullptr) const {
4586 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4587 StartToken, StartTokenByteOffset);
4588 }
4589
4590 SourceLocation getLocStart() const LLVM_READONLY {
4591 return FExpr->getLocStart().getLocWithOffset(Offset);
4592 }
4593 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4594};
4595} // end anonymous namespace
4596
4597static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004598 const Expr *OrigFormatExpr,
4599 ArrayRef<const Expr *> Args,
4600 bool HasVAListArg, unsigned format_idx,
4601 unsigned firstDataArg,
4602 Sema::FormatStringType Type,
4603 bool inFunctionCall,
4604 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004605 llvm::SmallBitVector &CheckedVarArgs,
4606 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004607
Richard Smith55ce3522012-06-25 20:30:08 +00004608// Determine if an expression is a string literal or constant string.
4609// If this function returns false on the arguments to a function expecting a
4610// format string, we will usually need to emit a warning.
4611// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00004612static StringLiteralCheckType
4613checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4614 bool HasVAListArg, unsigned format_idx,
4615 unsigned firstDataArg, Sema::FormatStringType Type,
4616 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004617 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004618 UncoveredArgHandler &UncoveredArg,
4619 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00004620 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00004621 assert(Offset.isSigned() && "invalid offset");
4622
Douglas Gregorc25f7662009-05-19 22:10:17 +00004623 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00004624 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004625
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004626 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00004627
Richard Smithd7293d72013-08-05 18:49:43 +00004628 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00004629 // Technically -Wformat-nonliteral does not warn about this case.
4630 // The behavior of printf and friends in this case is implementation
4631 // dependent. Ideally if the format string cannot be null then
4632 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00004633 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00004634
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004635 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00004636 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004637 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00004638 // The expression is a literal if both sub-expressions were, and it was
4639 // completely checked only if both sub-expressions were checked.
4640 const AbstractConditionalOperator *C =
4641 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004642
4643 // Determine whether it is necessary to check both sub-expressions, for
4644 // example, because the condition expression is a constant that can be
4645 // evaluated at compile time.
4646 bool CheckLeft = true, CheckRight = true;
4647
4648 bool Cond;
4649 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4650 if (Cond)
4651 CheckRight = false;
4652 else
4653 CheckLeft = false;
4654 }
4655
Stephen Hines648c3692016-09-16 01:07:04 +00004656 // We need to maintain the offsets for the right and the left hand side
4657 // separately to check if every possible indexed expression is a valid
4658 // string literal. They might have different offsets for different string
4659 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004660 StringLiteralCheckType Left;
4661 if (!CheckLeft)
4662 Left = SLCT_UncheckedLiteral;
4663 else {
4664 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4665 HasVAListArg, format_idx, firstDataArg,
4666 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004667 CheckedVarArgs, UncoveredArg, Offset);
4668 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004669 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004670 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004671 }
4672
Richard Smith55ce3522012-06-25 20:30:08 +00004673 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004674 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004675 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004676 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004677 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004678
4679 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004680 }
4681
4682 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00004683 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4684 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004685 }
4686
John McCallc07a0c72011-02-17 10:25:35 +00004687 case Stmt::OpaqueValueExprClass:
4688 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4689 E = src;
4690 goto tryAgain;
4691 }
Richard Smith55ce3522012-06-25 20:30:08 +00004692 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004693
Ted Kremeneka8890832011-02-24 23:03:04 +00004694 case Stmt::PredefinedExprClass:
4695 // While __func__, etc., are technically not string literals, they
4696 // cannot contain format specifiers and thus are not a security
4697 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004698 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004699
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004700 case Stmt::DeclRefExprClass: {
4701 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004702
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004703 // As an exception, do not flag errors for variables binding to
4704 // const string literals.
4705 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4706 bool isConstant = false;
4707 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004708
Richard Smithd7293d72013-08-05 18:49:43 +00004709 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4710 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004711 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004712 isConstant = T.isConstant(S.Context) &&
4713 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004714 } else if (T->isObjCObjectPointerType()) {
4715 // In ObjC, there is usually no "const ObjectPointer" type,
4716 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004717 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004718 }
Mike Stump11289f42009-09-09 15:08:12 +00004719
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004720 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004721 if (const Expr *Init = VD->getAnyInitializer()) {
4722 // Look through initializers like const char c[] = { "foo" }
4723 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4724 if (InitList->isStringLiteralInit())
4725 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4726 }
Richard Smithd7293d72013-08-05 18:49:43 +00004727 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004728 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004729 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004730 /*InFunctionCall*/ false, CheckedVarArgs,
4731 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004732 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004733 }
Mike Stump11289f42009-09-09 15:08:12 +00004734
Anders Carlssonb012ca92009-06-28 19:55:58 +00004735 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4736 // special check to see if the format string is a function parameter
4737 // of the function calling the printf function. If the function
4738 // has an attribute indicating it is a printf-like function, then we
4739 // should suppress warnings concerning non-literals being used in a call
4740 // to a vprintf function. For example:
4741 //
4742 // void
4743 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4744 // va_list ap;
4745 // va_start(ap, fmt);
4746 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4747 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00004748 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004749 if (HasVAListArg) {
4750 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4751 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4752 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004753 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004754 // adjust for implicit parameter
4755 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4756 if (MD->isInstance())
4757 ++PVIndex;
4758 // We also check if the formats are compatible.
4759 // We can't pass a 'scanf' string to a 'printf' function.
4760 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00004761 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00004762 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004763 }
4764 }
4765 }
4766 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004767 }
Mike Stump11289f42009-09-09 15:08:12 +00004768
Richard Smith55ce3522012-06-25 20:30:08 +00004769 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004770 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004771
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004772 case Stmt::CallExprClass:
4773 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004774 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004775 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4776 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4777 unsigned ArgIndex = FA->getFormatIdx();
4778 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4779 if (MD->isInstance())
4780 --ArgIndex;
4781 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00004782
Richard Smithd7293d72013-08-05 18:49:43 +00004783 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004784 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00004785 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004786 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004787 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4788 unsigned BuiltinID = FD->getBuiltinID();
4789 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4790 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4791 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00004792 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004793 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004794 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004795 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004796 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004797 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004798 }
4799 }
Mike Stump11289f42009-09-09 15:08:12 +00004800
Richard Smith55ce3522012-06-25 20:30:08 +00004801 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004802 }
Alex Lorenzd9007142016-10-24 09:42:34 +00004803 case Stmt::ObjCMessageExprClass: {
4804 const auto *ME = cast<ObjCMessageExpr>(E);
4805 if (const auto *ND = ME->getMethodDecl()) {
4806 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4807 unsigned ArgIndex = FA->getFormatIdx();
4808 const Expr *Arg = ME->getArg(ArgIndex - 1);
4809 return checkFormatStringExpr(
4810 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4811 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4812 }
4813 }
4814
4815 return SLCT_NotALiteral;
4816 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004817 case Stmt::ObjCStringLiteralClass:
4818 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00004819 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004820
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004821 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004822 StrE = ObjCFExpr->getString();
4823 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004824 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004825
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004826 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00004827 if (Offset.isNegative() || Offset > StrE->getLength()) {
4828 // TODO: It would be better to have an explicit warning for out of
4829 // bounds literals.
4830 return SLCT_NotALiteral;
4831 }
4832 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4833 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004834 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004835 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00004836 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004837 }
Mike Stump11289f42009-09-09 15:08:12 +00004838
Richard Smith55ce3522012-06-25 20:30:08 +00004839 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004840 }
Stephen Hines648c3692016-09-16 01:07:04 +00004841 case Stmt::BinaryOperatorClass: {
4842 llvm::APSInt LResult;
4843 llvm::APSInt RResult;
4844
4845 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4846
4847 // A string literal + an int offset is still a string literal.
4848 if (BinOp->isAdditiveOp()) {
4849 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4850 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4851
4852 if (LIsInt != RIsInt) {
4853 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4854
4855 if (LIsInt) {
4856 if (BinOpKind == BO_Add) {
4857 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4858 E = BinOp->getRHS();
4859 goto tryAgain;
4860 }
4861 } else {
4862 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4863 E = BinOp->getLHS();
4864 goto tryAgain;
4865 }
4866 }
Stephen Hines648c3692016-09-16 01:07:04 +00004867 }
George Burgess IVd273aab2016-09-22 00:00:26 +00004868
4869 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00004870 }
4871 case Stmt::UnaryOperatorClass: {
4872 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4873 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4874 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4875 llvm::APSInt IndexResult;
4876 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4877 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4878 E = ASE->getBase();
4879 goto tryAgain;
4880 }
4881 }
4882
4883 return SLCT_NotALiteral;
4884 }
Mike Stump11289f42009-09-09 15:08:12 +00004885
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004886 default:
Richard Smith55ce3522012-06-25 20:30:08 +00004887 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004888 }
4889}
4890
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004891Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00004892 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00004893 .Case("scanf", FST_Scanf)
4894 .Cases("printf", "printf0", FST_Printf)
4895 .Cases("NSString", "CFString", FST_NSString)
4896 .Case("strftime", FST_Strftime)
4897 .Case("strfmon", FST_Strfmon)
4898 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4899 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4900 .Case("os_trace", FST_OSLog)
4901 .Case("os_log", FST_OSLog)
4902 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004903}
4904
Jordan Rose3e0ec582012-07-19 18:10:23 +00004905/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00004906/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00004907/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004908bool Sema::CheckFormatArguments(const FormatAttr *Format,
4909 ArrayRef<const Expr *> Args,
4910 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004911 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004912 SourceLocation Loc, SourceRange Range,
4913 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00004914 FormatStringInfo FSI;
4915 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004916 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00004917 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00004918 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00004919 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004920}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00004921
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004922bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004923 bool HasVAListArg, unsigned format_idx,
4924 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004925 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004926 SourceLocation Loc, SourceRange Range,
4927 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004928 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004929 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004930 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00004931 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004932 }
Mike Stump11289f42009-09-09 15:08:12 +00004933
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004934 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004935
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004936 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00004937 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004938 // Dynamically generated format strings are difficult to
4939 // automatically vet at compile time. Requiring that format strings
4940 // are string literals: (1) permits the checking of format strings by
4941 // the compiler and thereby (2) can practically remove the source of
4942 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00004943
Mike Stump11289f42009-09-09 15:08:12 +00004944 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00004945 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00004946 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00004947 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004948 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00004949 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00004950 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4951 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004952 /*IsFunctionCall*/ true, CheckedVarArgs,
4953 UncoveredArg,
4954 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004955
4956 // Generate a diagnostic where an uncovered argument is detected.
4957 if (UncoveredArg.hasUncoveredArg()) {
4958 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4959 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4960 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4961 }
4962
Richard Smith55ce3522012-06-25 20:30:08 +00004963 if (CT != SLCT_NotALiteral)
4964 // Literal format string found, check done!
4965 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00004966
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004967 // Strftime is particular as it always uses a single 'time' argument,
4968 // so it is safe to pass a non-literal string.
4969 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00004970 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004971
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004972 // Do not emit diag when the string param is a macro expansion and the
4973 // format is either NSString or CFString. This is a hack to prevent
4974 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4975 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004976 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4977 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00004978 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004979
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004980 // If there are no arguments specified, warn with -Wformat-security, otherwise
4981 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004982 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00004983 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4984 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004985 switch (Type) {
4986 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004987 break;
4988 case FST_Kprintf:
4989 case FST_FreeBSDKPrintf:
4990 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00004991 Diag(FormatLoc, diag::note_format_security_fixit)
4992 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004993 break;
4994 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00004995 Diag(FormatLoc, diag::note_format_security_fixit)
4996 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004997 break;
4998 }
4999 } else {
5000 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005001 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005002 }
Richard Smith55ce3522012-06-25 20:30:08 +00005003 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005004}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005005
Ted Kremenekab278de2010-01-28 23:39:18 +00005006namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00005007class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5008protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00005009 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00005010 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00005011 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005012 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00005013 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00005014 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00005015 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00005016 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005017 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00005018 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00005019 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00005020 bool usesPositionalArgs;
5021 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005022 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00005023 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00005024 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005025 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005026
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005027public:
Stephen Hines648c3692016-09-16 01:07:04 +00005028 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005029 const Expr *origFormatExpr,
5030 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005031 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005032 ArrayRef<const Expr *> Args, unsigned formatIdx,
5033 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005034 llvm::SmallBitVector &CheckedVarArgs,
5035 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005036 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5037 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5038 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5039 usesPositionalArgs(false), atFirstArg(true),
5040 inFunctionCall(inFunctionCall), CallType(callType),
5041 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00005042 CoveredArgs.resize(numDataArgs);
5043 CoveredArgs.reset();
5044 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005045
Ted Kremenek019d2242010-01-29 01:50:07 +00005046 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005047
Ted Kremenek02087932010-07-16 02:11:22 +00005048 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005049 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005050
Jordan Rose92303592012-09-08 04:00:03 +00005051 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005052 const analyze_format_string::FormatSpecifier &FS,
5053 const analyze_format_string::ConversionSpecifier &CS,
5054 const char *startSpecifier, unsigned specifierLen,
5055 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00005056
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005057 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005058 const analyze_format_string::FormatSpecifier &FS,
5059 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005060
5061 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005062 const analyze_format_string::ConversionSpecifier &CS,
5063 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005064
Craig Toppere14c0f82014-03-12 04:55:44 +00005065 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005066
Craig Toppere14c0f82014-03-12 04:55:44 +00005067 void HandleInvalidPosition(const char *startSpecifier,
5068 unsigned specifierLen,
5069 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005070
Craig Toppere14c0f82014-03-12 04:55:44 +00005071 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005072
Craig Toppere14c0f82014-03-12 04:55:44 +00005073 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005074
Richard Trieu03cf7b72011-10-28 00:41:25 +00005075 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00005076 static void
5077 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5078 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5079 bool IsStringLocation, Range StringRange,
5080 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005081
Ted Kremenek02087932010-07-16 02:11:22 +00005082protected:
Ted Kremenekce815422010-07-19 21:25:57 +00005083 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5084 const char *startSpec,
5085 unsigned specifierLen,
5086 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005087
5088 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5089 const char *startSpec,
5090 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00005091
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005092 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00005093 CharSourceRange getSpecifierRange(const char *startSpecifier,
5094 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00005095 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005096
Ted Kremenek5739de72010-01-29 01:06:55 +00005097 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005098
5099 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5100 const analyze_format_string::ConversionSpecifier &CS,
5101 const char *startSpecifier, unsigned specifierLen,
5102 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005103
5104 template <typename Range>
5105 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5106 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005107 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00005108};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005109} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005110
Ted Kremenek02087932010-07-16 02:11:22 +00005111SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00005112 return OrigFormatExpr->getSourceRange();
5113}
5114
Ted Kremenek02087932010-07-16 02:11:22 +00005115CharSourceRange CheckFormatHandler::
5116getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00005117 SourceLocation Start = getLocationOfByte(startSpecifier);
5118 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5119
5120 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00005121 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00005122
5123 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005124}
5125
Ted Kremenek02087932010-07-16 02:11:22 +00005126SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00005127 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5128 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00005129}
5130
Ted Kremenek02087932010-07-16 02:11:22 +00005131void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5132 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00005133 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5134 getLocationOfByte(startSpecifier),
5135 /*IsStringLocation*/true,
5136 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00005137}
5138
Jordan Rose92303592012-09-08 04:00:03 +00005139void CheckFormatHandler::HandleInvalidLengthModifier(
5140 const analyze_format_string::FormatSpecifier &FS,
5141 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00005142 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00005143 using namespace analyze_format_string;
5144
5145 const LengthModifier &LM = FS.getLengthModifier();
5146 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5147
5148 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005149 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00005150 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005151 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005152 getLocationOfByte(LM.getStart()),
5153 /*IsStringLocation*/true,
5154 getSpecifierRange(startSpecifier, specifierLen));
5155
5156 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5157 << FixedLM->toString()
5158 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5159
5160 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005161 FixItHint Hint;
5162 if (DiagID == diag::warn_format_nonsensical_length)
5163 Hint = FixItHint::CreateRemoval(LMRange);
5164
5165 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005166 getLocationOfByte(LM.getStart()),
5167 /*IsStringLocation*/true,
5168 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00005169 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00005170 }
5171}
5172
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005173void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005174 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005175 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005176 using namespace analyze_format_string;
5177
5178 const LengthModifier &LM = FS.getLengthModifier();
5179 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5180
5181 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005182 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005183 if (FixedLM) {
5184 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5185 << LM.toString() << 0,
5186 getLocationOfByte(LM.getStart()),
5187 /*IsStringLocation*/true,
5188 getSpecifierRange(startSpecifier, specifierLen));
5189
5190 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5191 << FixedLM->toString()
5192 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5193
5194 } else {
5195 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5196 << LM.toString() << 0,
5197 getLocationOfByte(LM.getStart()),
5198 /*IsStringLocation*/true,
5199 getSpecifierRange(startSpecifier, specifierLen));
5200 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005201}
5202
5203void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5204 const analyze_format_string::ConversionSpecifier &CS,
5205 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005206 using namespace analyze_format_string;
5207
5208 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005209 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005210 if (FixedCS) {
5211 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5212 << CS.toString() << /*conversion specifier*/1,
5213 getLocationOfByte(CS.getStart()),
5214 /*IsStringLocation*/true,
5215 getSpecifierRange(startSpecifier, specifierLen));
5216
5217 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5218 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5219 << FixedCS->toString()
5220 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5221 } else {
5222 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5223 << CS.toString() << /*conversion specifier*/1,
5224 getLocationOfByte(CS.getStart()),
5225 /*IsStringLocation*/true,
5226 getSpecifierRange(startSpecifier, specifierLen));
5227 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005228}
5229
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005230void CheckFormatHandler::HandlePosition(const char *startPos,
5231 unsigned posLen) {
5232 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5233 getLocationOfByte(startPos),
5234 /*IsStringLocation*/true,
5235 getSpecifierRange(startPos, posLen));
5236}
5237
Ted Kremenekd1668192010-02-27 01:41:03 +00005238void
Ted Kremenek02087932010-07-16 02:11:22 +00005239CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5240 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005241 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5242 << (unsigned) p,
5243 getLocationOfByte(startPos), /*IsStringLocation*/true,
5244 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005245}
5246
Ted Kremenek02087932010-07-16 02:11:22 +00005247void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005248 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005249 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5250 getLocationOfByte(startPos),
5251 /*IsStringLocation*/true,
5252 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005253}
5254
Ted Kremenek02087932010-07-16 02:11:22 +00005255void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005256 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005257 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005258 EmitFormatDiagnostic(
5259 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5260 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5261 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005262 }
Ted Kremenek02087932010-07-16 02:11:22 +00005263}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005264
Jordan Rose58bbe422012-07-19 18:10:08 +00005265// Note that this may return NULL if there was an error parsing or building
5266// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005267const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005268 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005269}
5270
5271void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005272 // Does the number of data arguments exceed the number of
5273 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005274 if (!HasVAListArg) {
5275 // Find any arguments that weren't covered.
5276 CoveredArgs.flip();
5277 signed notCoveredArg = CoveredArgs.find_first();
5278 if (notCoveredArg >= 0) {
5279 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005280 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5281 } else {
5282 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005283 }
5284 }
5285}
5286
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005287void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5288 const Expr *ArgExpr) {
5289 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5290 "Invalid state");
5291
5292 if (!ArgExpr)
5293 return;
5294
5295 SourceLocation Loc = ArgExpr->getLocStart();
5296
5297 if (S.getSourceManager().isInSystemMacro(Loc))
5298 return;
5299
5300 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5301 for (auto E : DiagnosticExprs)
5302 PDiag << E->getSourceRange();
5303
5304 CheckFormatHandler::EmitFormatDiagnostic(
5305 S, IsFunctionCall, DiagnosticExprs[0],
5306 PDiag, Loc, /*IsStringLocation*/false,
5307 DiagnosticExprs[0]->getSourceRange());
5308}
5309
Ted Kremenekce815422010-07-19 21:25:57 +00005310bool
5311CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5312 SourceLocation Loc,
5313 const char *startSpec,
5314 unsigned specifierLen,
5315 const char *csStart,
5316 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005317 bool keepGoing = true;
5318 if (argIndex < NumDataArgs) {
5319 // Consider the argument coverered, even though the specifier doesn't
5320 // make sense.
5321 CoveredArgs.set(argIndex);
5322 }
5323 else {
5324 // If argIndex exceeds the number of data arguments we
5325 // don't issue a warning because that is just a cascade of warnings (and
5326 // they may have intended '%%' anyway). We don't want to continue processing
5327 // the format string after this point, however, as we will like just get
5328 // gibberish when trying to match arguments.
5329 keepGoing = false;
5330 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005331
5332 StringRef Specifier(csStart, csLen);
5333
5334 // If the specifier in non-printable, it could be the first byte of a UTF-8
5335 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5336 // hex value.
5337 std::string CodePointStr;
5338 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005339 llvm::UTF32 CodePoint;
5340 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5341 const llvm::UTF8 *E =
5342 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5343 llvm::ConversionResult Result =
5344 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005345
Justin Lebar90910552016-09-30 00:38:45 +00005346 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005347 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005348 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005349 }
5350
5351 llvm::raw_string_ostream OS(CodePointStr);
5352 if (CodePoint < 256)
5353 OS << "\\x" << llvm::format("%02x", CodePoint);
5354 else if (CodePoint <= 0xFFFF)
5355 OS << "\\u" << llvm::format("%04x", CodePoint);
5356 else
5357 OS << "\\U" << llvm::format("%08x", CodePoint);
5358 OS.flush();
5359 Specifier = CodePointStr;
5360 }
5361
5362 EmitFormatDiagnostic(
5363 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5364 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5365
Ted Kremenekce815422010-07-19 21:25:57 +00005366 return keepGoing;
5367}
5368
Richard Trieu03cf7b72011-10-28 00:41:25 +00005369void
5370CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5371 const char *startSpec,
5372 unsigned specifierLen) {
5373 EmitFormatDiagnostic(
5374 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5375 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5376}
5377
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005378bool
5379CheckFormatHandler::CheckNumArgs(
5380 const analyze_format_string::FormatSpecifier &FS,
5381 const analyze_format_string::ConversionSpecifier &CS,
5382 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5383
5384 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005385 PartialDiagnostic PDiag = FS.usesPositionalArg()
5386 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5387 << (argIndex+1) << NumDataArgs)
5388 : S.PDiag(diag::warn_printf_insufficient_data_args);
5389 EmitFormatDiagnostic(
5390 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5391 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005392
5393 // Since more arguments than conversion tokens are given, by extension
5394 // all arguments are covered, so mark this as so.
5395 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005396 return false;
5397 }
5398 return true;
5399}
5400
Richard Trieu03cf7b72011-10-28 00:41:25 +00005401template<typename Range>
5402void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5403 SourceLocation Loc,
5404 bool IsStringLocation,
5405 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005406 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005407 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005408 Loc, IsStringLocation, StringRange, FixIt);
5409}
5410
5411/// \brief If the format string is not within the funcion call, emit a note
5412/// so that the function call and string are in diagnostic messages.
5413///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005414/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005415/// call and only one diagnostic message will be produced. Otherwise, an
5416/// extra note will be emitted pointing to location of the format string.
5417///
5418/// \param ArgumentExpr the expression that is passed as the format string
5419/// argument in the function call. Used for getting locations when two
5420/// diagnostics are emitted.
5421///
5422/// \param PDiag the callee should already have provided any strings for the
5423/// diagnostic message. This function only adds locations and fixits
5424/// to diagnostics.
5425///
5426/// \param Loc primary location for diagnostic. If two diagnostics are
5427/// required, one will be at Loc and a new SourceLocation will be created for
5428/// the other one.
5429///
5430/// \param IsStringLocation if true, Loc points to the format string should be
5431/// used for the note. Otherwise, Loc points to the argument list and will
5432/// be used with PDiag.
5433///
5434/// \param StringRange some or all of the string to highlight. This is
5435/// templated so it can accept either a CharSourceRange or a SourceRange.
5436///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005437/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005438template <typename Range>
5439void CheckFormatHandler::EmitFormatDiagnostic(
5440 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5441 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5442 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005443 if (InFunctionCall) {
5444 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5445 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005446 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00005447 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005448 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5449 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00005450
5451 const Sema::SemaDiagnosticBuilder &Note =
5452 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5453 diag::note_format_string_defined);
5454
5455 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005456 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005457 }
5458}
5459
Ted Kremenek02087932010-07-16 02:11:22 +00005460//===--- CHECK: Printf format string checking ------------------------------===//
5461
5462namespace {
5463class CheckPrintfHandler : public CheckFormatHandler {
5464public:
Stephen Hines648c3692016-09-16 01:07:04 +00005465 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005466 const Expr *origFormatExpr,
5467 const Sema::FormatStringType type, unsigned firstDataArg,
5468 unsigned numDataArgs, bool isObjC, const char *beg,
5469 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005470 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005471 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005472 llvm::SmallBitVector &CheckedVarArgs,
5473 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005474 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5475 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5476 inFunctionCall, CallType, CheckedVarArgs,
5477 UncoveredArg) {}
5478
5479 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5480
5481 /// Returns true if '%@' specifiers are allowed in the format string.
5482 bool allowsObjCArg() const {
5483 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5484 FSType == Sema::FST_OSTrace;
5485 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00005486
Ted Kremenek02087932010-07-16 02:11:22 +00005487 bool HandleInvalidPrintfConversionSpecifier(
5488 const analyze_printf::PrintfSpecifier &FS,
5489 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005490 unsigned specifierLen) override;
5491
Ted Kremenek02087932010-07-16 02:11:22 +00005492 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5493 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005494 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005495 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5496 const char *StartSpecifier,
5497 unsigned SpecifierLen,
5498 const Expr *E);
5499
Ted Kremenek02087932010-07-16 02:11:22 +00005500 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5501 const char *startSpecifier, unsigned specifierLen);
5502 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5503 const analyze_printf::OptionalAmount &Amt,
5504 unsigned type,
5505 const char *startSpecifier, unsigned specifierLen);
5506 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5507 const analyze_printf::OptionalFlag &flag,
5508 const char *startSpecifier, unsigned specifierLen);
5509 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5510 const analyze_printf::OptionalFlag &ignoredFlag,
5511 const analyze_printf::OptionalFlag &flag,
5512 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005513 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00005514 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00005515
5516 void HandleEmptyObjCModifierFlag(const char *startFlag,
5517 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005518
Ted Kremenek2b417712015-07-02 05:39:16 +00005519 void HandleInvalidObjCModifierFlag(const char *startFlag,
5520 unsigned flagLen) override;
5521
5522 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5523 const char *flagsEnd,
5524 const char *conversionPosition)
5525 override;
5526};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005527} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00005528
5529bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5530 const analyze_printf::PrintfSpecifier &FS,
5531 const char *startSpecifier,
5532 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005533 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005534 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005535
Ted Kremenekce815422010-07-19 21:25:57 +00005536 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5537 getLocationOfByte(CS.getStart()),
5538 startSpecifier, specifierLen,
5539 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00005540}
5541
Ted Kremenek02087932010-07-16 02:11:22 +00005542bool CheckPrintfHandler::HandleAmount(
5543 const analyze_format_string::OptionalAmount &Amt,
5544 unsigned k, const char *startSpecifier,
5545 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005546 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005547 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00005548 unsigned argIndex = Amt.getArgIndex();
5549 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005550 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5551 << k,
5552 getLocationOfByte(Amt.getStart()),
5553 /*IsStringLocation*/true,
5554 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005555 // Don't do any more checking. We will just emit
5556 // spurious errors.
5557 return false;
5558 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005559
Ted Kremenek5739de72010-01-29 01:06:55 +00005560 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00005561 // Although not in conformance with C99, we also allow the argument to be
5562 // an 'unsigned int' as that is a reasonably safe case. GCC also
5563 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00005564 CoveredArgs.set(argIndex);
5565 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005566 if (!Arg)
5567 return false;
5568
Ted Kremenek5739de72010-01-29 01:06:55 +00005569 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005570
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005571 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5572 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005573
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005574 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005575 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005576 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00005577 << T << Arg->getSourceRange(),
5578 getLocationOfByte(Amt.getStart()),
5579 /*IsStringLocation*/true,
5580 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005581 // Don't do any more checking. We will just emit
5582 // spurious errors.
5583 return false;
5584 }
5585 }
5586 }
5587 return true;
5588}
Ted Kremenek5739de72010-01-29 01:06:55 +00005589
Tom Careb49ec692010-06-17 19:00:27 +00005590void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00005591 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005592 const analyze_printf::OptionalAmount &Amt,
5593 unsigned type,
5594 const char *startSpecifier,
5595 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005596 const analyze_printf::PrintfConversionSpecifier &CS =
5597 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00005598
Richard Trieu03cf7b72011-10-28 00:41:25 +00005599 FixItHint fixit =
5600 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5601 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5602 Amt.getConstantLength()))
5603 : FixItHint();
5604
5605 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5606 << type << CS.toString(),
5607 getLocationOfByte(Amt.getStart()),
5608 /*IsStringLocation*/true,
5609 getSpecifierRange(startSpecifier, specifierLen),
5610 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00005611}
5612
Ted Kremenek02087932010-07-16 02:11:22 +00005613void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005614 const analyze_printf::OptionalFlag &flag,
5615 const char *startSpecifier,
5616 unsigned specifierLen) {
5617 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005618 const analyze_printf::PrintfConversionSpecifier &CS =
5619 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00005620 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5621 << flag.toString() << CS.toString(),
5622 getLocationOfByte(flag.getPosition()),
5623 /*IsStringLocation*/true,
5624 getSpecifierRange(startSpecifier, specifierLen),
5625 FixItHint::CreateRemoval(
5626 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005627}
5628
5629void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00005630 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005631 const analyze_printf::OptionalFlag &ignoredFlag,
5632 const analyze_printf::OptionalFlag &flag,
5633 const char *startSpecifier,
5634 unsigned specifierLen) {
5635 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005636 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5637 << ignoredFlag.toString() << flag.toString(),
5638 getLocationOfByte(ignoredFlag.getPosition()),
5639 /*IsStringLocation*/true,
5640 getSpecifierRange(startSpecifier, specifierLen),
5641 FixItHint::CreateRemoval(
5642 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005643}
5644
Ted Kremenek2b417712015-07-02 05:39:16 +00005645// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5646// bool IsStringLocation, Range StringRange,
5647// ArrayRef<FixItHint> Fixit = None);
5648
5649void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5650 unsigned flagLen) {
5651 // Warn about an empty flag.
5652 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5653 getLocationOfByte(startFlag),
5654 /*IsStringLocation*/true,
5655 getSpecifierRange(startFlag, flagLen));
5656}
5657
5658void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5659 unsigned flagLen) {
5660 // Warn about an invalid flag.
5661 auto Range = getSpecifierRange(startFlag, flagLen);
5662 StringRef flag(startFlag, flagLen);
5663 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5664 getLocationOfByte(startFlag),
5665 /*IsStringLocation*/true,
5666 Range, FixItHint::CreateRemoval(Range));
5667}
5668
5669void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5670 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5671 // Warn about using '[...]' without a '@' conversion.
5672 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5673 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5674 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5675 getLocationOfByte(conversionPosition),
5676 /*IsStringLocation*/true,
5677 Range, FixItHint::CreateRemoval(Range));
5678}
5679
Richard Smith55ce3522012-06-25 20:30:08 +00005680// Determines if the specified is a C++ class or struct containing
5681// a member with the specified name and kind (e.g. a CXXMethodDecl named
5682// "c_str()").
5683template<typename MemberKind>
5684static llvm::SmallPtrSet<MemberKind*, 1>
5685CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5686 const RecordType *RT = Ty->getAs<RecordType>();
5687 llvm::SmallPtrSet<MemberKind*, 1> Results;
5688
5689 if (!RT)
5690 return Results;
5691 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005692 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005693 return Results;
5694
Alp Tokerb6cc5922014-05-03 03:45:55 +00005695 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005696 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005697 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005698
5699 // We just need to include all members of the right kind turned up by the
5700 // filter, at this point.
5701 if (S.LookupQualifiedName(R, RT->getDecl()))
5702 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5703 NamedDecl *decl = (*I)->getUnderlyingDecl();
5704 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5705 Results.insert(FK);
5706 }
5707 return Results;
5708}
5709
Richard Smith2868a732014-02-28 01:36:39 +00005710/// Check if we could call '.c_str()' on an object.
5711///
5712/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5713/// allow the call, or if it would be ambiguous).
5714bool Sema::hasCStrMethod(const Expr *E) {
5715 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5716 MethodSet Results =
5717 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5718 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5719 MI != ME; ++MI)
5720 if ((*MI)->getMinRequiredArguments() == 0)
5721 return true;
5722 return false;
5723}
5724
Richard Smith55ce3522012-06-25 20:30:08 +00005725// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005726// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00005727// Returns true when a c_str() conversion method is found.
5728bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00005729 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00005730 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5731
5732 MethodSet Results =
5733 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5734
5735 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5736 MI != ME; ++MI) {
5737 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00005738 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00005739 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00005740 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00005741 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00005742 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5743 << "c_str()"
5744 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5745 return true;
5746 }
5747 }
5748
5749 return false;
5750}
5751
Ted Kremenekab278de2010-01-28 23:39:18 +00005752bool
Ted Kremenek02087932010-07-16 02:11:22 +00005753CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00005754 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00005755 const char *startSpecifier,
5756 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005757 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00005758 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005759 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00005760
Ted Kremenek6cd69422010-07-19 22:01:06 +00005761 if (FS.consumesDataArgument()) {
5762 if (atFirstArg) {
5763 atFirstArg = false;
5764 usesPositionalArgs = FS.usesPositionalArg();
5765 }
5766 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005767 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5768 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005769 return false;
5770 }
Ted Kremenek5739de72010-01-29 01:06:55 +00005771 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005772
Ted Kremenekd1668192010-02-27 01:41:03 +00005773 // First check if the field width, precision, and conversion specifier
5774 // have matching data arguments.
5775 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5776 startSpecifier, specifierLen)) {
5777 return false;
5778 }
5779
5780 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5781 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005782 return false;
5783 }
5784
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005785 if (!CS.consumesDataArgument()) {
5786 // FIXME: Technically specifying a precision or field width here
5787 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00005788 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005789 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005790
Ted Kremenek4a49d982010-02-26 19:18:41 +00005791 // Consume the argument.
5792 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00005793 if (argIndex < NumDataArgs) {
5794 // The check to see if the argIndex is valid will come later.
5795 // We set the bit here because we may exit early from this
5796 // function if we encounter some other error.
5797 CoveredArgs.set(argIndex);
5798 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00005799
Dimitry Andric6b5ed342015-02-19 22:32:33 +00005800 // FreeBSD kernel extensions.
5801 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5802 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5803 // We need at least two arguments.
5804 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5805 return false;
5806
5807 // Claim the second argument.
5808 CoveredArgs.set(argIndex + 1);
5809
5810 // Type check the first argument (int for %b, pointer for %D)
5811 const Expr *Ex = getDataArg(argIndex);
5812 const analyze_printf::ArgType &AT =
5813 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5814 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5815 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5816 EmitFormatDiagnostic(
5817 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5818 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5819 << false << Ex->getSourceRange(),
5820 Ex->getLocStart(), /*IsStringLocation*/false,
5821 getSpecifierRange(startSpecifier, specifierLen));
5822
5823 // Type check the second argument (char * for both %b and %D)
5824 Ex = getDataArg(argIndex + 1);
5825 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5826 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5827 EmitFormatDiagnostic(
5828 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5829 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5830 << false << Ex->getSourceRange(),
5831 Ex->getLocStart(), /*IsStringLocation*/false,
5832 getSpecifierRange(startSpecifier, specifierLen));
5833
5834 return true;
5835 }
5836
Ted Kremenek4a49d982010-02-26 19:18:41 +00005837 // Check for using an Objective-C specific conversion specifier
5838 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00005839 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00005840 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5841 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00005842 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005843
Mehdi Amini06d367c2016-10-24 20:39:34 +00005844 // %P can only be used with os_log.
5845 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
5846 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5847 specifierLen);
5848 }
5849
5850 // %n is not allowed with os_log.
5851 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
5852 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
5853 getLocationOfByte(CS.getStart()),
5854 /*IsStringLocation*/ false,
5855 getSpecifierRange(startSpecifier, specifierLen));
5856
5857 return true;
5858 }
5859
5860 // Only scalars are allowed for os_trace.
5861 if (FSType == Sema::FST_OSTrace &&
5862 (CS.getKind() == ConversionSpecifier::PArg ||
5863 CS.getKind() == ConversionSpecifier::sArg ||
5864 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
5865 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5866 specifierLen);
5867 }
5868
5869 // Check for use of public/private annotation outside of os_log().
5870 if (FSType != Sema::FST_OSLog) {
5871 if (FS.isPublic().isSet()) {
5872 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5873 << "public",
5874 getLocationOfByte(FS.isPublic().getPosition()),
5875 /*IsStringLocation*/ false,
5876 getSpecifierRange(startSpecifier, specifierLen));
5877 }
5878 if (FS.isPrivate().isSet()) {
5879 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5880 << "private",
5881 getLocationOfByte(FS.isPrivate().getPosition()),
5882 /*IsStringLocation*/ false,
5883 getSpecifierRange(startSpecifier, specifierLen));
5884 }
5885 }
5886
Tom Careb49ec692010-06-17 19:00:27 +00005887 // Check for invalid use of field width
5888 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00005889 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00005890 startSpecifier, specifierLen);
5891 }
5892
5893 // Check for invalid use of precision
5894 if (!FS.hasValidPrecision()) {
5895 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5896 startSpecifier, specifierLen);
5897 }
5898
Mehdi Amini06d367c2016-10-24 20:39:34 +00005899 // Precision is mandatory for %P specifier.
5900 if (CS.getKind() == ConversionSpecifier::PArg &&
5901 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
5902 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
5903 getLocationOfByte(startSpecifier),
5904 /*IsStringLocation*/ false,
5905 getSpecifierRange(startSpecifier, specifierLen));
5906 }
5907
Tom Careb49ec692010-06-17 19:00:27 +00005908 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00005909 if (!FS.hasValidThousandsGroupingPrefix())
5910 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005911 if (!FS.hasValidLeadingZeros())
5912 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5913 if (!FS.hasValidPlusPrefix())
5914 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00005915 if (!FS.hasValidSpacePrefix())
5916 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005917 if (!FS.hasValidAlternativeForm())
5918 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5919 if (!FS.hasValidLeftJustified())
5920 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5921
5922 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00005923 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5924 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5925 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005926 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5927 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5928 startSpecifier, specifierLen);
5929
5930 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005931 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005932 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5933 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005934 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005935 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005936 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005937 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5938 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00005939
Jordan Rose92303592012-09-08 04:00:03 +00005940 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5941 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5942
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005943 // The remaining checks depend on the data arguments.
5944 if (HasVAListArg)
5945 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005946
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005947 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005948 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005949
Jordan Rose58bbe422012-07-19 18:10:08 +00005950 const Expr *Arg = getDataArg(argIndex);
5951 if (!Arg)
5952 return true;
5953
5954 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00005955}
5956
Jordan Roseaee34382012-09-05 22:56:26 +00005957static bool requiresParensToAddCast(const Expr *E) {
5958 // FIXME: We should have a general way to reason about operator
5959 // precedence and whether parens are actually needed here.
5960 // Take care of a few common cases where they aren't.
5961 const Expr *Inside = E->IgnoreImpCasts();
5962 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5963 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5964
5965 switch (Inside->getStmtClass()) {
5966 case Stmt::ArraySubscriptExprClass:
5967 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005968 case Stmt::CharacterLiteralClass:
5969 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005970 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005971 case Stmt::FloatingLiteralClass:
5972 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005973 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005974 case Stmt::ObjCArrayLiteralClass:
5975 case Stmt::ObjCBoolLiteralExprClass:
5976 case Stmt::ObjCBoxedExprClass:
5977 case Stmt::ObjCDictionaryLiteralClass:
5978 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005979 case Stmt::ObjCIvarRefExprClass:
5980 case Stmt::ObjCMessageExprClass:
5981 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005982 case Stmt::ObjCStringLiteralClass:
5983 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005984 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005985 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005986 case Stmt::UnaryOperatorClass:
5987 return false;
5988 default:
5989 return true;
5990 }
5991}
5992
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005993static std::pair<QualType, StringRef>
5994shouldNotPrintDirectly(const ASTContext &Context,
5995 QualType IntendedTy,
5996 const Expr *E) {
5997 // Use a 'while' to peel off layers of typedefs.
5998 QualType TyTy = IntendedTy;
5999 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6000 StringRef Name = UserTy->getDecl()->getName();
6001 QualType CastTy = llvm::StringSwitch<QualType>(Name)
6002 .Case("NSInteger", Context.LongTy)
6003 .Case("NSUInteger", Context.UnsignedLongTy)
6004 .Case("SInt32", Context.IntTy)
6005 .Case("UInt32", Context.UnsignedIntTy)
6006 .Default(QualType());
6007
6008 if (!CastTy.isNull())
6009 return std::make_pair(CastTy, Name);
6010
6011 TyTy = UserTy->desugar();
6012 }
6013
6014 // Strip parens if necessary.
6015 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6016 return shouldNotPrintDirectly(Context,
6017 PE->getSubExpr()->getType(),
6018 PE->getSubExpr());
6019
6020 // If this is a conditional expression, then its result type is constructed
6021 // via usual arithmetic conversions and thus there might be no necessary
6022 // typedef sugar there. Recurse to operands to check for NSInteger &
6023 // Co. usage condition.
6024 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6025 QualType TrueTy, FalseTy;
6026 StringRef TrueName, FalseName;
6027
6028 std::tie(TrueTy, TrueName) =
6029 shouldNotPrintDirectly(Context,
6030 CO->getTrueExpr()->getType(),
6031 CO->getTrueExpr());
6032 std::tie(FalseTy, FalseName) =
6033 shouldNotPrintDirectly(Context,
6034 CO->getFalseExpr()->getType(),
6035 CO->getFalseExpr());
6036
6037 if (TrueTy == FalseTy)
6038 return std::make_pair(TrueTy, TrueName);
6039 else if (TrueTy.isNull())
6040 return std::make_pair(FalseTy, FalseName);
6041 else if (FalseTy.isNull())
6042 return std::make_pair(TrueTy, TrueName);
6043 }
6044
6045 return std::make_pair(QualType(), StringRef());
6046}
6047
Richard Smith55ce3522012-06-25 20:30:08 +00006048bool
6049CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6050 const char *StartSpecifier,
6051 unsigned SpecifierLen,
6052 const Expr *E) {
6053 using namespace analyze_format_string;
6054 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006055 // Now type check the data expression that matches the
6056 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006057 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00006058 if (!AT.isValid())
6059 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00006060
Jordan Rose598ec092012-12-05 18:44:40 +00006061 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00006062 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6063 ExprTy = TET->getUnderlyingExpr()->getType();
6064 }
6065
Seth Cantrellb4802962015-03-04 03:12:10 +00006066 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6067
6068 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00006069 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006070 }
Jordan Rose98709982012-06-04 22:48:57 +00006071
Jordan Rose22b74712012-09-05 22:56:19 +00006072 // Look through argument promotions for our error message's reported type.
6073 // This includes the integral and floating promotions, but excludes array
6074 // and function pointer decay; seeing that an argument intended to be a
6075 // string has type 'char [6]' is probably more confusing than 'char *'.
6076 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6077 if (ICE->getCastKind() == CK_IntegralCast ||
6078 ICE->getCastKind() == CK_FloatingCast) {
6079 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006080 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006081
6082 // Check if we didn't match because of an implicit cast from a 'char'
6083 // or 'short' to an 'int'. This is done because printf is a varargs
6084 // function.
6085 if (ICE->getType() == S.Context.IntTy ||
6086 ICE->getType() == S.Context.UnsignedIntTy) {
6087 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006088 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006089 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006090 }
Jordan Rose98709982012-06-04 22:48:57 +00006091 }
Jordan Rose598ec092012-12-05 18:44:40 +00006092 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6093 // Special case for 'a', which has type 'int' in C.
6094 // Note, however, that we do /not/ want to treat multibyte constants like
6095 // 'MooV' as characters! This form is deprecated but still exists.
6096 if (ExprTy == S.Context.IntTy)
6097 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6098 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006099 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006100
Jordan Rosebc53ed12014-05-31 04:12:14 +00006101 // Look through enums to their underlying type.
6102 bool IsEnum = false;
6103 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6104 ExprTy = EnumTy->getDecl()->getIntegerType();
6105 IsEnum = true;
6106 }
6107
Jordan Rose0e5badd2012-12-05 18:44:49 +00006108 // %C in an Objective-C context prints a unichar, not a wchar_t.
6109 // If the argument is an integer of some kind, believe the %C and suggest
6110 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006111 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006112 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006113 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6114 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6115 !ExprTy->isCharType()) {
6116 // 'unichar' is defined as a typedef of unsigned short, but we should
6117 // prefer using the typedef if it is visible.
6118 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006119
6120 // While we are here, check if the value is an IntegerLiteral that happens
6121 // to be within the valid range.
6122 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6123 const llvm::APInt &V = IL->getValue();
6124 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6125 return true;
6126 }
6127
Jordan Rose0e5badd2012-12-05 18:44:49 +00006128 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6129 Sema::LookupOrdinaryName);
6130 if (S.LookupName(Result, S.getCurScope())) {
6131 NamedDecl *ND = Result.getFoundDecl();
6132 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6133 if (TD->getUnderlyingType() == IntendedTy)
6134 IntendedTy = S.Context.getTypedefType(TD);
6135 }
6136 }
6137 }
6138
6139 // Special-case some of Darwin's platform-independence types by suggesting
6140 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006141 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006142 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006143 QualType CastTy;
6144 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6145 if (!CastTy.isNull()) {
6146 IntendedTy = CastTy;
6147 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006148 }
6149 }
6150
Jordan Rose22b74712012-09-05 22:56:19 +00006151 // We may be able to offer a FixItHint if it is a supported type.
6152 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006153 bool success =
6154 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006155
Jordan Rose22b74712012-09-05 22:56:19 +00006156 if (success) {
6157 // Get the fix string from the fixed format specifier
6158 SmallString<16> buf;
6159 llvm::raw_svector_ostream os(buf);
6160 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006161
Jordan Roseaee34382012-09-05 22:56:26 +00006162 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6163
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006164 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00006165 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6166 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6167 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6168 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00006169 // In this case, the specifier is wrong and should be changed to match
6170 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006171 EmitFormatDiagnostic(S.PDiag(diag)
6172 << AT.getRepresentativeTypeName(S.Context)
6173 << IntendedTy << IsEnum << E->getSourceRange(),
6174 E->getLocStart(),
6175 /*IsStringLocation*/ false, SpecRange,
6176 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006177 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006178 // The canonical type for formatting this value is different from the
6179 // actual type of the expression. (This occurs, for example, with Darwin's
6180 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6181 // should be printed as 'long' for 64-bit compatibility.)
6182 // Rather than emitting a normal format/argument mismatch, we want to
6183 // add a cast to the recommended type (and correct the format string
6184 // if necessary).
6185 SmallString<16> CastBuf;
6186 llvm::raw_svector_ostream CastFix(CastBuf);
6187 CastFix << "(";
6188 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6189 CastFix << ")";
6190
6191 SmallVector<FixItHint,4> Hints;
6192 if (!AT.matchesType(S.Context, IntendedTy))
6193 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6194
6195 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6196 // If there's already a cast present, just replace it.
6197 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6198 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6199
6200 } else if (!requiresParensToAddCast(E)) {
6201 // If the expression has high enough precedence,
6202 // just write the C-style cast.
6203 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6204 CastFix.str()));
6205 } else {
6206 // Otherwise, add parens around the expression as well as the cast.
6207 CastFix << "(";
6208 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6209 CastFix.str()));
6210
Alp Tokerb6cc5922014-05-03 03:45:55 +00006211 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006212 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6213 }
6214
Jordan Rose0e5badd2012-12-05 18:44:49 +00006215 if (ShouldNotPrintDirectly) {
6216 // The expression has a type that should not be printed directly.
6217 // We extract the name from the typedef because we don't want to show
6218 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006219 StringRef Name;
6220 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6221 Name = TypedefTy->getDecl()->getName();
6222 else
6223 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006224 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006225 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006226 << E->getSourceRange(),
6227 E->getLocStart(), /*IsStringLocation=*/false,
6228 SpecRange, Hints);
6229 } else {
6230 // In this case, the expression could be printed using a different
6231 // specifier, but we've decided that the specifier is probably correct
6232 // and we should cast instead. Just use the normal warning message.
6233 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006234 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6235 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006236 << E->getSourceRange(),
6237 E->getLocStart(), /*IsStringLocation*/false,
6238 SpecRange, Hints);
6239 }
Jordan Roseaee34382012-09-05 22:56:26 +00006240 }
Jordan Rose22b74712012-09-05 22:56:19 +00006241 } else {
6242 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6243 SpecifierLen);
6244 // Since the warning for passing non-POD types to variadic functions
6245 // was deferred until now, we emit a warning for non-POD
6246 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006247 switch (S.isValidVarArgType(ExprTy)) {
6248 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006249 case Sema::VAK_ValidInCXX11: {
6250 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6251 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6252 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6253 }
Richard Smithd7293d72013-08-05 18:49:43 +00006254
Seth Cantrellb4802962015-03-04 03:12:10 +00006255 EmitFormatDiagnostic(
6256 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6257 << IsEnum << CSR << E->getSourceRange(),
6258 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6259 break;
6260 }
Richard Smithd7293d72013-08-05 18:49:43 +00006261 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006262 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006263 EmitFormatDiagnostic(
6264 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006265 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006266 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006267 << CallType
6268 << AT.getRepresentativeTypeName(S.Context)
6269 << CSR
6270 << E->getSourceRange(),
6271 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006272 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006273 break;
6274
6275 case Sema::VAK_Invalid:
6276 if (ExprTy->isObjCObjectType())
6277 EmitFormatDiagnostic(
6278 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6279 << S.getLangOpts().CPlusPlus11
6280 << ExprTy
6281 << CallType
6282 << AT.getRepresentativeTypeName(S.Context)
6283 << CSR
6284 << E->getSourceRange(),
6285 E->getLocStart(), /*IsStringLocation*/false, CSR);
6286 else
6287 // FIXME: If this is an initializer list, suggest removing the braces
6288 // or inserting a cast to the target type.
6289 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6290 << isa<InitListExpr>(E) << ExprTy << CallType
6291 << AT.getRepresentativeTypeName(S.Context)
6292 << E->getSourceRange();
6293 break;
6294 }
6295
6296 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6297 "format string specifier index out of range");
6298 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006299 }
6300
Ted Kremenekab278de2010-01-28 23:39:18 +00006301 return true;
6302}
6303
Ted Kremenek02087932010-07-16 02:11:22 +00006304//===--- CHECK: Scanf format string checking ------------------------------===//
6305
6306namespace {
6307class CheckScanfHandler : public CheckFormatHandler {
6308public:
Stephen Hines648c3692016-09-16 01:07:04 +00006309 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006310 const Expr *origFormatExpr, Sema::FormatStringType type,
6311 unsigned firstDataArg, unsigned numDataArgs,
6312 const char *beg, bool hasVAListArg,
6313 ArrayRef<const Expr *> Args, unsigned formatIdx,
6314 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006315 llvm::SmallBitVector &CheckedVarArgs,
6316 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006317 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6318 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6319 inFunctionCall, CallType, CheckedVarArgs,
6320 UncoveredArg) {}
6321
Ted Kremenek02087932010-07-16 02:11:22 +00006322 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6323 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006324 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006325
6326 bool HandleInvalidScanfConversionSpecifier(
6327 const analyze_scanf::ScanfSpecifier &FS,
6328 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006329 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006330
Craig Toppere14c0f82014-03-12 04:55:44 +00006331 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006332};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006333} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006334
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006335void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6336 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006337 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6338 getLocationOfByte(end), /*IsStringLocation*/true,
6339 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006340}
6341
Ted Kremenekce815422010-07-19 21:25:57 +00006342bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6343 const analyze_scanf::ScanfSpecifier &FS,
6344 const char *startSpecifier,
6345 unsigned specifierLen) {
6346
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006347 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006348 FS.getConversionSpecifier();
6349
6350 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6351 getLocationOfByte(CS.getStart()),
6352 startSpecifier, specifierLen,
6353 CS.getStart(), CS.getLength());
6354}
6355
Ted Kremenek02087932010-07-16 02:11:22 +00006356bool CheckScanfHandler::HandleScanfSpecifier(
6357 const analyze_scanf::ScanfSpecifier &FS,
6358 const char *startSpecifier,
6359 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006360 using namespace analyze_scanf;
6361 using namespace analyze_format_string;
6362
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006363 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006364
Ted Kremenek6cd69422010-07-19 22:01:06 +00006365 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6366 // be used to decide if we are using positional arguments consistently.
6367 if (FS.consumesDataArgument()) {
6368 if (atFirstArg) {
6369 atFirstArg = false;
6370 usesPositionalArgs = FS.usesPositionalArg();
6371 }
6372 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006373 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6374 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006375 return false;
6376 }
Ted Kremenek02087932010-07-16 02:11:22 +00006377 }
6378
6379 // Check if the field with is non-zero.
6380 const OptionalAmount &Amt = FS.getFieldWidth();
6381 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6382 if (Amt.getConstantAmount() == 0) {
6383 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6384 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006385 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6386 getLocationOfByte(Amt.getStart()),
6387 /*IsStringLocation*/true, R,
6388 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006389 }
6390 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006391
Ted Kremenek02087932010-07-16 02:11:22 +00006392 if (!FS.consumesDataArgument()) {
6393 // FIXME: Technically specifying a precision or field width here
6394 // makes no sense. Worth issuing a warning at some point.
6395 return true;
6396 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006397
Ted Kremenek02087932010-07-16 02:11:22 +00006398 // Consume the argument.
6399 unsigned argIndex = FS.getArgIndex();
6400 if (argIndex < NumDataArgs) {
6401 // The check to see if the argIndex is valid will come later.
6402 // We set the bit here because we may exit early from this
6403 // function if we encounter some other error.
6404 CoveredArgs.set(argIndex);
6405 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006406
Ted Kremenek4407ea42010-07-20 20:04:47 +00006407 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006408 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006409 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6410 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006411 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006412 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006413 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006414 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6415 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006416
Jordan Rose92303592012-09-08 04:00:03 +00006417 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6418 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6419
Ted Kremenek02087932010-07-16 02:11:22 +00006420 // The remaining checks depend on the data arguments.
6421 if (HasVAListArg)
6422 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006423
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006424 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006425 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006426
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006427 // Check that the argument type matches the format specifier.
6428 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006429 if (!Ex)
6430 return true;
6431
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006432 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006433
6434 if (!AT.isValid()) {
6435 return true;
6436 }
6437
Seth Cantrellb4802962015-03-04 03:12:10 +00006438 analyze_format_string::ArgType::MatchKind match =
6439 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006440 if (match == analyze_format_string::ArgType::Match) {
6441 return true;
6442 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006443
Seth Cantrell79340072015-03-04 05:58:08 +00006444 ScanfSpecifier fixedFS = FS;
6445 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6446 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006447
Seth Cantrell79340072015-03-04 05:58:08 +00006448 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6449 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6450 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6451 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006452
Seth Cantrell79340072015-03-04 05:58:08 +00006453 if (success) {
6454 // Get the fix string from the fixed format specifier.
6455 SmallString<128> buf;
6456 llvm::raw_svector_ostream os(buf);
6457 fixedFS.toString(os);
6458
6459 EmitFormatDiagnostic(
6460 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6461 << Ex->getType() << false << Ex->getSourceRange(),
6462 Ex->getLocStart(),
6463 /*IsStringLocation*/ false,
6464 getSpecifierRange(startSpecifier, specifierLen),
6465 FixItHint::CreateReplacement(
6466 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6467 } else {
6468 EmitFormatDiagnostic(S.PDiag(diag)
6469 << AT.getRepresentativeTypeName(S.Context)
6470 << Ex->getType() << false << Ex->getSourceRange(),
6471 Ex->getLocStart(),
6472 /*IsStringLocation*/ false,
6473 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006474 }
6475
Ted Kremenek02087932010-07-16 02:11:22 +00006476 return true;
6477}
6478
Stephen Hines648c3692016-09-16 01:07:04 +00006479static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006480 const Expr *OrigFormatExpr,
6481 ArrayRef<const Expr *> Args,
6482 bool HasVAListArg, unsigned format_idx,
6483 unsigned firstDataArg,
6484 Sema::FormatStringType Type,
6485 bool inFunctionCall,
6486 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006487 llvm::SmallBitVector &CheckedVarArgs,
6488 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00006489 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00006490 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006491 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006492 S, inFunctionCall, Args[format_idx],
6493 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006494 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006495 return;
6496 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006497
Ted Kremenekab278de2010-01-28 23:39:18 +00006498 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006499 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00006500 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006501 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006502 const ConstantArrayType *T =
6503 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006504 assert(T && "String literal not of constant array type!");
6505 size_t TypeSize = T->getSize().getZExtValue();
6506 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006507 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006508
6509 // Emit a warning if the string literal is truncated and does not contain an
6510 // embedded null character.
6511 if (TypeSize <= StrRef.size() &&
6512 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6513 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006514 S, inFunctionCall, Args[format_idx],
6515 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006516 FExpr->getLocStart(),
6517 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6518 return;
6519 }
6520
Ted Kremenekab278de2010-01-28 23:39:18 +00006521 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006522 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006523 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006524 S, inFunctionCall, Args[format_idx],
6525 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006526 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006527 return;
6528 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006529
6530 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00006531 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6532 Type == Sema::FST_OSTrace) {
6533 CheckPrintfHandler H(
6534 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6535 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6536 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6537 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006538
Hans Wennborg23926bd2011-12-15 10:25:47 +00006539 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006540 S.getLangOpts(),
6541 S.Context.getTargetInfo(),
6542 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006543 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006544 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00006545 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6546 numDataArgs, Str, HasVAListArg, Args, format_idx,
6547 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006548
Hans Wennborg23926bd2011-12-15 10:25:47 +00006549 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006550 S.getLangOpts(),
6551 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006552 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006553 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006554}
6555
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006556bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6557 // Str - The format string. NOTE: this is NOT null-terminated!
6558 StringRef StrRef = FExpr->getString();
6559 const char *Str = StrRef.data();
6560 // Account for cases where the string literal is truncated in a declaration.
6561 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6562 assert(T && "String literal not of constant array type!");
6563 size_t TypeSize = T->getSize().getZExtValue();
6564 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6565 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6566 getLangOpts(),
6567 Context.getTargetInfo());
6568}
6569
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006570//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6571
6572// Returns the related absolute value function that is larger, of 0 if one
6573// does not exist.
6574static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6575 switch (AbsFunction) {
6576 default:
6577 return 0;
6578
6579 case Builtin::BI__builtin_abs:
6580 return Builtin::BI__builtin_labs;
6581 case Builtin::BI__builtin_labs:
6582 return Builtin::BI__builtin_llabs;
6583 case Builtin::BI__builtin_llabs:
6584 return 0;
6585
6586 case Builtin::BI__builtin_fabsf:
6587 return Builtin::BI__builtin_fabs;
6588 case Builtin::BI__builtin_fabs:
6589 return Builtin::BI__builtin_fabsl;
6590 case Builtin::BI__builtin_fabsl:
6591 return 0;
6592
6593 case Builtin::BI__builtin_cabsf:
6594 return Builtin::BI__builtin_cabs;
6595 case Builtin::BI__builtin_cabs:
6596 return Builtin::BI__builtin_cabsl;
6597 case Builtin::BI__builtin_cabsl:
6598 return 0;
6599
6600 case Builtin::BIabs:
6601 return Builtin::BIlabs;
6602 case Builtin::BIlabs:
6603 return Builtin::BIllabs;
6604 case Builtin::BIllabs:
6605 return 0;
6606
6607 case Builtin::BIfabsf:
6608 return Builtin::BIfabs;
6609 case Builtin::BIfabs:
6610 return Builtin::BIfabsl;
6611 case Builtin::BIfabsl:
6612 return 0;
6613
6614 case Builtin::BIcabsf:
6615 return Builtin::BIcabs;
6616 case Builtin::BIcabs:
6617 return Builtin::BIcabsl;
6618 case Builtin::BIcabsl:
6619 return 0;
6620 }
6621}
6622
6623// Returns the argument type of the absolute value function.
6624static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6625 unsigned AbsType) {
6626 if (AbsType == 0)
6627 return QualType();
6628
6629 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6630 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6631 if (Error != ASTContext::GE_None)
6632 return QualType();
6633
6634 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6635 if (!FT)
6636 return QualType();
6637
6638 if (FT->getNumParams() != 1)
6639 return QualType();
6640
6641 return FT->getParamType(0);
6642}
6643
6644// Returns the best absolute value function, or zero, based on type and
6645// current absolute value function.
6646static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6647 unsigned AbsFunctionKind) {
6648 unsigned BestKind = 0;
6649 uint64_t ArgSize = Context.getTypeSize(ArgType);
6650 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6651 Kind = getLargerAbsoluteValueFunction(Kind)) {
6652 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6653 if (Context.getTypeSize(ParamType) >= ArgSize) {
6654 if (BestKind == 0)
6655 BestKind = Kind;
6656 else if (Context.hasSameType(ParamType, ArgType)) {
6657 BestKind = Kind;
6658 break;
6659 }
6660 }
6661 }
6662 return BestKind;
6663}
6664
6665enum AbsoluteValueKind {
6666 AVK_Integer,
6667 AVK_Floating,
6668 AVK_Complex
6669};
6670
6671static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6672 if (T->isIntegralOrEnumerationType())
6673 return AVK_Integer;
6674 if (T->isRealFloatingType())
6675 return AVK_Floating;
6676 if (T->isAnyComplexType())
6677 return AVK_Complex;
6678
6679 llvm_unreachable("Type not integer, floating, or complex");
6680}
6681
6682// Changes the absolute value function to a different type. Preserves whether
6683// the function is a builtin.
6684static unsigned changeAbsFunction(unsigned AbsKind,
6685 AbsoluteValueKind ValueKind) {
6686 switch (ValueKind) {
6687 case AVK_Integer:
6688 switch (AbsKind) {
6689 default:
6690 return 0;
6691 case Builtin::BI__builtin_fabsf:
6692 case Builtin::BI__builtin_fabs:
6693 case Builtin::BI__builtin_fabsl:
6694 case Builtin::BI__builtin_cabsf:
6695 case Builtin::BI__builtin_cabs:
6696 case Builtin::BI__builtin_cabsl:
6697 return Builtin::BI__builtin_abs;
6698 case Builtin::BIfabsf:
6699 case Builtin::BIfabs:
6700 case Builtin::BIfabsl:
6701 case Builtin::BIcabsf:
6702 case Builtin::BIcabs:
6703 case Builtin::BIcabsl:
6704 return Builtin::BIabs;
6705 }
6706 case AVK_Floating:
6707 switch (AbsKind) {
6708 default:
6709 return 0;
6710 case Builtin::BI__builtin_abs:
6711 case Builtin::BI__builtin_labs:
6712 case Builtin::BI__builtin_llabs:
6713 case Builtin::BI__builtin_cabsf:
6714 case Builtin::BI__builtin_cabs:
6715 case Builtin::BI__builtin_cabsl:
6716 return Builtin::BI__builtin_fabsf;
6717 case Builtin::BIabs:
6718 case Builtin::BIlabs:
6719 case Builtin::BIllabs:
6720 case Builtin::BIcabsf:
6721 case Builtin::BIcabs:
6722 case Builtin::BIcabsl:
6723 return Builtin::BIfabsf;
6724 }
6725 case AVK_Complex:
6726 switch (AbsKind) {
6727 default:
6728 return 0;
6729 case Builtin::BI__builtin_abs:
6730 case Builtin::BI__builtin_labs:
6731 case Builtin::BI__builtin_llabs:
6732 case Builtin::BI__builtin_fabsf:
6733 case Builtin::BI__builtin_fabs:
6734 case Builtin::BI__builtin_fabsl:
6735 return Builtin::BI__builtin_cabsf;
6736 case Builtin::BIabs:
6737 case Builtin::BIlabs:
6738 case Builtin::BIllabs:
6739 case Builtin::BIfabsf:
6740 case Builtin::BIfabs:
6741 case Builtin::BIfabsl:
6742 return Builtin::BIcabsf;
6743 }
6744 }
6745 llvm_unreachable("Unable to convert function");
6746}
6747
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006748static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006749 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6750 if (!FnInfo)
6751 return 0;
6752
6753 switch (FDecl->getBuiltinID()) {
6754 default:
6755 return 0;
6756 case Builtin::BI__builtin_abs:
6757 case Builtin::BI__builtin_fabs:
6758 case Builtin::BI__builtin_fabsf:
6759 case Builtin::BI__builtin_fabsl:
6760 case Builtin::BI__builtin_labs:
6761 case Builtin::BI__builtin_llabs:
6762 case Builtin::BI__builtin_cabs:
6763 case Builtin::BI__builtin_cabsf:
6764 case Builtin::BI__builtin_cabsl:
6765 case Builtin::BIabs:
6766 case Builtin::BIlabs:
6767 case Builtin::BIllabs:
6768 case Builtin::BIfabs:
6769 case Builtin::BIfabsf:
6770 case Builtin::BIfabsl:
6771 case Builtin::BIcabs:
6772 case Builtin::BIcabsf:
6773 case Builtin::BIcabsl:
6774 return FDecl->getBuiltinID();
6775 }
6776 llvm_unreachable("Unknown Builtin type");
6777}
6778
6779// If the replacement is valid, emit a note with replacement function.
6780// Additionally, suggest including the proper header if not already included.
6781static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00006782 unsigned AbsKind, QualType ArgType) {
6783 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006784 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00006785 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006786 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6787 FunctionName = "std::abs";
6788 if (ArgType->isIntegralOrEnumerationType()) {
6789 HeaderName = "cstdlib";
6790 } else if (ArgType->isRealFloatingType()) {
6791 HeaderName = "cmath";
6792 } else {
6793 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006794 }
Richard Trieubeffb832014-04-15 23:47:53 +00006795
6796 // Lookup all std::abs
6797 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00006798 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00006799 R.suppressDiagnostics();
6800 S.LookupQualifiedName(R, Std);
6801
6802 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006803 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006804 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6805 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6806 } else {
6807 FDecl = dyn_cast<FunctionDecl>(I);
6808 }
6809 if (!FDecl)
6810 continue;
6811
6812 // Found std::abs(), check that they are the right ones.
6813 if (FDecl->getNumParams() != 1)
6814 continue;
6815
6816 // Check that the parameter type can handle the argument.
6817 QualType ParamType = FDecl->getParamDecl(0)->getType();
6818 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6819 S.Context.getTypeSize(ArgType) <=
6820 S.Context.getTypeSize(ParamType)) {
6821 // Found a function, don't need the header hint.
6822 EmitHeaderHint = false;
6823 break;
6824 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006825 }
Richard Trieubeffb832014-04-15 23:47:53 +00006826 }
6827 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00006828 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00006829 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6830
6831 if (HeaderName) {
6832 DeclarationName DN(&S.Context.Idents.get(FunctionName));
6833 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6834 R.suppressDiagnostics();
6835 S.LookupName(R, S.getCurScope());
6836
6837 if (R.isSingleResult()) {
6838 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6839 if (FD && FD->getBuiltinID() == AbsKind) {
6840 EmitHeaderHint = false;
6841 } else {
6842 return;
6843 }
6844 } else if (!R.empty()) {
6845 return;
6846 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006847 }
6848 }
6849
6850 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00006851 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006852
Richard Trieubeffb832014-04-15 23:47:53 +00006853 if (!HeaderName)
6854 return;
6855
6856 if (!EmitHeaderHint)
6857 return;
6858
Alp Toker5d96e0a2014-07-11 20:53:51 +00006859 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6860 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00006861}
6862
Richard Trieua7f30b12016-12-06 01:42:28 +00006863template <std::size_t StrLen>
6864static bool IsStdFunction(const FunctionDecl *FDecl,
6865 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00006866 if (!FDecl)
6867 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00006868 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00006869 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00006870 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00006871 return false;
6872
6873 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006874}
6875
6876// Warn when using the wrong abs() function.
6877void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00006878 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006879 if (Call->getNumArgs() != 1)
6880 return;
6881
6882 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00006883 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00006884 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006885 return;
6886
6887 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6888 QualType ParamType = Call->getArg(0)->getType();
6889
Alp Toker5d96e0a2014-07-11 20:53:51 +00006890 // Unsigned types cannot be negative. Suggest removing the absolute value
6891 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006892 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00006893 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00006894 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006895 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6896 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00006897 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006898 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6899 return;
6900 }
6901
David Majnemer7f77eb92015-11-15 03:04:34 +00006902 // Taking the absolute value of a pointer is very suspicious, they probably
6903 // wanted to index into an array, dereference a pointer, call a function, etc.
6904 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6905 unsigned DiagType = 0;
6906 if (ArgType->isFunctionType())
6907 DiagType = 1;
6908 else if (ArgType->isArrayType())
6909 DiagType = 2;
6910
6911 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6912 return;
6913 }
6914
Richard Trieubeffb832014-04-15 23:47:53 +00006915 // std::abs has overloads which prevent most of the absolute value problems
6916 // from occurring.
6917 if (IsStdAbs)
6918 return;
6919
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006920 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6921 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6922
6923 // The argument and parameter are the same kind. Check if they are the right
6924 // size.
6925 if (ArgValueKind == ParamValueKind) {
6926 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6927 return;
6928
6929 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6930 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6931 << FDecl << ArgType << ParamType;
6932
6933 if (NewAbsKind == 0)
6934 return;
6935
6936 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006937 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006938 return;
6939 }
6940
6941 // ArgValueKind != ParamValueKind
6942 // The wrong type of absolute value function was used. Attempt to find the
6943 // proper one.
6944 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6945 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6946 if (NewAbsKind == 0)
6947 return;
6948
6949 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6950 << FDecl << ParamValueKind << ArgValueKind;
6951
6952 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006953 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006954}
6955
Richard Trieu67c00712016-12-05 23:41:46 +00006956//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00006957void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
6958 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00006959 if (!Call || !FDecl) return;
6960
6961 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00006962 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00006963 if (Call->getExprLoc().isMacroID()) return;
6964
6965 // Only care about the one template argument, two function parameter std::max
6966 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00006967 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00006968 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
6969 if (!ArgList) return;
6970 if (ArgList->size() != 1) return;
6971
6972 // Check that template type argument is unsigned integer.
6973 const auto& TA = ArgList->get(0);
6974 if (TA.getKind() != TemplateArgument::Type) return;
6975 QualType ArgType = TA.getAsType();
6976 if (!ArgType->isUnsignedIntegerType()) return;
6977
6978 // See if either argument is a literal zero.
6979 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
6980 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
6981 if (!MTE) return false;
6982 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
6983 if (!Num) return false;
6984 if (Num->getValue() != 0) return false;
6985 return true;
6986 };
6987
6988 const Expr *FirstArg = Call->getArg(0);
6989 const Expr *SecondArg = Call->getArg(1);
6990 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
6991 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
6992
6993 // Only warn when exactly one argument is zero.
6994 if (IsFirstArgZero == IsSecondArgZero) return;
6995
6996 SourceRange FirstRange = FirstArg->getSourceRange();
6997 SourceRange SecondRange = SecondArg->getSourceRange();
6998
6999 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7000
7001 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7002 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7003
7004 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7005 SourceRange RemovalRange;
7006 if (IsFirstArgZero) {
7007 RemovalRange = SourceRange(FirstRange.getBegin(),
7008 SecondRange.getBegin().getLocWithOffset(-1));
7009 } else {
7010 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7011 SecondRange.getEnd());
7012 }
7013
7014 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7015 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7016 << FixItHint::CreateRemoval(RemovalRange);
7017}
7018
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007019//===--- CHECK: Standard memory functions ---------------------------------===//
7020
Nico Weber0e6daef2013-12-26 23:38:39 +00007021/// \brief Takes the expression passed to the size_t parameter of functions
7022/// such as memcmp, strncat, etc and warns if it's a comparison.
7023///
7024/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7025static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7026 IdentifierInfo *FnName,
7027 SourceLocation FnLoc,
7028 SourceLocation RParenLoc) {
7029 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7030 if (!Size)
7031 return false;
7032
7033 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
7034 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
7035 return false;
7036
Nico Weber0e6daef2013-12-26 23:38:39 +00007037 SourceRange SizeRange = Size->getSourceRange();
7038 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7039 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00007040 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007041 << FnName << FixItHint::CreateInsertion(
7042 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00007043 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00007044 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00007045 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00007046 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7047 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00007048
7049 return true;
7050}
7051
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007052/// \brief Determine whether the given type is or contains a dynamic class type
7053/// (e.g., whether it has a vtable).
7054static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7055 bool &IsContained) {
7056 // Look through array types while ignoring qualifiers.
7057 const Type *Ty = T->getBaseElementTypeUnsafe();
7058 IsContained = false;
7059
7060 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7061 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00007062 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007063 return nullptr;
7064
7065 if (RD->isDynamicClass())
7066 return RD;
7067
7068 // Check all the fields. If any bases were dynamic, the class is dynamic.
7069 // It's impossible for a class to transitively contain itself by value, so
7070 // infinite recursion is impossible.
7071 for (auto *FD : RD->fields()) {
7072 bool SubContained;
7073 if (const CXXRecordDecl *ContainedRD =
7074 getContainedDynamicClass(FD->getType(), SubContained)) {
7075 IsContained = true;
7076 return ContainedRD;
7077 }
7078 }
7079
7080 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007081}
7082
Chandler Carruth889ed862011-06-21 23:04:20 +00007083/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007084/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007085static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007086 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007087 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7088 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
7089 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007090
Craig Topperc3ec1492014-05-26 06:22:03 +00007091 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007092}
7093
Chandler Carruth889ed862011-06-21 23:04:20 +00007094/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007095static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007096 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7097 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7098 if (SizeOf->getKind() == clang::UETT_SizeOf)
7099 return SizeOf->getTypeOfArgument();
7100
7101 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007102}
7103
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007104/// \brief Check for dangerous or invalid arguments to memset().
7105///
Chandler Carruthac687262011-06-03 06:23:57 +00007106/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007107/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7108/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007109///
7110/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007111void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007112 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007113 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007114 assert(BId != 0);
7115
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007116 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007117 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007118 unsigned ExpectedNumArgs =
7119 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007120 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007121 return;
7122
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007123 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007124 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007125 unsigned LenArg =
7126 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007127 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007128
Nico Weber0e6daef2013-12-26 23:38:39 +00007129 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7130 Call->getLocStart(), Call->getRParenLoc()))
7131 return;
7132
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007133 // We have special checking when the length is a sizeof expression.
7134 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7135 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7136 llvm::FoldingSetNodeID SizeOfArgID;
7137
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007138 // Although widely used, 'bzero' is not a standard function. Be more strict
7139 // with the argument types before allowing diagnostics and only allow the
7140 // form bzero(ptr, sizeof(...)).
7141 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7142 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7143 return;
7144
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007145 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7146 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007147 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007148
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007149 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007150 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007151 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007152 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007153
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007154 // Never warn about void type pointers. This can be used to suppress
7155 // false positives.
7156 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007157 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007158
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007159 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7160 // actually comparing the expressions for equality. Because computing the
7161 // expression IDs can be expensive, we only do this if the diagnostic is
7162 // enabled.
7163 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007164 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7165 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007166 // We only compute IDs for expressions if the warning is enabled, and
7167 // cache the sizeof arg's ID.
7168 if (SizeOfArgID == llvm::FoldingSetNodeID())
7169 SizeOfArg->Profile(SizeOfArgID, Context, true);
7170 llvm::FoldingSetNodeID DestID;
7171 Dest->Profile(DestID, Context, true);
7172 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007173 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7174 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007175 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007176 StringRef ReadableName = FnName->getName();
7177
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007178 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007179 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007180 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007181 if (!PointeeTy->isIncompleteType() &&
7182 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007183 ActionIdx = 2; // If the pointee's size is sizeof(char),
7184 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007185
7186 // If the function is defined as a builtin macro, do not show macro
7187 // expansion.
7188 SourceLocation SL = SizeOfArg->getExprLoc();
7189 SourceRange DSR = Dest->getSourceRange();
7190 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007191 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007192
7193 if (SM.isMacroArgExpansion(SL)) {
7194 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7195 SL = SM.getSpellingLoc(SL);
7196 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7197 SM.getSpellingLoc(DSR.getEnd()));
7198 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7199 SM.getSpellingLoc(SSR.getEnd()));
7200 }
7201
Anna Zaksd08d9152012-05-30 23:14:52 +00007202 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007203 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007204 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007205 << PointeeTy
7206 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007207 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007208 << SSR);
7209 DiagRuntimeBehavior(SL, SizeOfArg,
7210 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7211 << ActionIdx
7212 << SSR);
7213
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007214 break;
7215 }
7216 }
7217
7218 // Also check for cases where the sizeof argument is the exact same
7219 // type as the memory argument, and where it points to a user-defined
7220 // record type.
7221 if (SizeOfArgTy != QualType()) {
7222 if (PointeeTy->isRecordType() &&
7223 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7224 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7225 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7226 << FnName << SizeOfArgTy << ArgIdx
7227 << PointeeTy << Dest->getSourceRange()
7228 << LenExpr->getSourceRange());
7229 break;
7230 }
Nico Weberc5e73862011-06-14 16:14:58 +00007231 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00007232 } else if (DestTy->isArrayType()) {
7233 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00007234 }
Nico Weberc5e73862011-06-14 16:14:58 +00007235
Nico Weberc44b35e2015-03-21 17:37:46 +00007236 if (PointeeTy == QualType())
7237 continue;
Anna Zaks22122702012-01-17 00:37:07 +00007238
Nico Weberc44b35e2015-03-21 17:37:46 +00007239 // Always complain about dynamic classes.
7240 bool IsContained;
7241 if (const CXXRecordDecl *ContainedRD =
7242 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00007243
Nico Weberc44b35e2015-03-21 17:37:46 +00007244 unsigned OperationType = 0;
7245 // "overwritten" if we're warning about the destination for any call
7246 // but memcmp; otherwise a verb appropriate to the call.
7247 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7248 if (BId == Builtin::BImemcpy)
7249 OperationType = 1;
7250 else if(BId == Builtin::BImemmove)
7251 OperationType = 2;
7252 else if (BId == Builtin::BImemcmp)
7253 OperationType = 3;
7254 }
7255
John McCall31168b02011-06-15 23:02:42 +00007256 DiagRuntimeBehavior(
7257 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007258 PDiag(diag::warn_dyn_class_memaccess)
7259 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7260 << FnName << IsContained << ContainedRD << OperationType
7261 << Call->getCallee()->getSourceRange());
7262 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7263 BId != Builtin::BImemset)
7264 DiagRuntimeBehavior(
7265 Dest->getExprLoc(), Dest,
7266 PDiag(diag::warn_arc_object_memaccess)
7267 << ArgIdx << FnName << PointeeTy
7268 << Call->getCallee()->getSourceRange());
7269 else
7270 continue;
7271
7272 DiagRuntimeBehavior(
7273 Dest->getExprLoc(), Dest,
7274 PDiag(diag::note_bad_memaccess_silence)
7275 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7276 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007277 }
7278}
7279
Ted Kremenek6865f772011-08-18 20:55:45 +00007280// A little helper routine: ignore addition and subtraction of integer literals.
7281// This intentionally does not ignore all integer constant expressions because
7282// we don't want to remove sizeof().
7283static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7284 Ex = Ex->IgnoreParenCasts();
7285
7286 for (;;) {
7287 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7288 if (!BO || !BO->isAdditiveOp())
7289 break;
7290
7291 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7292 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7293
7294 if (isa<IntegerLiteral>(RHS))
7295 Ex = LHS;
7296 else if (isa<IntegerLiteral>(LHS))
7297 Ex = RHS;
7298 else
7299 break;
7300 }
7301
7302 return Ex;
7303}
7304
Anna Zaks13b08572012-08-08 21:42:23 +00007305static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7306 ASTContext &Context) {
7307 // Only handle constant-sized or VLAs, but not flexible members.
7308 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7309 // Only issue the FIXIT for arrays of size > 1.
7310 if (CAT->getSize().getSExtValue() <= 1)
7311 return false;
7312 } else if (!Ty->isVariableArrayType()) {
7313 return false;
7314 }
7315 return true;
7316}
7317
Ted Kremenek6865f772011-08-18 20:55:45 +00007318// Warn if the user has made the 'size' argument to strlcpy or strlcat
7319// be the size of the source, instead of the destination.
7320void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7321 IdentifierInfo *FnName) {
7322
7323 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007324 unsigned NumArgs = Call->getNumArgs();
7325 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007326 return;
7327
7328 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7329 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007330 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007331
7332 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7333 Call->getLocStart(), Call->getRParenLoc()))
7334 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00007335
7336 // Look for 'strlcpy(dst, x, sizeof(x))'
7337 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7338 CompareWithSrc = Ex;
7339 else {
7340 // Look for 'strlcpy(dst, x, strlen(x))'
7341 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00007342 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7343 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00007344 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7345 }
7346 }
7347
7348 if (!CompareWithSrc)
7349 return;
7350
7351 // Determine if the argument to sizeof/strlen is equal to the source
7352 // argument. In principle there's all kinds of things you could do
7353 // here, for instance creating an == expression and evaluating it with
7354 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7355 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7356 if (!SrcArgDRE)
7357 return;
7358
7359 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7360 if (!CompareWithSrcDRE ||
7361 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7362 return;
7363
7364 const Expr *OriginalSizeArg = Call->getArg(2);
7365 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7366 << OriginalSizeArg->getSourceRange() << FnName;
7367
7368 // Output a FIXIT hint if the destination is an array (rather than a
7369 // pointer to an array). This could be enhanced to handle some
7370 // pointers if we know the actual size, like if DstArg is 'array+2'
7371 // we could say 'sizeof(array)-2'.
7372 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00007373 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00007374 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007375
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007376 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007377 llvm::raw_svector_ostream OS(sizeString);
7378 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007379 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00007380 OS << ")";
7381
7382 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7383 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7384 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00007385}
7386
Anna Zaks314cd092012-02-01 19:08:57 +00007387/// Check if two expressions refer to the same declaration.
7388static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7389 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7390 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7391 return D1->getDecl() == D2->getDecl();
7392 return false;
7393}
7394
7395static const Expr *getStrlenExprArg(const Expr *E) {
7396 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7397 const FunctionDecl *FD = CE->getDirectCallee();
7398 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00007399 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007400 return CE->getArg(0)->IgnoreParenCasts();
7401 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007402 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007403}
7404
7405// Warn on anti-patterns as the 'size' argument to strncat.
7406// The correct size argument should look like following:
7407// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7408void Sema::CheckStrncatArguments(const CallExpr *CE,
7409 IdentifierInfo *FnName) {
7410 // Don't crash if the user has the wrong number of arguments.
7411 if (CE->getNumArgs() < 3)
7412 return;
7413 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7414 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7415 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7416
Nico Weber0e6daef2013-12-26 23:38:39 +00007417 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7418 CE->getRParenLoc()))
7419 return;
7420
Anna Zaks314cd092012-02-01 19:08:57 +00007421 // Identify common expressions, which are wrongly used as the size argument
7422 // to strncat and may lead to buffer overflows.
7423 unsigned PatternType = 0;
7424 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7425 // - sizeof(dst)
7426 if (referToTheSameDecl(SizeOfArg, DstArg))
7427 PatternType = 1;
7428 // - sizeof(src)
7429 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7430 PatternType = 2;
7431 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7432 if (BE->getOpcode() == BO_Sub) {
7433 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7434 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7435 // - sizeof(dst) - strlen(dst)
7436 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7437 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7438 PatternType = 1;
7439 // - sizeof(src) - (anything)
7440 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7441 PatternType = 2;
7442 }
7443 }
7444
7445 if (PatternType == 0)
7446 return;
7447
Anna Zaks5069aa32012-02-03 01:27:37 +00007448 // Generate the diagnostic.
7449 SourceLocation SL = LenArg->getLocStart();
7450 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007451 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00007452
7453 // If the function is defined as a builtin macro, do not show macro expansion.
7454 if (SM.isMacroArgExpansion(SL)) {
7455 SL = SM.getSpellingLoc(SL);
7456 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7457 SM.getSpellingLoc(SR.getEnd()));
7458 }
7459
Anna Zaks13b08572012-08-08 21:42:23 +00007460 // Check if the destination is an array (rather than a pointer to an array).
7461 QualType DstTy = DstArg->getType();
7462 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7463 Context);
7464 if (!isKnownSizeArray) {
7465 if (PatternType == 1)
7466 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7467 else
7468 Diag(SL, diag::warn_strncat_src_size) << SR;
7469 return;
7470 }
7471
Anna Zaks314cd092012-02-01 19:08:57 +00007472 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00007473 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007474 else
Anna Zaks5069aa32012-02-03 01:27:37 +00007475 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007476
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007477 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00007478 llvm::raw_svector_ostream OS(sizeString);
7479 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007480 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007481 OS << ") - ";
7482 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007483 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007484 OS << ") - 1";
7485
Anna Zaks5069aa32012-02-03 01:27:37 +00007486 Diag(SL, diag::note_strncat_wrong_size)
7487 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00007488}
7489
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007490//===--- CHECK: Return Address of Stack Variable --------------------------===//
7491
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007492static const Expr *EvalVal(const Expr *E,
7493 SmallVectorImpl<const DeclRefExpr *> &refVars,
7494 const Decl *ParentDecl);
7495static const Expr *EvalAddr(const Expr *E,
7496 SmallVectorImpl<const DeclRefExpr *> &refVars,
7497 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007498
7499/// CheckReturnStackAddr - Check if a return statement returns the address
7500/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007501static void
7502CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7503 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00007504
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007505 const Expr *stackE = nullptr;
7506 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007507
7508 // Perform checking for returned stack addresses, local blocks,
7509 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00007510 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007511 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007512 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00007513 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007514 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007515 }
7516
Craig Topperc3ec1492014-05-26 06:22:03 +00007517 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007518 return; // Nothing suspicious was found.
7519
Simon Pilgrim750bde62017-03-31 11:00:53 +00007520 // Parameters are initialized in the calling scope, so taking the address
Richard Trieu81b6c562016-08-05 23:24:47 +00007521 // of a parameter reference doesn't need a warning.
7522 for (auto *DRE : refVars)
7523 if (isa<ParmVarDecl>(DRE->getDecl()))
7524 return;
7525
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007526 SourceLocation diagLoc;
7527 SourceRange diagRange;
7528 if (refVars.empty()) {
7529 diagLoc = stackE->getLocStart();
7530 diagRange = stackE->getSourceRange();
7531 } else {
7532 // We followed through a reference variable. 'stackE' contains the
7533 // problematic expression but we will warn at the return statement pointing
7534 // at the reference variable. We will later display the "trail" of
7535 // reference variables using notes.
7536 diagLoc = refVars[0]->getLocStart();
7537 diagRange = refVars[0]->getSourceRange();
7538 }
7539
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007540 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7541 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00007542 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007543 << DR->getDecl()->getDeclName() << diagRange;
7544 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007545 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007546 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007547 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007548 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00007549 // If there is an LValue->RValue conversion, then the value of the
7550 // reference type is used, not the reference.
7551 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7552 if (ICE->getCastKind() == CK_LValueToRValue) {
7553 return;
7554 }
7555 }
Craig Topperda7b27f2015-11-17 05:40:09 +00007556 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7557 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007558 }
7559
7560 // Display the "trail" of reference variables that we followed until we
7561 // found the problematic expression using notes.
7562 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007563 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007564 // If this var binds to another reference var, show the range of the next
7565 // var, otherwise the var binds to the problematic expression, in which case
7566 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007567 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7568 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007569 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7570 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007571 }
7572}
7573
7574/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7575/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007576/// to a location on the stack, a local block, an address of a label, or a
7577/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007578/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007579/// encounter a subexpression that (1) clearly does not lead to one of the
7580/// above problematic expressions (2) is something we cannot determine leads to
7581/// a problematic expression based on such local checking.
7582///
7583/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7584/// the expression that they point to. Such variables are added to the
7585/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007586///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007587/// EvalAddr processes expressions that are pointers that are used as
7588/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007589/// At the base case of the recursion is a check for the above problematic
7590/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007591///
7592/// This implementation handles:
7593///
7594/// * pointer-to-pointer casts
7595/// * implicit conversions from array references to pointers
7596/// * taking the address of fields
7597/// * arbitrary interplay between "&" and "*" operators
7598/// * pointer arithmetic from an address of a stack variable
7599/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007600static const Expr *EvalAddr(const Expr *E,
7601 SmallVectorImpl<const DeclRefExpr *> &refVars,
7602 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007603 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00007604 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007605
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007606 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00007607 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00007608 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007609 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00007610 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00007611
Peter Collingbourne91147592011-04-15 00:35:48 +00007612 E = E->IgnoreParens();
7613
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007614 // Our "symbolic interpreter" is just a dispatch off the currently
7615 // viewed AST node. We then recursively traverse the AST by calling
7616 // EvalAddr and EvalVal appropriately.
7617 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007618 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007619 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007620
Richard Smith40f08eb2014-01-30 22:05:38 +00007621 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00007622 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00007623 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00007624
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007625 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007626 // If this is a reference variable, follow through to the expression that
7627 // it points to.
7628 if (V->hasLocalStorage() &&
7629 V->getType()->isReferenceType() && V->hasInit()) {
7630 // Add the reference variable to the "trail".
7631 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007632 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007633 }
7634
Craig Topperc3ec1492014-05-26 06:22:03 +00007635 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007636 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007637
Chris Lattner934edb22007-12-28 05:31:15 +00007638 case Stmt::UnaryOperatorClass: {
7639 // The only unary operator that make sense to handle here
7640 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007641 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007642
John McCalle3027922010-08-25 11:45:40 +00007643 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007644 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007645 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007646 }
Mike Stump11289f42009-09-09 15:08:12 +00007647
Chris Lattner934edb22007-12-28 05:31:15 +00007648 case Stmt::BinaryOperatorClass: {
7649 // Handle pointer arithmetic. All other binary operators are not valid
7650 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007651 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00007652 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00007653
John McCalle3027922010-08-25 11:45:40 +00007654 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00007655 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007656
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007657 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00007658
7659 // Determine which argument is the real pointer base. It could be
7660 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007661 if (!Base->getType()->isPointerType())
7662 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00007663
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007664 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007665 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007666 }
Steve Naroff2752a172008-09-10 19:17:48 +00007667
Chris Lattner934edb22007-12-28 05:31:15 +00007668 // For conditional operators we need to see if either the LHS or RHS are
7669 // valid DeclRefExpr*s. If one of them is valid, we return it.
7670 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007671 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007672
Chris Lattner934edb22007-12-28 05:31:15 +00007673 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007674 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007675 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007676 // In C++, we can have a throw-expression, which has 'void' type.
7677 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007678 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007679 return LHS;
7680 }
Chris Lattner934edb22007-12-28 05:31:15 +00007681
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007682 // In C++, we can have a throw-expression, which has 'void' type.
7683 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00007684 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007685
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007686 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007687 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007688
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007689 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00007690 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007691 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00007692 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007693
7694 case Stmt::AddrLabelExprClass:
7695 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00007696
John McCall28fc7092011-11-10 05:35:25 +00007697 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007698 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7699 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00007700
Ted Kremenekc3b4c522008-08-07 00:49:01 +00007701 // For casts, we need to handle conversions from arrays to
7702 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00007703 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00007704 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007705 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00007706 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00007707 case Stmt::CXXStaticCastExprClass:
7708 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00007709 case Stmt::CXXConstCastExprClass:
7710 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007711 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00007712 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00007713 case CK_LValueToRValue:
7714 case CK_NoOp:
7715 case CK_BaseToDerived:
7716 case CK_DerivedToBase:
7717 case CK_UncheckedDerivedToBase:
7718 case CK_Dynamic:
7719 case CK_CPointerToObjCPointerCast:
7720 case CK_BlockPointerToObjCPointerCast:
7721 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007722 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007723
7724 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007725 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007726
Richard Trieudadefde2014-07-02 04:39:38 +00007727 case CK_BitCast:
7728 if (SubExpr->getType()->isAnyPointerType() ||
7729 SubExpr->getType()->isBlockPointerType() ||
7730 SubExpr->getType()->isObjCQualifiedIdType())
7731 return EvalAddr(SubExpr, refVars, ParentDecl);
7732 else
7733 return nullptr;
7734
Eli Friedman8195ad72012-02-23 23:04:32 +00007735 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007736 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00007737 }
Chris Lattner934edb22007-12-28 05:31:15 +00007738 }
Mike Stump11289f42009-09-09 15:08:12 +00007739
Douglas Gregorfe314812011-06-21 17:03:29 +00007740 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007741 if (const Expr *Result =
7742 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7743 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00007744 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00007745 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007746
Chris Lattner934edb22007-12-28 05:31:15 +00007747 // Everything else: we simply don't reason about them.
7748 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007749 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00007750 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007751}
Mike Stump11289f42009-09-09 15:08:12 +00007752
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007753/// EvalVal - This function is complements EvalAddr in the mutual recursion.
7754/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007755static const Expr *EvalVal(const Expr *E,
7756 SmallVectorImpl<const DeclRefExpr *> &refVars,
7757 const Decl *ParentDecl) {
7758 do {
7759 // We should only be called for evaluating non-pointer expressions, or
7760 // expressions with a pointer type that are not used as references but
7761 // instead
7762 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00007763
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007764 // Our "symbolic interpreter" is just a dispatch off the currently
7765 // viewed AST node. We then recursively traverse the AST by calling
7766 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00007767
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007768 E = E->IgnoreParens();
7769 switch (E->getStmtClass()) {
7770 case Stmt::ImplicitCastExprClass: {
7771 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7772 if (IE->getValueKind() == VK_LValue) {
7773 E = IE->getSubExpr();
7774 continue;
7775 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007776 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007777 }
Richard Smith40f08eb2014-01-30 22:05:38 +00007778
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007779 case Stmt::ExprWithCleanupsClass:
7780 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7781 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007782
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007783 case Stmt::DeclRefExprClass: {
7784 // When we hit a DeclRefExpr we are looking at code that refers to a
7785 // variable's name. If it's not a reference variable we check if it has
7786 // local storage within the function, and if so, return the expression.
7787 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7788
7789 // If we leave the immediate function, the lifetime isn't about to end.
7790 if (DR->refersToEnclosingVariableOrCapture())
7791 return nullptr;
7792
7793 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7794 // Check if it refers to itself, e.g. "int& i = i;".
7795 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007796 return DR;
7797
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007798 if (V->hasLocalStorage()) {
7799 if (!V->getType()->isReferenceType())
7800 return DR;
7801
7802 // Reference variable, follow through to the expression that
7803 // it points to.
7804 if (V->hasInit()) {
7805 // Add the reference variable to the "trail".
7806 refVars.push_back(DR);
7807 return EvalVal(V->getInit(), refVars, V);
7808 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007809 }
7810 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007811
7812 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007813 }
Mike Stump11289f42009-09-09 15:08:12 +00007814
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007815 case Stmt::UnaryOperatorClass: {
7816 // The only unary operator that make sense to handle here
7817 // is Deref. All others don't resolve to a "name." This includes
7818 // handling all sorts of rvalues passed to a unary operator.
7819 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007820
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007821 if (U->getOpcode() == UO_Deref)
7822 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007823
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007824 return nullptr;
7825 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007826
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007827 case Stmt::ArraySubscriptExprClass: {
7828 // Array subscripts are potential references to data on the stack. We
7829 // retrieve the DeclRefExpr* for the array variable if it indeed
7830 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00007831 const auto *ASE = cast<ArraySubscriptExpr>(E);
7832 if (ASE->isTypeDependent())
7833 return nullptr;
7834 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007835 }
Mike Stump11289f42009-09-09 15:08:12 +00007836
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007837 case Stmt::OMPArraySectionExprClass: {
7838 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7839 ParentDecl);
7840 }
Mike Stump11289f42009-09-09 15:08:12 +00007841
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007842 case Stmt::ConditionalOperatorClass: {
7843 // For conditional operators we need to see if either the LHS or RHS are
7844 // non-NULL Expr's. If one is non-NULL, we return it.
7845 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007846
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007847 // Handle the GNU extension for missing LHS.
7848 if (const Expr *LHSExpr = C->getLHS()) {
7849 // In C++, we can have a throw-expression, which has 'void' type.
7850 if (!LHSExpr->getType()->isVoidType())
7851 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7852 return LHS;
7853 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007854
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007855 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007856 if (C->getRHS()->getType()->isVoidType())
7857 return nullptr;
7858
7859 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007860 }
7861
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007862 // Accesses to members are potential references to data on the stack.
7863 case Stmt::MemberExprClass: {
7864 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00007865
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007866 // Check for indirect access. We only want direct field accesses.
7867 if (M->isArrow())
7868 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007869
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007870 // Check whether the member type is itself a reference, in which case
7871 // we're not going to refer to the member, but to what the member refers
7872 // to.
7873 if (M->getMemberDecl()->getType()->isReferenceType())
7874 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007875
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007876 return EvalVal(M->getBase(), refVars, ParentDecl);
7877 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00007878
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007879 case Stmt::MaterializeTemporaryExprClass:
7880 if (const Expr *Result =
7881 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7882 refVars, ParentDecl))
7883 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007884 return E;
7885
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007886 default:
7887 // Check that we don't return or take the address of a reference to a
7888 // temporary. This is only useful in C++.
7889 if (!E->isTypeDependent() && E->isRValue())
7890 return E;
7891
7892 // Everything else: we simply don't reason about them.
7893 return nullptr;
7894 }
7895 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007896}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007897
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007898void
7899Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7900 SourceLocation ReturnLoc,
7901 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00007902 const AttrVec *Attrs,
7903 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007904 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7905
7906 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00007907 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7908 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00007909 CheckNonNullExpr(*this, RetValExp))
7910 Diag(ReturnLoc, diag::warn_null_ret)
7911 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00007912
7913 // C++11 [basic.stc.dynamic.allocation]p4:
7914 // If an allocation function declared with a non-throwing
7915 // exception-specification fails to allocate storage, it shall return
7916 // a null pointer. Any other allocation function that fails to allocate
7917 // storage shall indicate failure only by throwing an exception [...]
7918 if (FD) {
7919 OverloadedOperatorKind Op = FD->getOverloadedOperator();
7920 if (Op == OO_New || Op == OO_Array_New) {
7921 const FunctionProtoType *Proto
7922 = FD->getType()->castAs<FunctionProtoType>();
7923 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7924 CheckNonNullExpr(*this, RetValExp))
7925 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7926 << FD << getLangOpts().CPlusPlus11;
7927 }
7928 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007929}
7930
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007931//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7932
7933/// Check for comparisons of floating point operands using != and ==.
7934/// Issue a warning if these are no self-comparisons, as they are not likely
7935/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00007936void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00007937 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7938 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007939
7940 // Special case: check for x == x (which is OK).
7941 // Do not emit warnings for such cases.
7942 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7943 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7944 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00007945 return;
Mike Stump11289f42009-09-09 15:08:12 +00007946
Ted Kremenekeda40e22007-11-29 00:59:04 +00007947 // Special case: check for comparisons against literals that can be exactly
7948 // represented by APFloat. In such cases, do not emit a warning. This
7949 // is a heuristic: often comparison against such literals are used to
7950 // detect if a value in a variable has not changed. This clearly can
7951 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00007952 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7953 if (FLL->isExact())
7954 return;
7955 } else
7956 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7957 if (FLR->isExact())
7958 return;
Mike Stump11289f42009-09-09 15:08:12 +00007959
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007960 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00007961 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007962 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007963 return;
Mike Stump11289f42009-09-09 15:08:12 +00007964
David Blaikie1f4ff152012-07-16 20:47:22 +00007965 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007966 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007967 return;
Mike Stump11289f42009-09-09 15:08:12 +00007968
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007969 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00007970 Diag(Loc, diag::warn_floatingpoint_eq)
7971 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007972}
John McCallca01b222010-01-04 23:21:16 +00007973
John McCall70aa5392010-01-06 05:24:50 +00007974//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7975//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00007976
John McCall70aa5392010-01-06 05:24:50 +00007977namespace {
John McCallca01b222010-01-04 23:21:16 +00007978
John McCall70aa5392010-01-06 05:24:50 +00007979/// Structure recording the 'active' range of an integer-valued
7980/// expression.
7981struct IntRange {
7982 /// The number of bits active in the int.
7983 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00007984
John McCall70aa5392010-01-06 05:24:50 +00007985 /// True if the int is known not to have negative values.
7986 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00007987
John McCall70aa5392010-01-06 05:24:50 +00007988 IntRange(unsigned Width, bool NonNegative)
7989 : Width(Width), NonNegative(NonNegative)
7990 {}
John McCallca01b222010-01-04 23:21:16 +00007991
John McCall817d4af2010-11-10 23:38:19 +00007992 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00007993 static IntRange forBoolType() {
7994 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00007995 }
7996
John McCall817d4af2010-11-10 23:38:19 +00007997 /// Returns the range of an opaque value of the given integral type.
7998 static IntRange forValueOfType(ASTContext &C, QualType T) {
7999 return forValueOfCanonicalType(C,
8000 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00008001 }
8002
John McCall817d4af2010-11-10 23:38:19 +00008003 /// Returns the range of an opaque value of a canonical integral type.
8004 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00008005 assert(T->isCanonicalUnqualified());
8006
8007 if (const VectorType *VT = dyn_cast<VectorType>(T))
8008 T = VT->getElementType().getTypePtr();
8009 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8010 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008011 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8012 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00008013
David Majnemer6a426652013-06-07 22:07:20 +00008014 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00008015 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00008016 EnumDecl *Enum = ET->getDecl();
8017 if (!Enum->isCompleteDefinition())
8018 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00008019
David Majnemer6a426652013-06-07 22:07:20 +00008020 unsigned NumPositive = Enum->getNumPositiveBits();
8021 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00008022
David Majnemer6a426652013-06-07 22:07:20 +00008023 if (NumNegative == 0)
8024 return IntRange(NumPositive, true/*NonNegative*/);
8025 else
8026 return IntRange(std::max(NumPositive + 1, NumNegative),
8027 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00008028 }
John McCall70aa5392010-01-06 05:24:50 +00008029
8030 const BuiltinType *BT = cast<BuiltinType>(T);
8031 assert(BT->isInteger());
8032
8033 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8034 }
8035
John McCall817d4af2010-11-10 23:38:19 +00008036 /// Returns the "target" range of a canonical integral type, i.e.
8037 /// the range of values expressible in the type.
8038 ///
8039 /// This matches forValueOfCanonicalType except that enums have the
8040 /// full range of their type, not the range of their enumerators.
8041 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8042 assert(T->isCanonicalUnqualified());
8043
8044 if (const VectorType *VT = dyn_cast<VectorType>(T))
8045 T = VT->getElementType().getTypePtr();
8046 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8047 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008048 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8049 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008050 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00008051 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008052
8053 const BuiltinType *BT = cast<BuiltinType>(T);
8054 assert(BT->isInteger());
8055
8056 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8057 }
8058
8059 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00008060 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00008061 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00008062 L.NonNegative && R.NonNegative);
8063 }
8064
John McCall817d4af2010-11-10 23:38:19 +00008065 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008066 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008067 return IntRange(std::min(L.Width, R.Width),
8068 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008069 }
8070};
8071
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008072IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008073 if (value.isSigned() && value.isNegative())
8074 return IntRange(value.getMinSignedBits(), false);
8075
8076 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008077 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008078
8079 // isNonNegative() just checks the sign bit without considering
8080 // signedness.
8081 return IntRange(value.getActiveBits(), true);
8082}
8083
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008084IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8085 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008086 if (result.isInt())
8087 return GetValueRange(C, result.getInt(), MaxWidth);
8088
8089 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008090 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8091 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8092 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8093 R = IntRange::join(R, El);
8094 }
John McCall70aa5392010-01-06 05:24:50 +00008095 return R;
8096 }
8097
8098 if (result.isComplexInt()) {
8099 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8100 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8101 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008102 }
8103
8104 // This can happen with lossless casts to intptr_t of "based" lvalues.
8105 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008106 // FIXME: The only reason we need to pass the type in here is to get
8107 // the sign right on this one case. It would be nice if APValue
8108 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008109 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008110 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008111}
John McCall70aa5392010-01-06 05:24:50 +00008112
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008113QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008114 QualType Ty = E->getType();
8115 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8116 Ty = AtomicRHS->getValueType();
8117 return Ty;
8118}
8119
John McCall70aa5392010-01-06 05:24:50 +00008120/// Pseudo-evaluate the given integer expression, estimating the
8121/// range of values it might take.
8122///
8123/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008124IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008125 E = E->IgnoreParens();
8126
8127 // Try a full evaluation first.
8128 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008129 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008130 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008131
8132 // I think we only want to look through implicit casts here; if the
8133 // user has an explicit widening cast, we should treat the value as
8134 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008135 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00008136 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00008137 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8138
Eli Friedmane6d33952013-07-08 20:20:06 +00008139 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00008140
George Burgess IVdf1ed002016-01-13 01:52:39 +00008141 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8142 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00008143
John McCall70aa5392010-01-06 05:24:50 +00008144 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00008145 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00008146 return OutputTypeRange;
8147
8148 IntRange SubRange
8149 = GetExprRange(C, CE->getSubExpr(),
8150 std::min(MaxWidth, OutputTypeRange.Width));
8151
8152 // Bail out if the subexpr's range is as wide as the cast type.
8153 if (SubRange.Width >= OutputTypeRange.Width)
8154 return OutputTypeRange;
8155
8156 // Otherwise, we take the smaller width, and we're non-negative if
8157 // either the output type or the subexpr is.
8158 return IntRange(SubRange.Width,
8159 SubRange.NonNegative || OutputTypeRange.NonNegative);
8160 }
8161
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008162 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008163 // If we can fold the condition, just take that operand.
8164 bool CondResult;
8165 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8166 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8167 : CO->getFalseExpr(),
8168 MaxWidth);
8169
8170 // Otherwise, conservatively merge.
8171 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8172 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8173 return IntRange::join(L, R);
8174 }
8175
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008176 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008177 switch (BO->getOpcode()) {
8178
8179 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00008180 case BO_LAnd:
8181 case BO_LOr:
8182 case BO_LT:
8183 case BO_GT:
8184 case BO_LE:
8185 case BO_GE:
8186 case BO_EQ:
8187 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00008188 return IntRange::forBoolType();
8189
John McCallc3688382011-07-13 06:35:24 +00008190 // The type of the assignments is the type of the LHS, so the RHS
8191 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00008192 case BO_MulAssign:
8193 case BO_DivAssign:
8194 case BO_RemAssign:
8195 case BO_AddAssign:
8196 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00008197 case BO_XorAssign:
8198 case BO_OrAssign:
8199 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00008200 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00008201
John McCallc3688382011-07-13 06:35:24 +00008202 // Simple assignments just pass through the RHS, which will have
8203 // been coerced to the LHS type.
8204 case BO_Assign:
8205 // TODO: bitfields?
8206 return GetExprRange(C, BO->getRHS(), MaxWidth);
8207
John McCall70aa5392010-01-06 05:24:50 +00008208 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008209 case BO_PtrMemD:
8210 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00008211 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008212
John McCall2ce81ad2010-01-06 22:07:33 +00008213 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00008214 case BO_And:
8215 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00008216 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8217 GetExprRange(C, BO->getRHS(), MaxWidth));
8218
John McCall70aa5392010-01-06 05:24:50 +00008219 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00008220 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00008221 // ...except that we want to treat '1 << (blah)' as logically
8222 // positive. It's an important idiom.
8223 if (IntegerLiteral *I
8224 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8225 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008226 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00008227 return IntRange(R.Width, /*NonNegative*/ true);
8228 }
8229 }
8230 // fallthrough
8231
John McCalle3027922010-08-25 11:45:40 +00008232 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00008233 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008234
John McCall2ce81ad2010-01-06 22:07:33 +00008235 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00008236 case BO_Shr:
8237 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00008238 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8239
8240 // If the shift amount is a positive constant, drop the width by
8241 // that much.
8242 llvm::APSInt shift;
8243 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8244 shift.isNonNegative()) {
8245 unsigned zext = shift.getZExtValue();
8246 if (zext >= L.Width)
8247 L.Width = (L.NonNegative ? 0 : 1);
8248 else
8249 L.Width -= zext;
8250 }
8251
8252 return L;
8253 }
8254
8255 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008256 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008257 return GetExprRange(C, BO->getRHS(), MaxWidth);
8258
John McCall2ce81ad2010-01-06 22:07:33 +00008259 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008260 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008261 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008262 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008263 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008264
John McCall51431812011-07-14 22:39:48 +00008265 // The width of a division result is mostly determined by the size
8266 // of the LHS.
8267 case BO_Div: {
8268 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008269 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008270 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8271
8272 // If the divisor is constant, use that.
8273 llvm::APSInt divisor;
8274 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8275 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8276 if (log2 >= L.Width)
8277 L.Width = (L.NonNegative ? 0 : 1);
8278 else
8279 L.Width = std::min(L.Width - log2, MaxWidth);
8280 return L;
8281 }
8282
8283 // Otherwise, just use the LHS's width.
8284 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8285 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8286 }
8287
8288 // The result of a remainder can't be larger than the result of
8289 // either side.
8290 case BO_Rem: {
8291 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008292 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008293 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8294 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8295
8296 IntRange meet = IntRange::meet(L, R);
8297 meet.Width = std::min(meet.Width, MaxWidth);
8298 return meet;
8299 }
8300
8301 // The default behavior is okay for these.
8302 case BO_Mul:
8303 case BO_Add:
8304 case BO_Xor:
8305 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008306 break;
8307 }
8308
John McCall51431812011-07-14 22:39:48 +00008309 // The default case is to treat the operation as if it were closed
8310 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008311 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8312 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8313 return IntRange::join(L, R);
8314 }
8315
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008316 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008317 switch (UO->getOpcode()) {
8318 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008319 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008320 return IntRange::forBoolType();
8321
8322 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008323 case UO_Deref:
8324 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00008325 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008326
8327 default:
8328 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8329 }
8330 }
8331
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008332 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00008333 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8334
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008335 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00008336 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00008337 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00008338
Eli Friedmane6d33952013-07-08 20:20:06 +00008339 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008340}
John McCall263a48b2010-01-04 23:31:57 +00008341
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008342IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008343 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00008344}
8345
John McCall263a48b2010-01-04 23:31:57 +00008346/// Checks whether the given value, which currently has the given
8347/// source semantics, has the same value when coerced through the
8348/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008349bool IsSameFloatAfterCast(const llvm::APFloat &value,
8350 const llvm::fltSemantics &Src,
8351 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008352 llvm::APFloat truncated = value;
8353
8354 bool ignored;
8355 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8356 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8357
8358 return truncated.bitwiseIsEqual(value);
8359}
8360
8361/// Checks whether the given value, which currently has the given
8362/// source semantics, has the same value when coerced through the
8363/// target semantics.
8364///
8365/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008366bool IsSameFloatAfterCast(const APValue &value,
8367 const llvm::fltSemantics &Src,
8368 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008369 if (value.isFloat())
8370 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8371
8372 if (value.isVector()) {
8373 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8374 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8375 return false;
8376 return true;
8377 }
8378
8379 assert(value.isComplexFloat());
8380 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8381 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8382}
8383
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008384void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008385
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008386bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00008387 // Suppress cases where we are comparing against an enum constant.
8388 if (const DeclRefExpr *DR =
8389 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8390 if (isa<EnumConstantDecl>(DR->getDecl()))
8391 return false;
8392
8393 // Suppress cases where the '0' value is expanded from a macro.
8394 if (E->getLocStart().isMacroID())
8395 return false;
8396
John McCallcc7e5bf2010-05-06 08:58:33 +00008397 llvm::APSInt Value;
8398 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8399}
8400
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008401bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00008402 // Strip off implicit integral promotions.
8403 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008404 if (ICE->getCastKind() != CK_IntegralCast &&
8405 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00008406 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008407 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00008408 }
8409
8410 return E->getType()->isEnumeralType();
8411}
8412
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008413void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00008414 // Disable warning in template instantiations.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008415 if (S.inTemplateInstantiation())
Richard Trieu36594562013-11-01 21:47:19 +00008416 return;
8417
John McCalle3027922010-08-25 11:45:40 +00008418 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00008419 if (E->isValueDependent())
8420 return;
8421
John McCalle3027922010-08-25 11:45:40 +00008422 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008423 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008424 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008425 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008426 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008427 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008428 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008429 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008430 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008431 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008432 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008433 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008434 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008435 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008436 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008437 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8438 }
8439}
8440
Benjamin Kramer7320b992016-06-15 14:20:56 +00008441void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8442 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008443 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00008444 // Disable warning in template instantiations.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008445 if (S.inTemplateInstantiation())
Richard Trieudd51d742013-11-01 21:19:43 +00008446 return;
8447
Richard Trieu0f097742014-04-04 04:13:47 +00008448 // TODO: Investigate using GetExprRange() to get tighter bounds
8449 // on the bit ranges.
8450 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00008451 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00008452 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00008453 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8454 unsigned OtherWidth = OtherRange.Width;
8455
8456 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8457
Richard Trieu560910c2012-11-14 22:50:24 +00008458 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00008459 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00008460 return;
8461
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008462 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00008463 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008464
Richard Trieu0f097742014-04-04 04:13:47 +00008465 // Used for diagnostic printout.
8466 enum {
8467 LiteralConstant = 0,
8468 CXXBoolLiteralTrue,
8469 CXXBoolLiteralFalse
8470 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008471
Richard Trieu0f097742014-04-04 04:13:47 +00008472 if (!OtherIsBooleanType) {
8473 QualType ConstantT = Constant->getType();
8474 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00008475
Richard Trieu0f097742014-04-04 04:13:47 +00008476 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8477 return;
8478 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8479 "comparison with non-integer type");
8480
8481 bool ConstantSigned = ConstantT->isSignedIntegerType();
8482 bool CommonSigned = CommonT->isSignedIntegerType();
8483
8484 bool EqualityOnly = false;
8485
8486 if (CommonSigned) {
8487 // The common type is signed, therefore no signed to unsigned conversion.
8488 if (!OtherRange.NonNegative) {
8489 // Check that the constant is representable in type OtherT.
8490 if (ConstantSigned) {
8491 if (OtherWidth >= Value.getMinSignedBits())
8492 return;
8493 } else { // !ConstantSigned
8494 if (OtherWidth >= Value.getActiveBits() + 1)
8495 return;
8496 }
8497 } else { // !OtherSigned
8498 // Check that the constant is representable in type OtherT.
8499 // Negative values are out of range.
8500 if (ConstantSigned) {
8501 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8502 return;
8503 } else { // !ConstantSigned
8504 if (OtherWidth >= Value.getActiveBits())
8505 return;
8506 }
Richard Trieu560910c2012-11-14 22:50:24 +00008507 }
Richard Trieu0f097742014-04-04 04:13:47 +00008508 } else { // !CommonSigned
8509 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00008510 if (OtherWidth >= Value.getActiveBits())
8511 return;
Craig Toppercf360162014-06-18 05:13:11 +00008512 } else { // OtherSigned
8513 assert(!ConstantSigned &&
8514 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00008515 // Check to see if the constant is representable in OtherT.
8516 if (OtherWidth > Value.getActiveBits())
8517 return;
8518 // Check to see if the constant is equivalent to a negative value
8519 // cast to CommonT.
8520 if (S.Context.getIntWidth(ConstantT) ==
8521 S.Context.getIntWidth(CommonT) &&
8522 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8523 return;
8524 // The constant value rests between values that OtherT can represent
8525 // after conversion. Relational comparison still works, but equality
8526 // comparisons will be tautological.
8527 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008528 }
8529 }
Richard Trieu0f097742014-04-04 04:13:47 +00008530
8531 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8532
8533 if (op == BO_EQ || op == BO_NE) {
8534 IsTrue = op == BO_NE;
8535 } else if (EqualityOnly) {
8536 return;
8537 } else if (RhsConstant) {
8538 if (op == BO_GT || op == BO_GE)
8539 IsTrue = !PositiveConstant;
8540 else // op == BO_LT || op == BO_LE
8541 IsTrue = PositiveConstant;
8542 } else {
8543 if (op == BO_LT || op == BO_LE)
8544 IsTrue = !PositiveConstant;
8545 else // op == BO_GT || op == BO_GE
8546 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008547 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008548 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00008549 // Other isKnownToHaveBooleanValue
8550 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8551 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8552 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8553
8554 static const struct LinkedConditions {
8555 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8556 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8557 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8558 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8559 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8560 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8561
8562 } TruthTable = {
8563 // Constant on LHS. | Constant on RHS. |
8564 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
8565 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8566 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8567 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8568 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8569 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8570 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8571 };
8572
8573 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8574
8575 enum ConstantValue ConstVal = Zero;
8576 if (Value.isUnsigned() || Value.isNonNegative()) {
8577 if (Value == 0) {
8578 LiteralOrBoolConstant =
8579 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8580 ConstVal = Zero;
8581 } else if (Value == 1) {
8582 LiteralOrBoolConstant =
8583 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8584 ConstVal = One;
8585 } else {
8586 LiteralOrBoolConstant = LiteralConstant;
8587 ConstVal = GT_One;
8588 }
8589 } else {
8590 ConstVal = LT_Zero;
8591 }
8592
8593 CompareBoolWithConstantResult CmpRes;
8594
8595 switch (op) {
8596 case BO_LT:
8597 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8598 break;
8599 case BO_GT:
8600 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8601 break;
8602 case BO_LE:
8603 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8604 break;
8605 case BO_GE:
8606 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8607 break;
8608 case BO_EQ:
8609 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8610 break;
8611 case BO_NE:
8612 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8613 break;
8614 default:
8615 CmpRes = Unkwn;
8616 break;
8617 }
8618
8619 if (CmpRes == AFals) {
8620 IsTrue = false;
8621 } else if (CmpRes == ATrue) {
8622 IsTrue = true;
8623 } else {
8624 return;
8625 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008626 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008627
8628 // If this is a comparison to an enum constant, include that
8629 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00008630 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008631 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8632 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8633
8634 SmallString<64> PrettySourceValue;
8635 llvm::raw_svector_ostream OS(PrettySourceValue);
8636 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00008637 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008638 else
8639 OS << Value;
8640
Richard Trieu0f097742014-04-04 04:13:47 +00008641 S.DiagRuntimeBehavior(
8642 E->getOperatorLoc(), E,
8643 S.PDiag(diag::warn_out_of_range_compare)
8644 << OS.str() << LiteralOrBoolConstant
8645 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8646 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008647}
8648
John McCallcc7e5bf2010-05-06 08:58:33 +00008649/// Analyze the operands of the given comparison. Implements the
8650/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008651void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00008652 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8653 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008654}
John McCall263a48b2010-01-04 23:31:57 +00008655
John McCallca01b222010-01-04 23:21:16 +00008656/// \brief Implements -Wsign-compare.
8657///
Richard Trieu82402a02011-09-15 21:56:47 +00008658/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008659void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008660 // The type the comparison is being performed in.
8661 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00008662
8663 // Only analyze comparison operators where both sides have been converted to
8664 // the same type.
8665 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8666 return AnalyzeImpConvsInComparison(S, E);
8667
8668 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00008669 if (E->isValueDependent())
8670 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008671
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008672 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8673 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008674
8675 bool IsComparisonConstant = false;
8676
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008677 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008678 // of 'true' or 'false'.
8679 if (T->isIntegralType(S.Context)) {
8680 llvm::APSInt RHSValue;
8681 bool IsRHSIntegralLiteral =
8682 RHS->isIntegerConstantExpr(RHSValue, S.Context);
8683 llvm::APSInt LHSValue;
8684 bool IsLHSIntegralLiteral =
8685 LHS->isIntegerConstantExpr(LHSValue, S.Context);
8686 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8687 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8688 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8689 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8690 else
8691 IsComparisonConstant =
8692 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008693 } else if (!T->hasUnsignedIntegerRepresentation())
8694 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008695
John McCallcc7e5bf2010-05-06 08:58:33 +00008696 // We don't do anything special if this isn't an unsigned integral
8697 // comparison: we're only interested in integral comparisons, and
8698 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00008699 //
8700 // We also don't care about value-dependent expressions or expressions
8701 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008702 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00008703 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008704
John McCallcc7e5bf2010-05-06 08:58:33 +00008705 // Check to see if one of the (unmodified) operands is of different
8706 // signedness.
8707 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00008708 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8709 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00008710 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00008711 signedOperand = LHS;
8712 unsignedOperand = RHS;
8713 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8714 signedOperand = RHS;
8715 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00008716 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00008717 CheckTrivialUnsignedComparison(S, E);
8718 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008719 }
8720
John McCallcc7e5bf2010-05-06 08:58:33 +00008721 // Otherwise, calculate the effective range of the signed operand.
8722 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00008723
John McCallcc7e5bf2010-05-06 08:58:33 +00008724 // Go ahead and analyze implicit conversions in the operands. Note
8725 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00008726 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8727 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00008728
John McCallcc7e5bf2010-05-06 08:58:33 +00008729 // If the signed range is non-negative, -Wsign-compare won't fire,
8730 // but we should still check for comparisons which are always true
8731 // or false.
8732 if (signedRange.NonNegative)
8733 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008734
8735 // For (in)equality comparisons, if the unsigned operand is a
8736 // constant which cannot collide with a overflowed signed operand,
8737 // then reinterpreting the signed operand as unsigned will not
8738 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00008739 if (E->isEqualityOp()) {
8740 unsigned comparisonWidth = S.Context.getIntWidth(T);
8741 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00008742
John McCallcc7e5bf2010-05-06 08:58:33 +00008743 // We should never be unable to prove that the unsigned operand is
8744 // non-negative.
8745 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8746
8747 if (unsignedRange.Width < comparisonWidth)
8748 return;
8749 }
8750
Douglas Gregorbfb4a212012-05-01 01:53:49 +00008751 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8752 S.PDiag(diag::warn_mixed_sign_comparison)
8753 << LHS->getType() << RHS->getType()
8754 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00008755}
8756
John McCall1f425642010-11-11 03:21:53 +00008757/// Analyzes an attempt to assign the given value to a bitfield.
8758///
8759/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008760bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8761 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00008762 assert(Bitfield->isBitField());
8763 if (Bitfield->isInvalidDecl())
8764 return false;
8765
John McCalldeebbcf2010-11-11 05:33:51 +00008766 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00008767 QualType BitfieldType = Bitfield->getType();
8768 if (BitfieldType->isBooleanType())
8769 return false;
8770
8771 if (BitfieldType->isEnumeralType()) {
8772 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
8773 // If the underlying enum type was not explicitly specified as an unsigned
8774 // type and the enum contain only positive values, MSVC++ will cause an
8775 // inconsistency by storing this as a signed type.
8776 if (S.getLangOpts().CPlusPlus11 &&
8777 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
8778 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
8779 BitfieldEnumDecl->getNumNegativeBits() == 0) {
8780 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
8781 << BitfieldEnumDecl->getNameAsString();
8782 }
8783 }
8784
John McCalldeebbcf2010-11-11 05:33:51 +00008785 if (Bitfield->getType()->isBooleanType())
8786 return false;
8787
Douglas Gregor789adec2011-02-04 13:09:01 +00008788 // Ignore value- or type-dependent expressions.
8789 if (Bitfield->getBitWidth()->isValueDependent() ||
8790 Bitfield->getBitWidth()->isTypeDependent() ||
8791 Init->isValueDependent() ||
8792 Init->isTypeDependent())
8793 return false;
8794
John McCall1f425642010-11-11 03:21:53 +00008795 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00008796 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00008797
Richard Smith5fab0c92011-12-28 19:48:30 +00008798 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00008799 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
8800 Expr::SE_AllowSideEffects)) {
8801 // The RHS is not constant. If the RHS has an enum type, make sure the
8802 // bitfield is wide enough to hold all the values of the enum without
8803 // truncation.
8804 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
8805 EnumDecl *ED = EnumTy->getDecl();
8806 bool SignedBitfield = BitfieldType->isSignedIntegerType();
8807
8808 // Enum types are implicitly signed on Windows, so check if there are any
8809 // negative enumerators to see if the enum was intended to be signed or
8810 // not.
8811 bool SignedEnum = ED->getNumNegativeBits() > 0;
8812
8813 // Check for surprising sign changes when assigning enum values to a
8814 // bitfield of different signedness. If the bitfield is signed and we
8815 // have exactly the right number of bits to store this unsigned enum,
8816 // suggest changing the enum to an unsigned type. This typically happens
8817 // on Windows where unfixed enums always use an underlying type of 'int'.
8818 unsigned DiagID = 0;
8819 if (SignedEnum && !SignedBitfield) {
8820 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
8821 } else if (SignedBitfield && !SignedEnum &&
8822 ED->getNumPositiveBits() == FieldWidth) {
8823 DiagID = diag::warn_signed_bitfield_enum_conversion;
8824 }
8825
8826 if (DiagID) {
8827 S.Diag(InitLoc, DiagID) << Bitfield << ED;
8828 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
8829 SourceRange TypeRange =
8830 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
8831 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
8832 << SignedEnum << TypeRange;
8833 }
8834
8835 // Compute the required bitwidth. If the enum has negative values, we need
8836 // one more bit than the normal number of positive bits to represent the
8837 // sign bit.
8838 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
8839 ED->getNumNegativeBits())
8840 : ED->getNumPositiveBits();
8841
8842 // Check the bitwidth.
8843 if (BitsNeeded > FieldWidth) {
8844 Expr *WidthExpr = Bitfield->getBitWidth();
8845 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
8846 << Bitfield << ED;
8847 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
8848 << BitsNeeded << ED << WidthExpr->getSourceRange();
8849 }
8850 }
8851
John McCall1f425642010-11-11 03:21:53 +00008852 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00008853 }
John McCall1f425642010-11-11 03:21:53 +00008854
John McCall1f425642010-11-11 03:21:53 +00008855 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00008856
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008857 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00008858 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008859 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8860 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00008861
John McCall1f425642010-11-11 03:21:53 +00008862 if (OriginalWidth <= FieldWidth)
8863 return false;
8864
Eli Friedmanc267a322012-01-26 23:11:39 +00008865 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00008866 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00008867 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00008868
Eli Friedmanc267a322012-01-26 23:11:39 +00008869 // Check whether the stored value is equal to the original value.
8870 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00008871 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00008872 return false;
8873
Eli Friedmanc267a322012-01-26 23:11:39 +00008874 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00008875 // therefore don't strictly fit into a signed bitfield of width 1.
8876 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00008877 return false;
8878
John McCall1f425642010-11-11 03:21:53 +00008879 std::string PrettyValue = Value.toString(10);
8880 std::string PrettyTrunc = TruncatedValue.toString(10);
8881
8882 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8883 << PrettyValue << PrettyTrunc << OriginalInit->getType()
8884 << Init->getSourceRange();
8885
8886 return true;
8887}
8888
John McCalld2a53122010-11-09 23:24:47 +00008889/// Analyze the given simple or compound assignment for warning-worthy
8890/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008891void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00008892 // Just recurse on the LHS.
8893 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8894
8895 // We want to recurse on the RHS as normal unless we're assigning to
8896 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00008897 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008898 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00008899 E->getOperatorLoc())) {
8900 // Recurse, ignoring any implicit conversions on the RHS.
8901 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8902 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00008903 }
8904 }
8905
8906 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8907}
8908
John McCall263a48b2010-01-04 23:31:57 +00008909/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008910void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8911 SourceLocation CContext, unsigned diag,
8912 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008913 if (pruneControlFlow) {
8914 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8915 S.PDiag(diag)
8916 << SourceType << T << E->getSourceRange()
8917 << SourceRange(CContext));
8918 return;
8919 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00008920 S.Diag(E->getExprLoc(), diag)
8921 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8922}
8923
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008924/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008925void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8926 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008927 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008928}
8929
Richard Trieube234c32016-04-21 21:04:55 +00008930
8931/// Diagnose an implicit cast from a floating point value to an integer value.
8932void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8933
8934 SourceLocation CContext) {
8935 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00008936 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00008937
8938 Expr *InnerE = E->IgnoreParenImpCasts();
8939 // We also want to warn on, e.g., "int i = -1.234"
8940 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8941 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8942 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8943
8944 const bool IsLiteral =
8945 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8946
8947 llvm::APFloat Value(0.0);
8948 bool IsConstant =
8949 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8950 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00008951 return DiagnoseImpCast(S, E, T, CContext,
8952 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00008953 }
8954
Chandler Carruth016ef402011-04-10 08:36:24 +00008955 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00008956
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00008957 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8958 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00008959 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8960 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00008961 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00008962 if (IsLiteral) return;
8963 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8964 PruneWarnings);
8965 }
8966
8967 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00008968 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00008969 // Warn on floating point literal to integer.
8970 DiagID = diag::warn_impcast_literal_float_to_integer;
8971 } else if (IntegerValue == 0) {
8972 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
8973 return DiagnoseImpCast(S, E, T, CContext,
8974 diag::warn_impcast_float_integer, PruneWarnings);
8975 }
8976 // Warn on non-zero to zero conversion.
8977 DiagID = diag::warn_impcast_float_to_integer_zero;
8978 } else {
8979 if (IntegerValue.isUnsigned()) {
8980 if (!IntegerValue.isMaxValue()) {
8981 return DiagnoseImpCast(S, E, T, CContext,
8982 diag::warn_impcast_float_integer, PruneWarnings);
8983 }
8984 } else { // IntegerValue.isSigned()
8985 if (!IntegerValue.isMaxSignedValue() &&
8986 !IntegerValue.isMinSignedValue()) {
8987 return DiagnoseImpCast(S, E, T, CContext,
8988 diag::warn_impcast_float_integer, PruneWarnings);
8989 }
8990 }
8991 // Warn on evaluatable floating point expression to integer conversion.
8992 DiagID = diag::warn_impcast_float_to_integer;
8993 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008994
Eli Friedman07185912013-08-29 23:44:43 +00008995 // FIXME: Force the precision of the source value down so we don't print
8996 // digits which are usually useless (we don't really care here if we
8997 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
8998 // would automatically print the shortest representation, but it's a bit
8999 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00009000 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00009001 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9002 precision = (precision * 59 + 195) / 196;
9003 Value.toString(PrettySourceValue, precision);
9004
David Blaikie9b88cc02012-05-15 17:18:27 +00009005 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00009006 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00009007 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00009008 else
David Blaikie9b88cc02012-05-15 17:18:27 +00009009 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00009010
Richard Trieube234c32016-04-21 21:04:55 +00009011 if (PruneWarnings) {
9012 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9013 S.PDiag(DiagID)
9014 << E->getType() << T.getUnqualifiedType()
9015 << PrettySourceValue << PrettyTargetValue
9016 << E->getSourceRange() << SourceRange(CContext));
9017 } else {
9018 S.Diag(E->getExprLoc(), DiagID)
9019 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9020 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9021 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009022}
9023
John McCall18a2c2c2010-11-09 22:22:12 +00009024std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
9025 if (!Range.Width) return "0";
9026
9027 llvm::APSInt ValueInRange = Value;
9028 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00009029 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00009030 return ValueInRange.toString(10);
9031}
9032
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009033bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009034 if (!isa<ImplicitCastExpr>(Ex))
9035 return false;
9036
9037 Expr *InnerE = Ex->IgnoreParenImpCasts();
9038 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9039 const Type *Source =
9040 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9041 if (Target->isDependentType())
9042 return false;
9043
9044 const BuiltinType *FloatCandidateBT =
9045 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9046 const Type *BoolCandidateType = ToBool ? Target : Source;
9047
9048 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9049 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9050}
9051
9052void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9053 SourceLocation CC) {
9054 unsigned NumArgs = TheCall->getNumArgs();
9055 for (unsigned i = 0; i < NumArgs; ++i) {
9056 Expr *CurrA = TheCall->getArg(i);
9057 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9058 continue;
9059
9060 bool IsSwapped = ((i > 0) &&
9061 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9062 IsSwapped |= ((i < (NumArgs - 1)) &&
9063 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9064 if (IsSwapped) {
9065 // Warn on this floating-point to bool conversion.
9066 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9067 CurrA->getType(), CC,
9068 diag::warn_impcast_floating_point_to_bool);
9069 }
9070 }
9071}
9072
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009073void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009074 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9075 E->getExprLoc()))
9076 return;
9077
Richard Trieu09d6b802016-01-08 23:35:06 +00009078 // Don't warn on functions which have return type nullptr_t.
9079 if (isa<CallExpr>(E))
9080 return;
9081
Richard Trieu5b993502014-10-15 03:42:06 +00009082 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9083 const Expr::NullPointerConstantKind NullKind =
9084 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9085 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9086 return;
9087
9088 // Return if target type is a safe conversion.
9089 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9090 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9091 return;
9092
9093 SourceLocation Loc = E->getSourceRange().getBegin();
9094
Richard Trieu0a5e1662016-02-13 00:58:53 +00009095 // Venture through the macro stacks to get to the source of macro arguments.
9096 // The new location is a better location than the complete location that was
9097 // passed in.
9098 while (S.SourceMgr.isMacroArgExpansion(Loc))
9099 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
9100
9101 while (S.SourceMgr.isMacroArgExpansion(CC))
9102 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
9103
Richard Trieu5b993502014-10-15 03:42:06 +00009104 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00009105 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9106 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9107 Loc, S.SourceMgr, S.getLangOpts());
9108 if (MacroName == "NULL")
9109 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00009110 }
9111
9112 // Only warn if the null and context location are in the same macro expansion.
9113 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9114 return;
9115
9116 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9117 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
9118 << FixItHint::CreateReplacement(Loc,
9119 S.getFixItZeroLiteralForType(T, Loc));
9120}
9121
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009122void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9123 ObjCArrayLiteral *ArrayLiteral);
9124void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9125 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00009126
9127/// Check a single element within a collection literal against the
9128/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009129void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
9130 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009131 // Skip a bitcast to 'id' or qualified 'id'.
9132 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9133 if (ICE->getCastKind() == CK_BitCast &&
9134 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9135 Element = ICE->getSubExpr();
9136 }
9137
9138 QualType ElementType = Element->getType();
9139 ExprResult ElementResult(Element);
9140 if (ElementType->getAs<ObjCObjectPointerType>() &&
9141 S.CheckSingleAssignmentConstraints(TargetElementType,
9142 ElementResult,
9143 false, false)
9144 != Sema::Compatible) {
9145 S.Diag(Element->getLocStart(),
9146 diag::warn_objc_collection_literal_element)
9147 << ElementType << ElementKind << TargetElementType
9148 << Element->getSourceRange();
9149 }
9150
9151 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9152 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9153 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9154 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9155}
9156
9157/// Check an Objective-C array literal being converted to the given
9158/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009159void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9160 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009161 if (!S.NSArrayDecl)
9162 return;
9163
9164 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9165 if (!TargetObjCPtr)
9166 return;
9167
9168 if (TargetObjCPtr->isUnspecialized() ||
9169 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9170 != S.NSArrayDecl->getCanonicalDecl())
9171 return;
9172
9173 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9174 if (TypeArgs.size() != 1)
9175 return;
9176
9177 QualType TargetElementType = TypeArgs[0];
9178 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9179 checkObjCCollectionLiteralElement(S, TargetElementType,
9180 ArrayLiteral->getElement(I),
9181 0);
9182 }
9183}
9184
9185/// Check an Objective-C dictionary literal being converted to the given
9186/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009187void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9188 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009189 if (!S.NSDictionaryDecl)
9190 return;
9191
9192 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9193 if (!TargetObjCPtr)
9194 return;
9195
9196 if (TargetObjCPtr->isUnspecialized() ||
9197 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9198 != S.NSDictionaryDecl->getCanonicalDecl())
9199 return;
9200
9201 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9202 if (TypeArgs.size() != 2)
9203 return;
9204
9205 QualType TargetKeyType = TypeArgs[0];
9206 QualType TargetObjectType = TypeArgs[1];
9207 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9208 auto Element = DictionaryLiteral->getKeyValueElement(I);
9209 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9210 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9211 }
9212}
9213
Richard Trieufc404c72016-02-05 23:02:38 +00009214// Helper function to filter out cases for constant width constant conversion.
9215// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009216bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9217 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00009218 // If initializing from a constant, and the constant starts with '0',
9219 // then it is a binary, octal, or hexadecimal. Allow these constants
9220 // to fill all the bits, even if there is a sign change.
9221 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9222 const char FirstLiteralCharacter =
9223 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9224 if (FirstLiteralCharacter == '0')
9225 return false;
9226 }
9227
9228 // If the CC location points to a '{', and the type is char, then assume
9229 // assume it is an array initialization.
9230 if (CC.isValid() && T->isCharType()) {
9231 const char FirstContextCharacter =
9232 S.getSourceManager().getCharacterData(CC)[0];
9233 if (FirstContextCharacter == '{')
9234 return false;
9235 }
9236
9237 return true;
9238}
9239
John McCallcc7e5bf2010-05-06 08:58:33 +00009240void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00009241 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009242 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00009243
John McCallcc7e5bf2010-05-06 08:58:33 +00009244 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9245 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9246 if (Source == Target) return;
9247 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00009248
Chandler Carruthc22845a2011-07-26 05:40:03 +00009249 // If the conversion context location is invalid don't complain. We also
9250 // don't want to emit a warning if the issue occurs from the expansion of
9251 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9252 // delay this check as long as possible. Once we detect we are in that
9253 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009254 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00009255 return;
9256
Richard Trieu021baa32011-09-23 20:10:00 +00009257 // Diagnose implicit casts to bool.
9258 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9259 if (isa<StringLiteral>(E))
9260 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00009261 // and expressions, for instance, assert(0 && "error here"), are
9262 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00009263 return DiagnoseImpCast(S, E, T, CC,
9264 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00009265 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9266 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9267 // This covers the literal expressions that evaluate to Objective-C
9268 // objects.
9269 return DiagnoseImpCast(S, E, T, CC,
9270 diag::warn_impcast_objective_c_literal_to_bool);
9271 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009272 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9273 // Warn on pointer to bool conversion that is always true.
9274 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9275 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00009276 }
Richard Trieu021baa32011-09-23 20:10:00 +00009277 }
John McCall263a48b2010-01-04 23:31:57 +00009278
Douglas Gregor5054cb02015-07-07 03:58:22 +00009279 // Check implicit casts from Objective-C collection literals to specialized
9280 // collection types, e.g., NSArray<NSString *> *.
9281 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9282 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9283 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9284 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9285
John McCall263a48b2010-01-04 23:31:57 +00009286 // Strip vector types.
9287 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009288 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009289 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009290 return;
John McCallacf0ee52010-10-08 02:01:28 +00009291 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009292 }
Chris Lattneree7286f2011-06-14 04:51:15 +00009293
9294 // If the vector cast is cast between two vectors of the same size, it is
9295 // a bitcast, not a conversion.
9296 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9297 return;
John McCall263a48b2010-01-04 23:31:57 +00009298
9299 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9300 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9301 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00009302 if (auto VecTy = dyn_cast<VectorType>(Target))
9303 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00009304
9305 // Strip complex types.
9306 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009307 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009308 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009309 return;
9310
John McCallacf0ee52010-10-08 02:01:28 +00009311 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009312 }
John McCall263a48b2010-01-04 23:31:57 +00009313
9314 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9315 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9316 }
9317
9318 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9319 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9320
9321 // If the source is floating point...
9322 if (SourceBT && SourceBT->isFloatingPoint()) {
9323 // ...and the target is floating point...
9324 if (TargetBT && TargetBT->isFloatingPoint()) {
9325 // ...then warn if we're dropping FP rank.
9326
9327 // Builtin FP kinds are ordered by increasing FP rank.
9328 if (SourceBT->getKind() > TargetBT->getKind()) {
9329 // Don't warn about float constants that are precisely
9330 // representable in the target type.
9331 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009332 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00009333 // Value might be a float, a float vector, or a float complex.
9334 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00009335 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9336 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00009337 return;
9338 }
9339
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009340 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009341 return;
9342
John McCallacf0ee52010-10-08 02:01:28 +00009343 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00009344 }
9345 // ... or possibly if we're increasing rank, too
9346 else if (TargetBT->getKind() > SourceBT->getKind()) {
9347 if (S.SourceMgr.isInSystemMacro(CC))
9348 return;
9349
9350 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00009351 }
9352 return;
9353 }
9354
Richard Trieube234c32016-04-21 21:04:55 +00009355 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00009356 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009357 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009358 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00009359
Richard Trieube234c32016-04-21 21:04:55 +00009360 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00009361 }
John McCall263a48b2010-01-04 23:31:57 +00009362
Richard Smith54894fd2015-12-30 01:06:52 +00009363 // Detect the case where a call result is converted from floating-point to
9364 // to bool, and the final argument to the call is converted from bool, to
9365 // discover this typo:
9366 //
9367 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9368 //
9369 // FIXME: This is an incredibly special case; is there some more general
9370 // way to detect this class of misplaced-parentheses bug?
9371 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009372 // Check last argument of function call to see if it is an
9373 // implicit cast from a type matching the type the result
9374 // is being cast to.
9375 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00009376 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009377 Expr *LastA = CEx->getArg(NumArgs - 1);
9378 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00009379 if (isa<ImplicitCastExpr>(LastA) &&
9380 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009381 // Warn on this floating-point to bool conversion
9382 DiagnoseImpCast(S, E, T, CC,
9383 diag::warn_impcast_floating_point_to_bool);
9384 }
9385 }
9386 }
John McCall263a48b2010-01-04 23:31:57 +00009387 return;
9388 }
9389
Richard Trieu5b993502014-10-15 03:42:06 +00009390 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00009391
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009392 S.DiscardMisalignedMemberAddress(Target, E);
9393
David Blaikie9366d2b2012-06-19 21:19:06 +00009394 if (!Source->isIntegerType() || !Target->isIntegerType())
9395 return;
9396
David Blaikie7555b6a2012-05-15 16:56:36 +00009397 // TODO: remove this early return once the false positives for constant->bool
9398 // in templates, macros, etc, are reduced or removed.
9399 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9400 return;
9401
John McCallcc7e5bf2010-05-06 08:58:33 +00009402 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00009403 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00009404
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009405 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00009406 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009407 // TODO: this should happen for bitfield stores, too.
9408 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00009409 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009410 if (S.SourceMgr.isInSystemMacro(CC))
9411 return;
9412
John McCall18a2c2c2010-11-09 22:22:12 +00009413 std::string PrettySourceValue = Value.toString(10);
9414 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009415
Ted Kremenek33ba9952011-10-22 02:37:33 +00009416 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9417 S.PDiag(diag::warn_impcast_integer_precision_constant)
9418 << PrettySourceValue << PrettyTargetValue
9419 << E->getType() << T << E->getSourceRange()
9420 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00009421 return;
9422 }
9423
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009424 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9425 if (S.SourceMgr.isInSystemMacro(CC))
9426 return;
9427
David Blaikie9455da02012-04-12 22:40:54 +00009428 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00009429 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9430 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00009431 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00009432 }
9433
Richard Trieudcb55572016-01-29 23:51:16 +00009434 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9435 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9436 // Warn when doing a signed to signed conversion, warn if the positive
9437 // source value is exactly the width of the target type, which will
9438 // cause a negative value to be stored.
9439
9440 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00009441 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9442 !S.SourceMgr.isInSystemMacro(CC)) {
9443 if (isSameWidthConstantConversion(S, E, T, CC)) {
9444 std::string PrettySourceValue = Value.toString(10);
9445 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00009446
Richard Trieufc404c72016-02-05 23:02:38 +00009447 S.DiagRuntimeBehavior(
9448 E->getExprLoc(), E,
9449 S.PDiag(diag::warn_impcast_integer_precision_constant)
9450 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9451 << E->getSourceRange() << clang::SourceRange(CC));
9452 return;
Richard Trieudcb55572016-01-29 23:51:16 +00009453 }
9454 }
Richard Trieufc404c72016-02-05 23:02:38 +00009455
Richard Trieudcb55572016-01-29 23:51:16 +00009456 // Fall through for non-constants to give a sign conversion warning.
9457 }
9458
John McCallcc7e5bf2010-05-06 08:58:33 +00009459 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9460 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9461 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009462 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009463 return;
9464
John McCallcc7e5bf2010-05-06 08:58:33 +00009465 unsigned DiagID = diag::warn_impcast_integer_sign;
9466
9467 // Traditionally, gcc has warned about this under -Wsign-compare.
9468 // We also want to warn about it in -Wconversion.
9469 // So if -Wconversion is off, use a completely identical diagnostic
9470 // in the sign-compare group.
9471 // The conditional-checking code will
9472 if (ICContext) {
9473 DiagID = diag::warn_impcast_integer_sign_conditional;
9474 *ICContext = true;
9475 }
9476
John McCallacf0ee52010-10-08 02:01:28 +00009477 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00009478 }
9479
Douglas Gregora78f1932011-02-22 02:45:07 +00009480 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00009481 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9482 // type, to give us better diagnostics.
9483 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009484 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00009485 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9486 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9487 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9488 SourceType = S.Context.getTypeDeclType(Enum);
9489 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9490 }
9491 }
9492
Douglas Gregora78f1932011-02-22 02:45:07 +00009493 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9494 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00009495 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9496 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009497 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009498 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009499 return;
9500
Douglas Gregor364f7db2011-03-12 00:14:31 +00009501 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00009502 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009503 }
John McCall263a48b2010-01-04 23:31:57 +00009504}
9505
David Blaikie18e9ac72012-05-15 21:57:38 +00009506void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9507 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009508
9509void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00009510 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009511 E = E->IgnoreParenImpCasts();
9512
9513 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00009514 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009515
John McCallacf0ee52010-10-08 02:01:28 +00009516 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009517 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009518 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00009519}
9520
David Blaikie18e9ac72012-05-15 21:57:38 +00009521void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9522 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00009523 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009524
9525 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00009526 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9527 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009528
9529 // If -Wconversion would have warned about either of the candidates
9530 // for a signedness conversion to the context type...
9531 if (!Suspicious) return;
9532
9533 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009534 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00009535 return;
9536
John McCallcc7e5bf2010-05-06 08:58:33 +00009537 // ...then check whether it would have warned about either of the
9538 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00009539 if (E->getType() == T) return;
9540
9541 Suspicious = false;
9542 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9543 E->getType(), CC, &Suspicious);
9544 if (!Suspicious)
9545 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00009546 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009547}
9548
Richard Trieu65724892014-11-15 06:37:39 +00009549/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9550/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009551void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00009552 if (S.getLangOpts().Bool)
9553 return;
9554 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9555}
9556
John McCallcc7e5bf2010-05-06 08:58:33 +00009557/// AnalyzeImplicitConversions - Find and report any interesting
9558/// implicit conversions in the given expression. There are a couple
9559/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009560void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00009561 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00009562 Expr *E = OrigE->IgnoreParenImpCasts();
9563
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00009564 if (E->isTypeDependent() || E->isValueDependent())
9565 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00009566
John McCallcc7e5bf2010-05-06 08:58:33 +00009567 // For conditional operators, we analyze the arguments as if they
9568 // were being fed directly into the output.
9569 if (isa<ConditionalOperator>(E)) {
9570 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00009571 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009572 return;
9573 }
9574
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009575 // Check implicit argument conversions for function calls.
9576 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9577 CheckImplicitArgumentConversions(S, Call, CC);
9578
John McCallcc7e5bf2010-05-06 08:58:33 +00009579 // Go ahead and check any implicit conversions we might have skipped.
9580 // The non-canonical typecheck is just an optimization;
9581 // CheckImplicitConversion will filter out dead implicit conversions.
9582 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009583 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009584
9585 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00009586
9587 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9588 // The bound subexpressions in a PseudoObjectExpr are not reachable
9589 // as transitive children.
9590 // FIXME: Use a more uniform representation for this.
9591 for (auto *SE : POE->semantics())
9592 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9593 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00009594 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00009595
John McCallcc7e5bf2010-05-06 08:58:33 +00009596 // Skip past explicit casts.
9597 if (isa<ExplicitCastExpr>(E)) {
9598 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00009599 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009600 }
9601
John McCalld2a53122010-11-09 23:24:47 +00009602 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9603 // Do a somewhat different check with comparison operators.
9604 if (BO->isComparisonOp())
9605 return AnalyzeComparison(S, BO);
9606
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009607 // And with simple assignments.
9608 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00009609 return AnalyzeAssignment(S, BO);
9610 }
John McCallcc7e5bf2010-05-06 08:58:33 +00009611
9612 // These break the otherwise-useful invariant below. Fortunately,
9613 // we don't really need to recurse into them, because any internal
9614 // expressions should have been analyzed already when they were
9615 // built into statements.
9616 if (isa<StmtExpr>(E)) return;
9617
9618 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00009619 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00009620
9621 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00009622 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00009623 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00009624 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00009625 for (Stmt *SubStmt : E->children()) {
9626 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00009627 if (!ChildExpr)
9628 continue;
9629
Richard Trieu955231d2014-01-25 01:10:35 +00009630 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00009631 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00009632 // Ignore checking string literals that are in logical and operators.
9633 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00009634 continue;
9635 AnalyzeImplicitConversions(S, ChildExpr, CC);
9636 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009637
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009638 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00009639 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9640 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009641 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00009642
9643 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9644 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009645 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009646 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009647
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009648 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9649 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00009650 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009651}
9652
9653} // end anonymous namespace
9654
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009655/// Diagnose integer type and any valid implicit convertion to it.
9656static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9657 // Taking into account implicit conversions,
9658 // allow any integer.
9659 if (!E->getType()->isIntegerType()) {
9660 S.Diag(E->getLocStart(),
9661 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9662 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009663 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009664 // Potentially emit standard warnings for implicit conversions if enabled
9665 // using -Wconversion.
9666 CheckImplicitConversion(S, E, IntT, E->getLocStart());
9667 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009668}
9669
Richard Trieuc1888e02014-06-28 23:25:37 +00009670// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9671// Returns true when emitting a warning about taking the address of a reference.
9672static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00009673 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00009674 E = E->IgnoreParenImpCasts();
9675
9676 const FunctionDecl *FD = nullptr;
9677
9678 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9679 if (!DRE->getDecl()->getType()->isReferenceType())
9680 return false;
9681 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9682 if (!M->getMemberDecl()->getType()->isReferenceType())
9683 return false;
9684 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00009685 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00009686 return false;
9687 FD = Call->getDirectCallee();
9688 } else {
9689 return false;
9690 }
9691
9692 SemaRef.Diag(E->getExprLoc(), PD);
9693
9694 // If possible, point to location of function.
9695 if (FD) {
9696 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9697 }
9698
9699 return true;
9700}
9701
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009702// Returns true if the SourceLocation is expanded from any macro body.
9703// Returns false if the SourceLocation is invalid, is from not in a macro
9704// expansion, or is from expanded from a top-level macro argument.
9705static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9706 if (Loc.isInvalid())
9707 return false;
9708
9709 while (Loc.isMacroID()) {
9710 if (SM.isMacroBodyExpansion(Loc))
9711 return true;
9712 Loc = SM.getImmediateMacroCallerLoc(Loc);
9713 }
9714
9715 return false;
9716}
9717
Richard Trieu3bb8b562014-02-26 02:36:06 +00009718/// \brief Diagnose pointers that are always non-null.
9719/// \param E the expression containing the pointer
9720/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9721/// compared to a null pointer
9722/// \param IsEqual True when the comparison is equal to a null pointer
9723/// \param Range Extra SourceRange to highlight in the diagnostic
9724void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9725 Expr::NullPointerConstantKind NullKind,
9726 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00009727 if (!E)
9728 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009729
9730 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009731 if (E->getExprLoc().isMacroID()) {
9732 const SourceManager &SM = getSourceManager();
9733 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9734 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00009735 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009736 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009737 E = E->IgnoreImpCasts();
9738
9739 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9740
Richard Trieuf7432752014-06-06 21:39:26 +00009741 if (isa<CXXThisExpr>(E)) {
9742 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9743 : diag::warn_this_bool_conversion;
9744 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9745 return;
9746 }
9747
Richard Trieu3bb8b562014-02-26 02:36:06 +00009748 bool IsAddressOf = false;
9749
9750 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9751 if (UO->getOpcode() != UO_AddrOf)
9752 return;
9753 IsAddressOf = true;
9754 E = UO->getSubExpr();
9755 }
9756
Richard Trieuc1888e02014-06-28 23:25:37 +00009757 if (IsAddressOf) {
9758 unsigned DiagID = IsCompare
9759 ? diag::warn_address_of_reference_null_compare
9760 : diag::warn_address_of_reference_bool_conversion;
9761 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9762 << IsEqual;
9763 if (CheckForReference(*this, E, PD)) {
9764 return;
9765 }
9766 }
9767
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009768 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9769 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00009770 std::string Str;
9771 llvm::raw_string_ostream S(Str);
9772 E->printPretty(S, nullptr, getPrintingPolicy());
9773 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9774 : diag::warn_cast_nonnull_to_bool;
9775 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9776 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009777 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00009778 };
9779
9780 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9781 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9782 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009783 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9784 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009785 return;
9786 }
9787 }
9788 }
9789
Richard Trieu3bb8b562014-02-26 02:36:06 +00009790 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00009791 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009792 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9793 D = R->getDecl();
9794 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9795 D = M->getMemberDecl();
9796 }
9797
9798 // Weak Decls can be null.
9799 if (!D || D->isWeak())
9800 return;
George Burgess IV850269a2015-12-08 22:02:00 +00009801
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009802 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00009803 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9804 if (getCurFunction() &&
9805 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009806 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9807 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009808 return;
9809 }
9810
9811 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +00009812 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +00009813 assert(ParamIter != FD->param_end());
9814 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9815
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009816 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9817 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009818 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +00009819 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009820 }
George Burgess IV850269a2015-12-08 22:02:00 +00009821
9822 for (unsigned ArgNo : NonNull->args()) {
9823 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009824 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009825 return;
9826 }
George Burgess IV850269a2015-12-08 22:02:00 +00009827 }
9828 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009829 }
9830 }
George Burgess IV850269a2015-12-08 22:02:00 +00009831 }
9832
Richard Trieu3bb8b562014-02-26 02:36:06 +00009833 QualType T = D->getType();
9834 const bool IsArray = T->isArrayType();
9835 const bool IsFunction = T->isFunctionType();
9836
Richard Trieuc1888e02014-06-28 23:25:37 +00009837 // Address of function is used to silence the function warning.
9838 if (IsAddressOf && IsFunction) {
9839 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009840 }
9841
9842 // Found nothing.
9843 if (!IsAddressOf && !IsFunction && !IsArray)
9844 return;
9845
9846 // Pretty print the expression for the diagnostic.
9847 std::string Str;
9848 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00009849 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00009850
9851 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9852 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00009853 enum {
9854 AddressOf,
9855 FunctionPointer,
9856 ArrayPointer
9857 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009858 if (IsAddressOf)
9859 DiagType = AddressOf;
9860 else if (IsFunction)
9861 DiagType = FunctionPointer;
9862 else if (IsArray)
9863 DiagType = ArrayPointer;
9864 else
9865 llvm_unreachable("Could not determine diagnostic.");
9866 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9867 << Range << IsEqual;
9868
9869 if (!IsFunction)
9870 return;
9871
9872 // Suggest '&' to silence the function warning.
9873 Diag(E->getExprLoc(), diag::note_function_warning_silence)
9874 << FixItHint::CreateInsertion(E->getLocStart(), "&");
9875
9876 // Check to see if '()' fixit should be emitted.
9877 QualType ReturnType;
9878 UnresolvedSet<4> NonTemplateOverloads;
9879 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9880 if (ReturnType.isNull())
9881 return;
9882
9883 if (IsCompare) {
9884 // There are two cases here. If there is null constant, the only suggest
9885 // for a pointer return type. If the null is 0, then suggest if the return
9886 // type is a pointer or an integer type.
9887 if (!ReturnType->isPointerType()) {
9888 if (NullKind == Expr::NPCK_ZeroExpression ||
9889 NullKind == Expr::NPCK_ZeroLiteral) {
9890 if (!ReturnType->isIntegerType())
9891 return;
9892 } else {
9893 return;
9894 }
9895 }
9896 } else { // !IsCompare
9897 // For function to bool, only suggest if the function pointer has bool
9898 // return type.
9899 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9900 return;
9901 }
9902 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00009903 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00009904}
9905
John McCallcc7e5bf2010-05-06 08:58:33 +00009906/// Diagnoses "dangerous" implicit conversions within the given
9907/// expression (which is a full expression). Implements -Wconversion
9908/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009909///
9910/// \param CC the "context" location of the implicit conversion, i.e.
9911/// the most location of the syntactic entity requiring the implicit
9912/// conversion
9913void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009914 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00009915 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00009916 return;
9917
9918 // Don't diagnose for value- or type-dependent expressions.
9919 if (E->isTypeDependent() || E->isValueDependent())
9920 return;
9921
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009922 // Check for array bounds violations in cases where the check isn't triggered
9923 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9924 // ArraySubscriptExpr is on the RHS of a variable initialization.
9925 CheckArrayAccess(E);
9926
John McCallacf0ee52010-10-08 02:01:28 +00009927 // This is not the right CC for (e.g.) a variable initialization.
9928 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009929}
9930
Richard Trieu65724892014-11-15 06:37:39 +00009931/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9932/// Input argument E is a logical expression.
9933void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9934 ::CheckBoolLikeConversion(*this, E, CC);
9935}
9936
Richard Smithc406cb72013-01-17 01:17:56 +00009937namespace {
9938/// \brief Visitor for expressions which looks for unsequenced operations on the
9939/// same object.
9940class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009941 typedef EvaluatedExprVisitor<SequenceChecker> Base;
9942
Richard Smithc406cb72013-01-17 01:17:56 +00009943 /// \brief A tree of sequenced regions within an expression. Two regions are
9944 /// unsequenced if one is an ancestor or a descendent of the other. When we
9945 /// finish processing an expression with sequencing, such as a comma
9946 /// expression, we fold its tree nodes into its parent, since they are
9947 /// unsequenced with respect to nodes we will visit later.
9948 class SequenceTree {
9949 struct Value {
9950 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9951 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +00009952 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +00009953 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009954 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00009955
9956 public:
9957 /// \brief A region within an expression which may be sequenced with respect
9958 /// to some other region.
9959 class Seq {
9960 explicit Seq(unsigned N) : Index(N) {}
9961 unsigned Index;
9962 friend class SequenceTree;
9963 public:
9964 Seq() : Index(0) {}
9965 };
9966
9967 SequenceTree() { Values.push_back(Value(0)); }
9968 Seq root() const { return Seq(0); }
9969
9970 /// \brief Create a new sequence of operations, which is an unsequenced
9971 /// subset of \p Parent. This sequence of operations is sequenced with
9972 /// respect to other children of \p Parent.
9973 Seq allocate(Seq Parent) {
9974 Values.push_back(Value(Parent.Index));
9975 return Seq(Values.size() - 1);
9976 }
9977
9978 /// \brief Merge a sequence of operations into its parent.
9979 void merge(Seq S) {
9980 Values[S.Index].Merged = true;
9981 }
9982
9983 /// \brief Determine whether two operations are unsequenced. This operation
9984 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9985 /// should have been merged into its parent as appropriate.
9986 bool isUnsequenced(Seq Cur, Seq Old) {
9987 unsigned C = representative(Cur.Index);
9988 unsigned Target = representative(Old.Index);
9989 while (C >= Target) {
9990 if (C == Target)
9991 return true;
9992 C = Values[C].Parent;
9993 }
9994 return false;
9995 }
9996
9997 private:
9998 /// \brief Pick a representative for a sequence.
9999 unsigned representative(unsigned K) {
10000 if (Values[K].Merged)
10001 // Perform path compression as we go.
10002 return Values[K].Parent = representative(Values[K].Parent);
10003 return K;
10004 }
10005 };
10006
10007 /// An object for which we can track unsequenced uses.
10008 typedef NamedDecl *Object;
10009
10010 /// Different flavors of object usage which we track. We only track the
10011 /// least-sequenced usage of each kind.
10012 enum UsageKind {
10013 /// A read of an object. Multiple unsequenced reads are OK.
10014 UK_Use,
10015 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000010016 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000010017 UK_ModAsValue,
10018 /// A modification of an object which is not sequenced before the value
10019 /// computation of the expression, such as n++.
10020 UK_ModAsSideEffect,
10021
10022 UK_Count = UK_ModAsSideEffect + 1
10023 };
10024
10025 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +000010026 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +000010027 Expr *Use;
10028 SequenceTree::Seq Seq;
10029 };
10030
10031 struct UsageInfo {
10032 UsageInfo() : Diagnosed(false) {}
10033 Usage Uses[UK_Count];
10034 /// Have we issued a diagnostic for this variable already?
10035 bool Diagnosed;
10036 };
10037 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
10038
10039 Sema &SemaRef;
10040 /// Sequenced regions within the expression.
10041 SequenceTree Tree;
10042 /// Declaration modifications and references which we have seen.
10043 UsageInfoMap UsageMap;
10044 /// The region we are currently within.
10045 SequenceTree::Seq Region;
10046 /// Filled in with declarations which were modified as a side-effect
10047 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010048 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +000010049 /// Expressions to check later. We defer checking these to reduce
10050 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010051 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000010052
10053 /// RAII object wrapping the visitation of a sequenced subexpression of an
10054 /// expression. At the end of this process, the side-effects of the evaluation
10055 /// become sequenced with respect to the value computation of the result, so
10056 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10057 /// UK_ModAsValue.
10058 struct SequencedSubexpression {
10059 SequencedSubexpression(SequenceChecker &Self)
10060 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10061 Self.ModAsSideEffect = &ModAsSideEffect;
10062 }
10063 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000010064 for (auto &M : llvm::reverse(ModAsSideEffect)) {
10065 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000010066 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000010067 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10068 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000010069 }
10070 Self.ModAsSideEffect = OldModAsSideEffect;
10071 }
10072
10073 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010074 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
10075 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000010076 };
10077
Richard Smith40238f02013-06-20 22:21:56 +000010078 /// RAII object wrapping the visitation of a subexpression which we might
10079 /// choose to evaluate as a constant. If any subexpression is evaluated and
10080 /// found to be non-constant, this allows us to suppress the evaluation of
10081 /// the outer expression.
10082 class EvaluationTracker {
10083 public:
10084 EvaluationTracker(SequenceChecker &Self)
10085 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
10086 Self.EvalTracker = this;
10087 }
10088 ~EvaluationTracker() {
10089 Self.EvalTracker = Prev;
10090 if (Prev)
10091 Prev->EvalOK &= EvalOK;
10092 }
10093
10094 bool evaluate(const Expr *E, bool &Result) {
10095 if (!EvalOK || E->isValueDependent())
10096 return false;
10097 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10098 return EvalOK;
10099 }
10100
10101 private:
10102 SequenceChecker &Self;
10103 EvaluationTracker *Prev;
10104 bool EvalOK;
10105 } *EvalTracker;
10106
Richard Smithc406cb72013-01-17 01:17:56 +000010107 /// \brief Find the object which is produced by the specified expression,
10108 /// if any.
10109 Object getObject(Expr *E, bool Mod) const {
10110 E = E->IgnoreParenCasts();
10111 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10112 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10113 return getObject(UO->getSubExpr(), Mod);
10114 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10115 if (BO->getOpcode() == BO_Comma)
10116 return getObject(BO->getRHS(), Mod);
10117 if (Mod && BO->isAssignmentOp())
10118 return getObject(BO->getLHS(), Mod);
10119 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10120 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10121 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10122 return ME->getMemberDecl();
10123 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10124 // FIXME: If this is a reference, map through to its value.
10125 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000010126 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010127 }
10128
10129 /// \brief Note that an object was modified or used by an expression.
10130 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10131 Usage &U = UI.Uses[UK];
10132 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10133 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10134 ModAsSideEffect->push_back(std::make_pair(O, U));
10135 U.Use = Ref;
10136 U.Seq = Region;
10137 }
10138 }
10139 /// \brief Check whether a modification or use conflicts with a prior usage.
10140 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10141 bool IsModMod) {
10142 if (UI.Diagnosed)
10143 return;
10144
10145 const Usage &U = UI.Uses[OtherKind];
10146 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10147 return;
10148
10149 Expr *Mod = U.Use;
10150 Expr *ModOrUse = Ref;
10151 if (OtherKind == UK_Use)
10152 std::swap(Mod, ModOrUse);
10153
10154 SemaRef.Diag(Mod->getExprLoc(),
10155 IsModMod ? diag::warn_unsequenced_mod_mod
10156 : diag::warn_unsequenced_mod_use)
10157 << O << SourceRange(ModOrUse->getExprLoc());
10158 UI.Diagnosed = true;
10159 }
10160
10161 void notePreUse(Object O, Expr *Use) {
10162 UsageInfo &U = UsageMap[O];
10163 // Uses conflict with other modifications.
10164 checkUsage(O, U, Use, UK_ModAsValue, false);
10165 }
10166 void notePostUse(Object O, Expr *Use) {
10167 UsageInfo &U = UsageMap[O];
10168 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10169 addUsage(U, O, Use, UK_Use);
10170 }
10171
10172 void notePreMod(Object O, Expr *Mod) {
10173 UsageInfo &U = UsageMap[O];
10174 // Modifications conflict with other modifications and with uses.
10175 checkUsage(O, U, Mod, UK_ModAsValue, true);
10176 checkUsage(O, U, Mod, UK_Use, false);
10177 }
10178 void notePostMod(Object O, Expr *Use, UsageKind UK) {
10179 UsageInfo &U = UsageMap[O];
10180 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10181 addUsage(U, O, Use, UK);
10182 }
10183
10184public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010185 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +000010186 : Base(S.Context), SemaRef(S), Region(Tree.root()),
10187 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010188 Visit(E);
10189 }
10190
10191 void VisitStmt(Stmt *S) {
10192 // Skip all statements which aren't expressions for now.
10193 }
10194
10195 void VisitExpr(Expr *E) {
10196 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000010197 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000010198 }
10199
10200 void VisitCastExpr(CastExpr *E) {
10201 Object O = Object();
10202 if (E->getCastKind() == CK_LValueToRValue)
10203 O = getObject(E->getSubExpr(), false);
10204
10205 if (O)
10206 notePreUse(O, E);
10207 VisitExpr(E);
10208 if (O)
10209 notePostUse(O, E);
10210 }
10211
10212 void VisitBinComma(BinaryOperator *BO) {
10213 // C++11 [expr.comma]p1:
10214 // Every value computation and side effect associated with the left
10215 // expression is sequenced before every value computation and side
10216 // effect associated with the right expression.
10217 SequenceTree::Seq LHS = Tree.allocate(Region);
10218 SequenceTree::Seq RHS = Tree.allocate(Region);
10219 SequenceTree::Seq OldRegion = Region;
10220
10221 {
10222 SequencedSubexpression SeqLHS(*this);
10223 Region = LHS;
10224 Visit(BO->getLHS());
10225 }
10226
10227 Region = RHS;
10228 Visit(BO->getRHS());
10229
10230 Region = OldRegion;
10231
10232 // Forget that LHS and RHS are sequenced. They are both unsequenced
10233 // with respect to other stuff.
10234 Tree.merge(LHS);
10235 Tree.merge(RHS);
10236 }
10237
10238 void VisitBinAssign(BinaryOperator *BO) {
10239 // The modification is sequenced after the value computation of the LHS
10240 // and RHS, so check it before inspecting the operands and update the
10241 // map afterwards.
10242 Object O = getObject(BO->getLHS(), true);
10243 if (!O)
10244 return VisitExpr(BO);
10245
10246 notePreMod(O, BO);
10247
10248 // C++11 [expr.ass]p7:
10249 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10250 // only once.
10251 //
10252 // Therefore, for a compound assignment operator, O is considered used
10253 // everywhere except within the evaluation of E1 itself.
10254 if (isa<CompoundAssignOperator>(BO))
10255 notePreUse(O, BO);
10256
10257 Visit(BO->getLHS());
10258
10259 if (isa<CompoundAssignOperator>(BO))
10260 notePostUse(O, BO);
10261
10262 Visit(BO->getRHS());
10263
Richard Smith83e37bee2013-06-26 23:16:51 +000010264 // C++11 [expr.ass]p1:
10265 // the assignment is sequenced [...] before the value computation of the
10266 // assignment expression.
10267 // C11 6.5.16/3 has no such rule.
10268 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10269 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010270 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010271
Richard Smithc406cb72013-01-17 01:17:56 +000010272 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10273 VisitBinAssign(CAO);
10274 }
10275
10276 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10277 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10278 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10279 Object O = getObject(UO->getSubExpr(), true);
10280 if (!O)
10281 return VisitExpr(UO);
10282
10283 notePreMod(O, UO);
10284 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000010285 // C++11 [expr.pre.incr]p1:
10286 // the expression ++x is equivalent to x+=1
10287 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10288 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010289 }
10290
10291 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10292 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10293 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10294 Object O = getObject(UO->getSubExpr(), true);
10295 if (!O)
10296 return VisitExpr(UO);
10297
10298 notePreMod(O, UO);
10299 Visit(UO->getSubExpr());
10300 notePostMod(O, UO, UK_ModAsSideEffect);
10301 }
10302
10303 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10304 void VisitBinLOr(BinaryOperator *BO) {
10305 // The side-effects of the LHS of an '&&' are sequenced before the
10306 // value computation of the RHS, and hence before the value computation
10307 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10308 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000010309 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010310 {
10311 SequencedSubexpression Sequenced(*this);
10312 Visit(BO->getLHS());
10313 }
10314
10315 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010316 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010317 if (!Result)
10318 Visit(BO->getRHS());
10319 } else {
10320 // Check for unsequenced operations in the RHS, treating it as an
10321 // entirely separate evaluation.
10322 //
10323 // FIXME: If there are operations in the RHS which are unsequenced
10324 // with respect to operations outside the RHS, and those operations
10325 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000010326 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010327 }
Richard Smithc406cb72013-01-17 01:17:56 +000010328 }
10329 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000010330 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010331 {
10332 SequencedSubexpression Sequenced(*this);
10333 Visit(BO->getLHS());
10334 }
10335
10336 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010337 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010338 if (Result)
10339 Visit(BO->getRHS());
10340 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000010341 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010342 }
Richard Smithc406cb72013-01-17 01:17:56 +000010343 }
10344
10345 // Only visit the condition, unless we can be sure which subexpression will
10346 // be chosen.
10347 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000010348 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000010349 {
10350 SequencedSubexpression Sequenced(*this);
10351 Visit(CO->getCond());
10352 }
Richard Smithc406cb72013-01-17 01:17:56 +000010353
10354 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010355 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000010356 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010357 else {
Richard Smithd33f5202013-01-17 23:18:09 +000010358 WorkList.push_back(CO->getTrueExpr());
10359 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010360 }
Richard Smithc406cb72013-01-17 01:17:56 +000010361 }
10362
Richard Smithe3dbfe02013-06-30 10:40:20 +000010363 void VisitCallExpr(CallExpr *CE) {
10364 // C++11 [intro.execution]p15:
10365 // When calling a function [...], every value computation and side effect
10366 // associated with any argument expression, or with the postfix expression
10367 // designating the called function, is sequenced before execution of every
10368 // expression or statement in the body of the function [and thus before
10369 // the value computation of its result].
10370 SequencedSubexpression Sequenced(*this);
10371 Base::VisitCallExpr(CE);
10372
10373 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10374 }
10375
Richard Smithc406cb72013-01-17 01:17:56 +000010376 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010377 // This is a call, so all subexpressions are sequenced before the result.
10378 SequencedSubexpression Sequenced(*this);
10379
Richard Smithc406cb72013-01-17 01:17:56 +000010380 if (!CCE->isListInitialization())
10381 return VisitExpr(CCE);
10382
10383 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010384 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010385 SequenceTree::Seq Parent = Region;
10386 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10387 E = CCE->arg_end();
10388 I != E; ++I) {
10389 Region = Tree.allocate(Parent);
10390 Elts.push_back(Region);
10391 Visit(*I);
10392 }
10393
10394 // Forget that the initializers are sequenced.
10395 Region = Parent;
10396 for (unsigned I = 0; I < Elts.size(); ++I)
10397 Tree.merge(Elts[I]);
10398 }
10399
10400 void VisitInitListExpr(InitListExpr *ILE) {
10401 if (!SemaRef.getLangOpts().CPlusPlus11)
10402 return VisitExpr(ILE);
10403
10404 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010405 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010406 SequenceTree::Seq Parent = Region;
10407 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10408 Expr *E = ILE->getInit(I);
10409 if (!E) continue;
10410 Region = Tree.allocate(Parent);
10411 Elts.push_back(Region);
10412 Visit(E);
10413 }
10414
10415 // Forget that the initializers are sequenced.
10416 Region = Parent;
10417 for (unsigned I = 0; I < Elts.size(); ++I)
10418 Tree.merge(Elts[I]);
10419 }
10420};
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010421} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +000010422
10423void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010424 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000010425 WorkList.push_back(E);
10426 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000010427 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000010428 SequenceChecker(*this, Item, WorkList);
10429 }
Richard Smithc406cb72013-01-17 01:17:56 +000010430}
10431
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010432void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10433 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010434 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000010435 if (!E->isInstantiationDependent())
10436 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010437 if (!IsConstexpr && !E->isValueDependent())
Nick Lewyckye7d6fbd2017-04-29 09:33:46 +000010438 E->EvaluateForOverflow(Context);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010439 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000010440}
10441
John McCall1f425642010-11-11 03:21:53 +000010442void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10443 FieldDecl *BitField,
10444 Expr *Init) {
10445 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10446}
10447
David Majnemer61a5bbf2015-04-07 22:08:51 +000010448static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10449 SourceLocation Loc) {
10450 if (!PType->isVariablyModifiedType())
10451 return;
10452 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10453 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10454 return;
10455 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000010456 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10457 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10458 return;
10459 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000010460 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10461 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10462 return;
10463 }
10464
10465 const ArrayType *AT = S.Context.getAsArrayType(PType);
10466 if (!AT)
10467 return;
10468
10469 if (AT->getSizeModifier() != ArrayType::Star) {
10470 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10471 return;
10472 }
10473
10474 S.Diag(Loc, diag::err_array_star_in_function_definition);
10475}
10476
Mike Stump0c2ec772010-01-21 03:59:47 +000010477/// CheckParmsForFunctionDef - Check that the parameters of the given
10478/// function are appropriate for the definition of a function. This
10479/// takes care of any checks that cannot be performed on the
10480/// declaration itself, e.g., that the types of each of the function
10481/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000010482bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000010483 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010484 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000010485 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010486 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10487 // function declarator that is part of a function definition of
10488 // that function shall not have incomplete type.
10489 //
10490 // This is also C++ [dcl.fct]p6.
10491 if (!Param->isInvalidDecl() &&
10492 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010493 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010494 Param->setInvalidDecl();
10495 HasInvalidParm = true;
10496 }
10497
10498 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10499 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000010500 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000010501 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000010502 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000010503 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000010504 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000010505
10506 // C99 6.7.5.3p12:
10507 // If the function declarator is not part of a definition of that
10508 // function, parameters may have incomplete type and may use the [*]
10509 // notation in their sequences of declarator specifiers to specify
10510 // variable length array types.
10511 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000010512 // FIXME: This diagnostic should point the '[*]' if source-location
10513 // information is added for it.
10514 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010515
10516 // MSVC destroys objects passed by value in the callee. Therefore a
10517 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010518 // object's destructor. However, we don't perform any direct access check
10519 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +000010520 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10521 .getCXXABI()
10522 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +000010523 if (!Param->isInvalidDecl()) {
10524 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10525 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10526 if (!ClassDecl->isInvalidDecl() &&
10527 !ClassDecl->hasIrrelevantDestructor() &&
10528 !ClassDecl->isDependentContext()) {
10529 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10530 MarkFunctionReferenced(Param->getLocation(), Destructor);
10531 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10532 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010533 }
10534 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010535 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010536
10537 // Parameters with the pass_object_size attribute only need to be marked
10538 // constant at function definitions. Because we lack information about
10539 // whether we're on a declaration or definition when we're instantiating the
10540 // attribute, we need to check for constness here.
10541 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10542 if (!Param->getType().isConstQualified())
10543 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10544 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000010545 }
10546
10547 return HasInvalidParm;
10548}
John McCall2b5c1b22010-08-12 21:44:57 +000010549
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010550/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10551/// or MemberExpr.
10552static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10553 ASTContext &Context) {
10554 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10555 return Context.getDeclAlign(DRE->getDecl());
10556
10557 if (const auto *ME = dyn_cast<MemberExpr>(E))
10558 return Context.getDeclAlign(ME->getMemberDecl());
10559
10560 return TypeAlign;
10561}
10562
John McCall2b5c1b22010-08-12 21:44:57 +000010563/// CheckCastAlign - Implements -Wcast-align, which warns when a
10564/// pointer cast increases the alignment requirements.
10565void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10566 // This is actually a lot of work to potentially be doing on every
10567 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010568 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000010569 return;
10570
10571 // Ignore dependent types.
10572 if (T->isDependentType() || Op->getType()->isDependentType())
10573 return;
10574
10575 // Require that the destination be a pointer type.
10576 const PointerType *DestPtr = T->getAs<PointerType>();
10577 if (!DestPtr) return;
10578
10579 // If the destination has alignment 1, we're done.
10580 QualType DestPointee = DestPtr->getPointeeType();
10581 if (DestPointee->isIncompleteType()) return;
10582 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10583 if (DestAlign.isOne()) return;
10584
10585 // Require that the source be a pointer type.
10586 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10587 if (!SrcPtr) return;
10588 QualType SrcPointee = SrcPtr->getPointeeType();
10589
10590 // Whitelist casts from cv void*. We already implicitly
10591 // whitelisted casts to cv void*, since they have alignment 1.
10592 // Also whitelist casts involving incomplete types, which implicitly
10593 // includes 'void'.
10594 if (SrcPointee->isIncompleteType()) return;
10595
10596 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010597
10598 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10599 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10600 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10601 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10602 if (UO->getOpcode() == UO_AddrOf)
10603 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10604 }
10605
John McCall2b5c1b22010-08-12 21:44:57 +000010606 if (SrcAlign >= DestAlign) return;
10607
10608 Diag(TRange.getBegin(), diag::warn_cast_align)
10609 << Op->getType() << T
10610 << static_cast<unsigned>(SrcAlign.getQuantity())
10611 << static_cast<unsigned>(DestAlign.getQuantity())
10612 << TRange << Op->getSourceRange();
10613}
10614
Chandler Carruth28389f02011-08-05 09:10:50 +000010615/// \brief Check whether this array fits the idiom of a size-one tail padded
10616/// array member of a struct.
10617///
10618/// We avoid emitting out-of-bounds access warnings for such arrays as they are
10619/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000010620static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000010621 const NamedDecl *ND) {
10622 if (Size != 1 || !ND) return false;
10623
10624 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10625 if (!FD) return false;
10626
10627 // Don't consider sizes resulting from macro expansions or template argument
10628 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000010629
10630 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010631 while (TInfo) {
10632 TypeLoc TL = TInfo->getTypeLoc();
10633 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000010634 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10635 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010636 TInfo = TDL->getTypeSourceInfo();
10637 continue;
10638 }
David Blaikie6adc78e2013-02-18 22:06:02 +000010639 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10640 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000010641 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10642 return false;
10643 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010644 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000010645 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010646
10647 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000010648 if (!RD) return false;
10649 if (RD->isUnion()) return false;
10650 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10651 if (!CRD->isStandardLayout()) return false;
10652 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010653
Benjamin Kramer8c543672011-08-06 03:04:42 +000010654 // See if this is the last field decl in the record.
10655 const Decl *D = FD;
10656 while ((D = D->getNextDeclInContext()))
10657 if (isa<FieldDecl>(D))
10658 return false;
10659 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000010660}
10661
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010662void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010663 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000010664 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010665 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010666 if (IndexExpr->isValueDependent())
10667 return;
10668
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010669 const Type *EffectiveType =
10670 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010671 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010672 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010673 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010674 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000010675 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000010676
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010677 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000010678 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000010679 return;
Richard Smith13f67182011-12-16 19:31:14 +000010680 if (IndexNegated)
10681 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000010682
Craig Topperc3ec1492014-05-26 06:22:03 +000010683 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000010684 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10685 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +000010686 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +000010687 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +000010688
Ted Kremeneke4b316c2011-02-23 23:06:04 +000010689 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010690 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000010691 if (!size.isStrictlyPositive())
10692 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010693
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010694 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000010695 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010696 // Make sure we're comparing apples to apples when comparing index to size
10697 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10698 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000010699 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000010700 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010701 if (ptrarith_typesize != array_typesize) {
10702 // There's a cast to a different size type involved
10703 uint64_t ratio = array_typesize / ptrarith_typesize;
10704 // TODO: Be smarter about handling cases where array_typesize is not a
10705 // multiple of ptrarith_typesize
10706 if (ptrarith_typesize * ratio == array_typesize)
10707 size *= llvm::APInt(size.getBitWidth(), ratio);
10708 }
10709 }
10710
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010711 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010712 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010713 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010714 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010715
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010716 // For array subscripting the index must be less than size, but for pointer
10717 // arithmetic also allow the index (offset) to be equal to size since
10718 // computing the next address after the end of the array is legal and
10719 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010720 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000010721 return;
10722
10723 // Also don't warn for arrays of size 1 which are members of some
10724 // structure. These are often used to approximate flexible arrays in C89
10725 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010726 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000010727 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010728
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010729 // Suppress the warning if the subscript expression (as identified by the
10730 // ']' location) and the index expression are both from macro expansions
10731 // within a system header.
10732 if (ASE) {
10733 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10734 ASE->getRBracketLoc());
10735 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10736 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10737 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000010738 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010739 return;
10740 }
10741 }
10742
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010743 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010744 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010745 DiagID = diag::warn_array_index_exceeds_bounds;
10746
10747 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10748 PDiag(DiagID) << index.toString(10, true)
10749 << size.toString(10, true)
10750 << (unsigned)size.getLimitedValue(~0U)
10751 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010752 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010753 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010754 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010755 DiagID = diag::warn_ptr_arith_precedes_bounds;
10756 if (index.isNegative()) index = -index;
10757 }
10758
10759 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10760 PDiag(DiagID) << index.toString(10, true)
10761 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000010762 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000010763
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000010764 if (!ND) {
10765 // Try harder to find a NamedDecl to point at in the note.
10766 while (const ArraySubscriptExpr *ASE =
10767 dyn_cast<ArraySubscriptExpr>(BaseExpr))
10768 BaseExpr = ASE->getBase()->IgnoreParenCasts();
10769 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10770 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10771 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10772 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10773 }
10774
Chandler Carruth1af88f12011-02-17 21:10:52 +000010775 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010776 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10777 PDiag(diag::note_array_index_out_of_bounds)
10778 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000010779}
10780
Ted Kremenekdf26df72011-03-01 18:41:00 +000010781void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010782 int AllowOnePastEnd = 0;
10783 while (expr) {
10784 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000010785 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010786 case Stmt::ArraySubscriptExprClass: {
10787 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010788 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010789 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +000010790 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010791 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010792 case Stmt::OMPArraySectionExprClass: {
10793 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10794 if (ASE->getLowerBound())
10795 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10796 /*ASE=*/nullptr, AllowOnePastEnd > 0);
10797 return;
10798 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010799 case Stmt::UnaryOperatorClass: {
10800 // Only unwrap the * and & unary operators
10801 const UnaryOperator *UO = cast<UnaryOperator>(expr);
10802 expr = UO->getSubExpr();
10803 switch (UO->getOpcode()) {
10804 case UO_AddrOf:
10805 AllowOnePastEnd++;
10806 break;
10807 case UO_Deref:
10808 AllowOnePastEnd--;
10809 break;
10810 default:
10811 return;
10812 }
10813 break;
10814 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010815 case Stmt::ConditionalOperatorClass: {
10816 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10817 if (const Expr *lhs = cond->getLHS())
10818 CheckArrayAccess(lhs);
10819 if (const Expr *rhs = cond->getRHS())
10820 CheckArrayAccess(rhs);
10821 return;
10822 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000010823 case Stmt::CXXOperatorCallExprClass: {
10824 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
10825 for (const auto *Arg : OCE->arguments())
10826 CheckArrayAccess(Arg);
10827 return;
10828 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010829 default:
10830 return;
10831 }
Peter Collingbourne91147592011-04-15 00:35:48 +000010832 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010833}
John McCall31168b02011-06-15 23:02:42 +000010834
10835//===--- CHECK: Objective-C retain cycles ----------------------------------//
10836
10837namespace {
10838 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +000010839 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +000010840 VarDecl *Variable;
10841 SourceRange Range;
10842 SourceLocation Loc;
10843 bool Indirect;
10844
10845 void setLocsFrom(Expr *e) {
10846 Loc = e->getExprLoc();
10847 Range = e->getSourceRange();
10848 }
10849 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010850} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010851
10852/// Consider whether capturing the given variable can possibly lead to
10853/// a retain cycle.
10854static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010855 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000010856 // lifetime. In MRR, it's captured strongly if the variable is
10857 // __block and has an appropriate type.
10858 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10859 return false;
10860
10861 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010862 if (ref)
10863 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000010864 return true;
10865}
10866
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010867static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000010868 while (true) {
10869 e = e->IgnoreParens();
10870 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10871 switch (cast->getCastKind()) {
10872 case CK_BitCast:
10873 case CK_LValueBitCast:
10874 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000010875 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000010876 e = cast->getSubExpr();
10877 continue;
10878
John McCall31168b02011-06-15 23:02:42 +000010879 default:
10880 return false;
10881 }
10882 }
10883
10884 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10885 ObjCIvarDecl *ivar = ref->getDecl();
10886 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10887 return false;
10888
10889 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010890 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000010891 return false;
10892
10893 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10894 owner.Indirect = true;
10895 return true;
10896 }
10897
10898 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10899 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10900 if (!var) return false;
10901 return considerVariable(var, ref, owner);
10902 }
10903
John McCall31168b02011-06-15 23:02:42 +000010904 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10905 if (member->isArrow()) return false;
10906
10907 // Don't count this as an indirect ownership.
10908 e = member->getBase();
10909 continue;
10910 }
10911
John McCallfe96e0b2011-11-06 09:01:30 +000010912 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10913 // Only pay attention to pseudo-objects on property references.
10914 ObjCPropertyRefExpr *pre
10915 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10916 ->IgnoreParens());
10917 if (!pre) return false;
10918 if (pre->isImplicitProperty()) return false;
10919 ObjCPropertyDecl *property = pre->getExplicitProperty();
10920 if (!property->isRetaining() &&
10921 !(property->getPropertyIvarDecl() &&
10922 property->getPropertyIvarDecl()->getType()
10923 .getObjCLifetime() == Qualifiers::OCL_Strong))
10924 return false;
10925
10926 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010927 if (pre->isSuperReceiver()) {
10928 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10929 if (!owner.Variable)
10930 return false;
10931 owner.Loc = pre->getLocation();
10932 owner.Range = pre->getSourceRange();
10933 return true;
10934 }
John McCallfe96e0b2011-11-06 09:01:30 +000010935 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10936 ->getSourceExpr());
10937 continue;
10938 }
10939
John McCall31168b02011-06-15 23:02:42 +000010940 // Array ivars?
10941
10942 return false;
10943 }
10944}
10945
10946namespace {
10947 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10948 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10949 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010950 Context(Context), Variable(variable), Capturer(nullptr),
10951 VarWillBeReased(false) {}
10952 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000010953 VarDecl *Variable;
10954 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010955 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +000010956
10957 void VisitDeclRefExpr(DeclRefExpr *ref) {
10958 if (ref->getDecl() == Variable && !Capturer)
10959 Capturer = ref;
10960 }
10961
John McCall31168b02011-06-15 23:02:42 +000010962 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10963 if (Capturer) return;
10964 Visit(ref->getBase());
10965 if (Capturer && ref->isFreeIvar())
10966 Capturer = ref;
10967 }
10968
10969 void VisitBlockExpr(BlockExpr *block) {
10970 // Look inside nested blocks
10971 if (block->getBlockDecl()->capturesVariable(Variable))
10972 Visit(block->getBlockDecl()->getBody());
10973 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000010974
10975 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
10976 if (Capturer) return;
10977 if (OVE->getSourceExpr())
10978 Visit(OVE->getSourceExpr());
10979 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010980 void VisitBinaryOperator(BinaryOperator *BinOp) {
10981 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
10982 return;
10983 Expr *LHS = BinOp->getLHS();
10984 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
10985 if (DRE->getDecl() != Variable)
10986 return;
10987 if (Expr *RHS = BinOp->getRHS()) {
10988 RHS = RHS->IgnoreParenCasts();
10989 llvm::APSInt Value;
10990 VarWillBeReased =
10991 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
10992 }
10993 }
10994 }
John McCall31168b02011-06-15 23:02:42 +000010995 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010996} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010997
10998/// Check whether the given argument is a block which captures a
10999/// variable.
11000static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11001 assert(owner.Variable && owner.Loc.isValid());
11002
11003 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000011004
11005 // Look through [^{...} copy] and Block_copy(^{...}).
11006 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11007 Selector Cmd = ME->getSelector();
11008 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11009 e = ME->getInstanceReceiver();
11010 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000011011 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000011012 e = e->IgnoreParenCasts();
11013 }
11014 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11015 if (CE->getNumArgs() == 1) {
11016 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000011017 if (Fn) {
11018 const IdentifierInfo *FnI = Fn->getIdentifier();
11019 if (FnI && FnI->isStr("_Block_copy")) {
11020 e = CE->getArg(0)->IgnoreParenCasts();
11021 }
11022 }
Jordan Rose67e887c2012-09-17 17:54:30 +000011023 }
11024 }
11025
John McCall31168b02011-06-15 23:02:42 +000011026 BlockExpr *block = dyn_cast<BlockExpr>(e);
11027 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000011028 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011029
11030 FindCaptureVisitor visitor(S.Context, owner.Variable);
11031 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011032 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000011033}
11034
11035static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11036 RetainCycleOwner &owner) {
11037 assert(capturer);
11038 assert(owner.Variable && owner.Loc.isValid());
11039
11040 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11041 << owner.Variable << capturer->getSourceRange();
11042 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11043 << owner.Indirect << owner.Range;
11044}
11045
11046/// Check for a keyword selector that starts with the word 'add' or
11047/// 'set'.
11048static bool isSetterLikeSelector(Selector sel) {
11049 if (sel.isUnarySelector()) return false;
11050
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011051 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000011052 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011053 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000011054 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011055 else if (str.startswith("add")) {
11056 // Specially whitelist 'addOperationWithBlock:'.
11057 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11058 return false;
11059 str = str.substr(3);
11060 }
John McCall31168b02011-06-15 23:02:42 +000011061 else
11062 return false;
11063
11064 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000011065 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000011066}
11067
Benjamin Kramer3a743452015-03-09 15:03:32 +000011068static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11069 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011070 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11071 Message->getReceiverInterface(),
11072 NSAPI::ClassId_NSMutableArray);
11073 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011074 return None;
11075 }
11076
11077 Selector Sel = Message->getSelector();
11078
11079 Optional<NSAPI::NSArrayMethodKind> MKOpt =
11080 S.NSAPIObj->getNSArrayMethodKind(Sel);
11081 if (!MKOpt) {
11082 return None;
11083 }
11084
11085 NSAPI::NSArrayMethodKind MK = *MKOpt;
11086
11087 switch (MK) {
11088 case NSAPI::NSMutableArr_addObject:
11089 case NSAPI::NSMutableArr_insertObjectAtIndex:
11090 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11091 return 0;
11092 case NSAPI::NSMutableArr_replaceObjectAtIndex:
11093 return 1;
11094
11095 default:
11096 return None;
11097 }
11098
11099 return None;
11100}
11101
11102static
11103Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11104 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011105 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11106 Message->getReceiverInterface(),
11107 NSAPI::ClassId_NSMutableDictionary);
11108 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011109 return None;
11110 }
11111
11112 Selector Sel = Message->getSelector();
11113
11114 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11115 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11116 if (!MKOpt) {
11117 return None;
11118 }
11119
11120 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11121
11122 switch (MK) {
11123 case NSAPI::NSMutableDict_setObjectForKey:
11124 case NSAPI::NSMutableDict_setValueForKey:
11125 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11126 return 0;
11127
11128 default:
11129 return None;
11130 }
11131
11132 return None;
11133}
11134
11135static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011136 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11137 Message->getReceiverInterface(),
11138 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000011139
Alex Denisov5dfac812015-08-06 04:51:14 +000011140 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11141 Message->getReceiverInterface(),
11142 NSAPI::ClassId_NSMutableOrderedSet);
11143 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011144 return None;
11145 }
11146
11147 Selector Sel = Message->getSelector();
11148
11149 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11150 if (!MKOpt) {
11151 return None;
11152 }
11153
11154 NSAPI::NSSetMethodKind MK = *MKOpt;
11155
11156 switch (MK) {
11157 case NSAPI::NSMutableSet_addObject:
11158 case NSAPI::NSOrderedSet_setObjectAtIndex:
11159 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11160 case NSAPI::NSOrderedSet_insertObjectAtIndex:
11161 return 0;
11162 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11163 return 1;
11164 }
11165
11166 return None;
11167}
11168
11169void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11170 if (!Message->isInstanceMessage()) {
11171 return;
11172 }
11173
11174 Optional<int> ArgOpt;
11175
11176 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11177 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11178 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11179 return;
11180 }
11181
11182 int ArgIndex = *ArgOpt;
11183
Alex Denisove1d882c2015-03-04 17:55:52 +000011184 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11185 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11186 Arg = OE->getSourceExpr()->IgnoreImpCasts();
11187 }
11188
Alex Denisov5dfac812015-08-06 04:51:14 +000011189 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011190 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011191 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011192 Diag(Message->getSourceRange().getBegin(),
11193 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000011194 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000011195 }
11196 }
Alex Denisov5dfac812015-08-06 04:51:14 +000011197 } else {
11198 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11199
11200 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11201 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11202 }
11203
11204 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11205 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11206 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11207 ValueDecl *Decl = ReceiverRE->getDecl();
11208 Diag(Message->getSourceRange().getBegin(),
11209 diag::warn_objc_circular_container)
11210 << Decl->getName() << Decl->getName();
11211 if (!ArgRE->isObjCSelfExpr()) {
11212 Diag(Decl->getLocation(),
11213 diag::note_objc_circular_container_declared_here)
11214 << Decl->getName();
11215 }
11216 }
11217 }
11218 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11219 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11220 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11221 ObjCIvarDecl *Decl = IvarRE->getDecl();
11222 Diag(Message->getSourceRange().getBegin(),
11223 diag::warn_objc_circular_container)
11224 << Decl->getName() << Decl->getName();
11225 Diag(Decl->getLocation(),
11226 diag::note_objc_circular_container_declared_here)
11227 << Decl->getName();
11228 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011229 }
11230 }
11231 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011232}
11233
John McCall31168b02011-06-15 23:02:42 +000011234/// Check a message send to see if it's likely to cause a retain cycle.
11235void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11236 // Only check instance methods whose selector looks like a setter.
11237 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11238 return;
11239
11240 // Try to find a variable that the receiver is strongly owned by.
11241 RetainCycleOwner owner;
11242 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011243 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000011244 return;
11245 } else {
11246 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11247 owner.Variable = getCurMethodDecl()->getSelfDecl();
11248 owner.Loc = msg->getSuperLoc();
11249 owner.Range = msg->getSuperLoc();
11250 }
11251
11252 // Check whether the receiver is captured by any of the arguments.
11253 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
11254 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
11255 return diagnoseRetainCycle(*this, capturer, owner);
11256}
11257
11258/// Check a property assign to see if it's likely to cause a retain cycle.
11259void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11260 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011261 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000011262 return;
11263
11264 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11265 diagnoseRetainCycle(*this, capturer, owner);
11266}
11267
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011268void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11269 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000011270 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011271 return;
11272
11273 // Because we don't have an expression for the variable, we have to set the
11274 // location explicitly here.
11275 Owner.Loc = Var->getLocation();
11276 Owner.Range = Var->getSourceRange();
11277
11278 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11279 diagnoseRetainCycle(*this, Capturer, Owner);
11280}
11281
Ted Kremenek9304da92012-12-21 08:04:28 +000011282static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11283 Expr *RHS, bool isProperty) {
11284 // Check if RHS is an Objective-C object literal, which also can get
11285 // immediately zapped in a weak reference. Note that we explicitly
11286 // allow ObjCStringLiterals, since those are designed to never really die.
11287 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011288
Ted Kremenek64873352012-12-21 22:46:35 +000011289 // This enum needs to match with the 'select' in
11290 // warn_objc_arc_literal_assign (off-by-1).
11291 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11292 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11293 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011294
11295 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000011296 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000011297 << (isProperty ? 0 : 1)
11298 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011299
11300 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000011301}
11302
Ted Kremenekc1f014a2012-12-21 19:45:30 +000011303static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11304 Qualifiers::ObjCLifetime LT,
11305 Expr *RHS, bool isProperty) {
11306 // Strip off any implicit cast added to get to the one ARC-specific.
11307 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11308 if (cast->getCastKind() == CK_ARCConsumeObject) {
11309 S.Diag(Loc, diag::warn_arc_retained_assign)
11310 << (LT == Qualifiers::OCL_ExplicitNone)
11311 << (isProperty ? 0 : 1)
11312 << RHS->getSourceRange();
11313 return true;
11314 }
11315 RHS = cast->getSubExpr();
11316 }
11317
11318 if (LT == Qualifiers::OCL_Weak &&
11319 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11320 return true;
11321
11322 return false;
11323}
11324
Ted Kremenekb36234d2012-12-21 08:04:20 +000011325bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11326 QualType LHS, Expr *RHS) {
11327 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11328
11329 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11330 return false;
11331
11332 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11333 return true;
11334
11335 return false;
11336}
11337
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011338void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11339 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011340 QualType LHSType;
11341 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011342 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011343 ObjCPropertyRefExpr *PRE
11344 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11345 if (PRE && !PRE->isImplicitProperty()) {
11346 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11347 if (PD)
11348 LHSType = PD->getType();
11349 }
11350
11351 if (LHSType.isNull())
11352 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000011353
11354 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11355
11356 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011357 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000011358 getCurFunction()->markSafeWeakUse(LHS);
11359 }
11360
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011361 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11362 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000011363
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011364 // FIXME. Check for other life times.
11365 if (LT != Qualifiers::OCL_None)
11366 return;
11367
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011368 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011369 if (PRE->isImplicitProperty())
11370 return;
11371 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11372 if (!PD)
11373 return;
11374
Bill Wendling44426052012-12-20 19:22:21 +000011375 unsigned Attributes = PD->getPropertyAttributes();
11376 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011377 // when 'assign' attribute was not explicitly specified
11378 // by user, ignore it and rely on property type itself
11379 // for lifetime info.
11380 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11381 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11382 LHSType->isObjCRetainableType())
11383 return;
11384
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011385 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000011386 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011387 Diag(Loc, diag::warn_arc_retained_property_assign)
11388 << RHS->getSourceRange();
11389 return;
11390 }
11391 RHS = cast->getSubExpr();
11392 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011393 }
Bill Wendling44426052012-12-20 19:22:21 +000011394 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000011395 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11396 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000011397 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011398 }
11399}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011400
11401//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11402
11403namespace {
11404bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11405 SourceLocation StmtLoc,
11406 const NullStmt *Body) {
11407 // Do not warn if the body is a macro that expands to nothing, e.g:
11408 //
11409 // #define CALL(x)
11410 // if (condition)
11411 // CALL(0);
11412 //
11413 if (Body->hasLeadingEmptyMacro())
11414 return false;
11415
11416 // Get line numbers of statement and body.
11417 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000011418 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011419 &StmtLineInvalid);
11420 if (StmtLineInvalid)
11421 return false;
11422
11423 bool BodyLineInvalid;
11424 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11425 &BodyLineInvalid);
11426 if (BodyLineInvalid)
11427 return false;
11428
11429 // Warn if null statement and body are on the same line.
11430 if (StmtLine != BodyLine)
11431 return false;
11432
11433 return true;
11434}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011435} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011436
11437void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11438 const Stmt *Body,
11439 unsigned DiagID) {
11440 // Since this is a syntactic check, don't emit diagnostic for template
11441 // instantiations, this just adds noise.
11442 if (CurrentInstantiationScope)
11443 return;
11444
11445 // The body should be a null statement.
11446 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11447 if (!NBody)
11448 return;
11449
11450 // Do the usual checks.
11451 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11452 return;
11453
11454 Diag(NBody->getSemiLoc(), DiagID);
11455 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11456}
11457
11458void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11459 const Stmt *PossibleBody) {
11460 assert(!CurrentInstantiationScope); // Ensured by caller
11461
11462 SourceLocation StmtLoc;
11463 const Stmt *Body;
11464 unsigned DiagID;
11465 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11466 StmtLoc = FS->getRParenLoc();
11467 Body = FS->getBody();
11468 DiagID = diag::warn_empty_for_body;
11469 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11470 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11471 Body = WS->getBody();
11472 DiagID = diag::warn_empty_while_body;
11473 } else
11474 return; // Neither `for' nor `while'.
11475
11476 // The body should be a null statement.
11477 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11478 if (!NBody)
11479 return;
11480
11481 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011482 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011483 return;
11484
11485 // Do the usual checks.
11486 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11487 return;
11488
11489 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11490 // noise level low, emit diagnostics only if for/while is followed by a
11491 // CompoundStmt, e.g.:
11492 // for (int i = 0; i < n; i++);
11493 // {
11494 // a(i);
11495 // }
11496 // or if for/while is followed by a statement with more indentation
11497 // than for/while itself:
11498 // for (int i = 0; i < n; i++);
11499 // a(i);
11500 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11501 if (!ProbableTypo) {
11502 bool BodyColInvalid;
11503 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11504 PossibleBody->getLocStart(),
11505 &BodyColInvalid);
11506 if (BodyColInvalid)
11507 return;
11508
11509 bool StmtColInvalid;
11510 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11511 S->getLocStart(),
11512 &StmtColInvalid);
11513 if (StmtColInvalid)
11514 return;
11515
11516 if (BodyCol > StmtCol)
11517 ProbableTypo = true;
11518 }
11519
11520 if (ProbableTypo) {
11521 Diag(NBody->getSemiLoc(), DiagID);
11522 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11523 }
11524}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011525
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011526//===--- CHECK: Warn on self move with std::move. -------------------------===//
11527
11528/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11529void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11530 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011531 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11532 return;
11533
Richard Smith51ec0cf2017-02-21 01:17:38 +000011534 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011535 return;
11536
11537 // Strip parens and casts away.
11538 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11539 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11540
11541 // Check for a call expression
11542 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11543 if (!CE || CE->getNumArgs() != 1)
11544 return;
11545
11546 // Check for a call to std::move
11547 const FunctionDecl *FD = CE->getDirectCallee();
11548 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11549 !FD->getIdentifier()->isStr("move"))
11550 return;
11551
11552 // Get argument from std::move
11553 RHSExpr = CE->getArg(0);
11554
11555 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11556 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11557
11558 // Two DeclRefExpr's, check that the decls are the same.
11559 if (LHSDeclRef && RHSDeclRef) {
11560 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11561 return;
11562 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11563 RHSDeclRef->getDecl()->getCanonicalDecl())
11564 return;
11565
11566 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11567 << LHSExpr->getSourceRange()
11568 << RHSExpr->getSourceRange();
11569 return;
11570 }
11571
11572 // Member variables require a different approach to check for self moves.
11573 // MemberExpr's are the same if every nested MemberExpr refers to the same
11574 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11575 // the base Expr's are CXXThisExpr's.
11576 const Expr *LHSBase = LHSExpr;
11577 const Expr *RHSBase = RHSExpr;
11578 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11579 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11580 if (!LHSME || !RHSME)
11581 return;
11582
11583 while (LHSME && RHSME) {
11584 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11585 RHSME->getMemberDecl()->getCanonicalDecl())
11586 return;
11587
11588 LHSBase = LHSME->getBase();
11589 RHSBase = RHSME->getBase();
11590 LHSME = dyn_cast<MemberExpr>(LHSBase);
11591 RHSME = dyn_cast<MemberExpr>(RHSBase);
11592 }
11593
11594 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11595 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11596 if (LHSDeclRef && RHSDeclRef) {
11597 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11598 return;
11599 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11600 RHSDeclRef->getDecl()->getCanonicalDecl())
11601 return;
11602
11603 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11604 << LHSExpr->getSourceRange()
11605 << RHSExpr->getSourceRange();
11606 return;
11607 }
11608
11609 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11610 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11611 << LHSExpr->getSourceRange()
11612 << RHSExpr->getSourceRange();
11613}
11614
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011615//===--- Layout compatibility ----------------------------------------------//
11616
11617namespace {
11618
11619bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11620
11621/// \brief Check if two enumeration types are layout-compatible.
11622bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11623 // C++11 [dcl.enum] p8:
11624 // Two enumeration types are layout-compatible if they have the same
11625 // underlying type.
11626 return ED1->isComplete() && ED2->isComplete() &&
11627 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11628}
11629
11630/// \brief Check if two fields are layout-compatible.
11631bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11632 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11633 return false;
11634
11635 if (Field1->isBitField() != Field2->isBitField())
11636 return false;
11637
11638 if (Field1->isBitField()) {
11639 // Make sure that the bit-fields are the same length.
11640 unsigned Bits1 = Field1->getBitWidthValue(C);
11641 unsigned Bits2 = Field2->getBitWidthValue(C);
11642
11643 if (Bits1 != Bits2)
11644 return false;
11645 }
11646
11647 return true;
11648}
11649
11650/// \brief Check if two standard-layout structs are layout-compatible.
11651/// (C++11 [class.mem] p17)
11652bool isLayoutCompatibleStruct(ASTContext &C,
11653 RecordDecl *RD1,
11654 RecordDecl *RD2) {
11655 // If both records are C++ classes, check that base classes match.
11656 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11657 // If one of records is a CXXRecordDecl we are in C++ mode,
11658 // thus the other one is a CXXRecordDecl, too.
11659 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11660 // Check number of base classes.
11661 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11662 return false;
11663
11664 // Check the base classes.
11665 for (CXXRecordDecl::base_class_const_iterator
11666 Base1 = D1CXX->bases_begin(),
11667 BaseEnd1 = D1CXX->bases_end(),
11668 Base2 = D2CXX->bases_begin();
11669 Base1 != BaseEnd1;
11670 ++Base1, ++Base2) {
11671 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11672 return false;
11673 }
11674 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11675 // If only RD2 is a C++ class, it should have zero base classes.
11676 if (D2CXX->getNumBases() > 0)
11677 return false;
11678 }
11679
11680 // Check the fields.
11681 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11682 Field2End = RD2->field_end(),
11683 Field1 = RD1->field_begin(),
11684 Field1End = RD1->field_end();
11685 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11686 if (!isLayoutCompatible(C, *Field1, *Field2))
11687 return false;
11688 }
11689 if (Field1 != Field1End || Field2 != Field2End)
11690 return false;
11691
11692 return true;
11693}
11694
11695/// \brief Check if two standard-layout unions are layout-compatible.
11696/// (C++11 [class.mem] p18)
11697bool isLayoutCompatibleUnion(ASTContext &C,
11698 RecordDecl *RD1,
11699 RecordDecl *RD2) {
11700 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011701 for (auto *Field2 : RD2->fields())
11702 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011703
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011704 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011705 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11706 I = UnmatchedFields.begin(),
11707 E = UnmatchedFields.end();
11708
11709 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011710 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011711 bool Result = UnmatchedFields.erase(*I);
11712 (void) Result;
11713 assert(Result);
11714 break;
11715 }
11716 }
11717 if (I == E)
11718 return false;
11719 }
11720
11721 return UnmatchedFields.empty();
11722}
11723
11724bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11725 if (RD1->isUnion() != RD2->isUnion())
11726 return false;
11727
11728 if (RD1->isUnion())
11729 return isLayoutCompatibleUnion(C, RD1, RD2);
11730 else
11731 return isLayoutCompatibleStruct(C, RD1, RD2);
11732}
11733
11734/// \brief Check if two types are layout-compatible in C++11 sense.
11735bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11736 if (T1.isNull() || T2.isNull())
11737 return false;
11738
11739 // C++11 [basic.types] p11:
11740 // If two types T1 and T2 are the same type, then T1 and T2 are
11741 // layout-compatible types.
11742 if (C.hasSameType(T1, T2))
11743 return true;
11744
11745 T1 = T1.getCanonicalType().getUnqualifiedType();
11746 T2 = T2.getCanonicalType().getUnqualifiedType();
11747
11748 const Type::TypeClass TC1 = T1->getTypeClass();
11749 const Type::TypeClass TC2 = T2->getTypeClass();
11750
11751 if (TC1 != TC2)
11752 return false;
11753
11754 if (TC1 == Type::Enum) {
11755 return isLayoutCompatible(C,
11756 cast<EnumType>(T1)->getDecl(),
11757 cast<EnumType>(T2)->getDecl());
11758 } else if (TC1 == Type::Record) {
11759 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11760 return false;
11761
11762 return isLayoutCompatible(C,
11763 cast<RecordType>(T1)->getDecl(),
11764 cast<RecordType>(T2)->getDecl());
11765 }
11766
11767 return false;
11768}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011769} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011770
11771//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11772
11773namespace {
11774/// \brief Given a type tag expression find the type tag itself.
11775///
11776/// \param TypeExpr Type tag expression, as it appears in user's code.
11777///
11778/// \param VD Declaration of an identifier that appears in a type tag.
11779///
11780/// \param MagicValue Type tag magic value.
11781bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11782 const ValueDecl **VD, uint64_t *MagicValue) {
11783 while(true) {
11784 if (!TypeExpr)
11785 return false;
11786
11787 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11788
11789 switch (TypeExpr->getStmtClass()) {
11790 case Stmt::UnaryOperatorClass: {
11791 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11792 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11793 TypeExpr = UO->getSubExpr();
11794 continue;
11795 }
11796 return false;
11797 }
11798
11799 case Stmt::DeclRefExprClass: {
11800 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11801 *VD = DRE->getDecl();
11802 return true;
11803 }
11804
11805 case Stmt::IntegerLiteralClass: {
11806 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11807 llvm::APInt MagicValueAPInt = IL->getValue();
11808 if (MagicValueAPInt.getActiveBits() <= 64) {
11809 *MagicValue = MagicValueAPInt.getZExtValue();
11810 return true;
11811 } else
11812 return false;
11813 }
11814
11815 case Stmt::BinaryConditionalOperatorClass:
11816 case Stmt::ConditionalOperatorClass: {
11817 const AbstractConditionalOperator *ACO =
11818 cast<AbstractConditionalOperator>(TypeExpr);
11819 bool Result;
11820 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11821 if (Result)
11822 TypeExpr = ACO->getTrueExpr();
11823 else
11824 TypeExpr = ACO->getFalseExpr();
11825 continue;
11826 }
11827 return false;
11828 }
11829
11830 case Stmt::BinaryOperatorClass: {
11831 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11832 if (BO->getOpcode() == BO_Comma) {
11833 TypeExpr = BO->getRHS();
11834 continue;
11835 }
11836 return false;
11837 }
11838
11839 default:
11840 return false;
11841 }
11842 }
11843}
11844
11845/// \brief Retrieve the C type corresponding to type tag TypeExpr.
11846///
11847/// \param TypeExpr Expression that specifies a type tag.
11848///
11849/// \param MagicValues Registered magic values.
11850///
11851/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11852/// kind.
11853///
11854/// \param TypeInfo Information about the corresponding C type.
11855///
11856/// \returns true if the corresponding C type was found.
11857bool GetMatchingCType(
11858 const IdentifierInfo *ArgumentKind,
11859 const Expr *TypeExpr, const ASTContext &Ctx,
11860 const llvm::DenseMap<Sema::TypeTagMagicValue,
11861 Sema::TypeTagData> *MagicValues,
11862 bool &FoundWrongKind,
11863 Sema::TypeTagData &TypeInfo) {
11864 FoundWrongKind = false;
11865
11866 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000011867 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011868
11869 uint64_t MagicValue;
11870
11871 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11872 return false;
11873
11874 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000011875 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011876 if (I->getArgumentKind() != ArgumentKind) {
11877 FoundWrongKind = true;
11878 return false;
11879 }
11880 TypeInfo.Type = I->getMatchingCType();
11881 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11882 TypeInfo.MustBeNull = I->getMustBeNull();
11883 return true;
11884 }
11885 return false;
11886 }
11887
11888 if (!MagicValues)
11889 return false;
11890
11891 llvm::DenseMap<Sema::TypeTagMagicValue,
11892 Sema::TypeTagData>::const_iterator I =
11893 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11894 if (I == MagicValues->end())
11895 return false;
11896
11897 TypeInfo = I->second;
11898 return true;
11899}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011900} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011901
11902void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11903 uint64_t MagicValue, QualType Type,
11904 bool LayoutCompatible,
11905 bool MustBeNull) {
11906 if (!TypeTagForDatatypeMagicValues)
11907 TypeTagForDatatypeMagicValues.reset(
11908 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11909
11910 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11911 (*TypeTagForDatatypeMagicValues)[Magic] =
11912 TypeTagData(Type, LayoutCompatible, MustBeNull);
11913}
11914
11915namespace {
11916bool IsSameCharType(QualType T1, QualType T2) {
11917 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11918 if (!BT1)
11919 return false;
11920
11921 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11922 if (!BT2)
11923 return false;
11924
11925 BuiltinType::Kind T1Kind = BT1->getKind();
11926 BuiltinType::Kind T2Kind = BT2->getKind();
11927
11928 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
11929 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
11930 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11931 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11932}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011933} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011934
11935void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11936 const Expr * const *ExprArgs) {
11937 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11938 bool IsPointerAttr = Attr->getIsPointer();
11939
11940 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11941 bool FoundWrongKind;
11942 TypeTagData TypeInfo;
11943 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11944 TypeTagForDatatypeMagicValues.get(),
11945 FoundWrongKind, TypeInfo)) {
11946 if (FoundWrongKind)
11947 Diag(TypeTagExpr->getExprLoc(),
11948 diag::warn_type_tag_for_datatype_wrong_kind)
11949 << TypeTagExpr->getSourceRange();
11950 return;
11951 }
11952
11953 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11954 if (IsPointerAttr) {
11955 // Skip implicit cast of pointer to `void *' (as a function argument).
11956 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000011957 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000011958 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011959 ArgumentExpr = ICE->getSubExpr();
11960 }
11961 QualType ArgumentType = ArgumentExpr->getType();
11962
11963 // Passing a `void*' pointer shouldn't trigger a warning.
11964 if (IsPointerAttr && ArgumentType->isVoidPointerType())
11965 return;
11966
11967 if (TypeInfo.MustBeNull) {
11968 // Type tag with matching void type requires a null pointer.
11969 if (!ArgumentExpr->isNullPointerConstant(Context,
11970 Expr::NPC_ValueDependentIsNotNull)) {
11971 Diag(ArgumentExpr->getExprLoc(),
11972 diag::warn_type_safety_null_pointer_required)
11973 << ArgumentKind->getName()
11974 << ArgumentExpr->getSourceRange()
11975 << TypeTagExpr->getSourceRange();
11976 }
11977 return;
11978 }
11979
11980 QualType RequiredType = TypeInfo.Type;
11981 if (IsPointerAttr)
11982 RequiredType = Context.getPointerType(RequiredType);
11983
11984 bool mismatch = false;
11985 if (!TypeInfo.LayoutCompatible) {
11986 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
11987
11988 // C++11 [basic.fundamental] p1:
11989 // Plain char, signed char, and unsigned char are three distinct types.
11990 //
11991 // But we treat plain `char' as equivalent to `signed char' or `unsigned
11992 // char' depending on the current char signedness mode.
11993 if (mismatch)
11994 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
11995 RequiredType->getPointeeType())) ||
11996 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
11997 mismatch = false;
11998 } else
11999 if (IsPointerAttr)
12000 mismatch = !isLayoutCompatible(Context,
12001 ArgumentType->getPointeeType(),
12002 RequiredType->getPointeeType());
12003 else
12004 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12005
12006 if (mismatch)
12007 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000012008 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012009 << TypeInfo.LayoutCompatible << RequiredType
12010 << ArgumentExpr->getSourceRange()
12011 << TypeTagExpr->getSourceRange();
12012}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012013
12014void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12015 CharUnits Alignment) {
12016 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12017}
12018
12019void Sema::DiagnoseMisalignedMembers() {
12020 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000012021 const NamedDecl *ND = m.RD;
12022 if (ND->getName().empty()) {
12023 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12024 ND = TD;
12025 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012026 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000012027 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012028 }
12029 MisalignedMembers.clear();
12030}
12031
12032void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012033 E = E->IgnoreParens();
12034 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012035 return;
12036 if (isa<UnaryOperator>(E) &&
12037 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12038 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12039 if (isa<MemberExpr>(Op)) {
12040 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12041 MisalignedMember(Op));
12042 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012043 (T->isIntegerType() ||
12044 (T->isPointerType() &&
12045 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012046 MisalignedMembers.erase(MA);
12047 }
12048 }
12049}
12050
12051void Sema::RefersToMemberWithReducedAlignment(
12052 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000012053 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12054 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012055 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012056 if (!ME)
12057 return;
12058
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000012059 // No need to check expressions with an __unaligned-qualified type.
12060 if (E->getType().getQualifiers().hasUnaligned())
12061 return;
12062
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012063 // For a chain of MemberExpr like "a.b.c.d" this list
12064 // will keep FieldDecl's like [d, c, b].
12065 SmallVector<FieldDecl *, 4> ReverseMemberChain;
12066 const MemberExpr *TopME = nullptr;
12067 bool AnyIsPacked = false;
12068 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012069 QualType BaseType = ME->getBase()->getType();
12070 if (ME->isArrow())
12071 BaseType = BaseType->getPointeeType();
12072 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
12073
12074 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012075 auto *FD = dyn_cast<FieldDecl>(MD);
12076 // We do not care about non-data members.
12077 if (!FD || FD->isInvalidDecl())
12078 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012079
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012080 AnyIsPacked =
12081 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12082 ReverseMemberChain.push_back(FD);
12083
12084 TopME = ME;
12085 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12086 } while (ME);
12087 assert(TopME && "We did not compute a topmost MemberExpr!");
12088
12089 // Not the scope of this diagnostic.
12090 if (!AnyIsPacked)
12091 return;
12092
12093 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12094 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12095 // TODO: The innermost base of the member expression may be too complicated.
12096 // For now, just disregard these cases. This is left for future
12097 // improvement.
12098 if (!DRE && !isa<CXXThisExpr>(TopBase))
12099 return;
12100
12101 // Alignment expected by the whole expression.
12102 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12103
12104 // No need to do anything else with this case.
12105 if (ExpectedAlignment.isOne())
12106 return;
12107
12108 // Synthesize offset of the whole access.
12109 CharUnits Offset;
12110 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12111 I++) {
12112 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12113 }
12114
12115 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12116 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12117 ReverseMemberChain.back()->getParent()->getTypeForDecl());
12118
12119 // The base expression of the innermost MemberExpr may give
12120 // stronger guarantees than the class containing the member.
12121 if (DRE && !TopME->isArrow()) {
12122 const ValueDecl *VD = DRE->getDecl();
12123 if (!VD->getType()->isReferenceType())
12124 CompleteObjectAlignment =
12125 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12126 }
12127
12128 // Check if the synthesized offset fulfills the alignment.
12129 if (Offset % ExpectedAlignment != 0 ||
12130 // It may fulfill the offset it but the effective alignment may still be
12131 // lower than the expected expression alignment.
12132 CompleteObjectAlignment < ExpectedAlignment) {
12133 // If this happens, we want to determine a sensible culprit of this.
12134 // Intuitively, watching the chain of member expressions from right to
12135 // left, we start with the required alignment (as required by the field
12136 // type) but some packed attribute in that chain has reduced the alignment.
12137 // It may happen that another packed structure increases it again. But if
12138 // we are here such increase has not been enough. So pointing the first
12139 // FieldDecl that either is packed or else its RecordDecl is,
12140 // seems reasonable.
12141 FieldDecl *FD = nullptr;
12142 CharUnits Alignment;
12143 for (FieldDecl *FDI : ReverseMemberChain) {
12144 if (FDI->hasAttr<PackedAttr>() ||
12145 FDI->getParent()->hasAttr<PackedAttr>()) {
12146 FD = FDI;
12147 Alignment = std::min(
12148 Context.getTypeAlignInChars(FD->getType()),
12149 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12150 break;
12151 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012152 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012153 assert(FD && "We did not find a packed FieldDecl!");
12154 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012155 }
12156}
12157
12158void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12159 using namespace std::placeholders;
12160 RefersToMemberWithReducedAlignment(
12161 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12162 _2, _3, _4));
12163}
12164