blob: b794628db738d137b52a6283d1f355887431e603 [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:
Tony Jiang9aa2c032017-05-24 15:54:13 +00001700 case PPC::BI__builtin_vsx_xxsldwi:
Tony Jiangbbc48e92017-05-24 15:13:32 +00001701 return SemaBuiltinVSX(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00001702 }
1703 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1704}
1705
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001706bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1707 CallExpr *TheCall) {
1708 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1709 Expr *Arg = TheCall->getArg(0);
1710 llvm::APSInt AbortCode(32);
1711 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1712 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1713 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1714 << Arg->getSourceRange();
1715 }
1716
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001717 // For intrinsics which take an immediate value as part of the instruction,
1718 // range check them here.
1719 unsigned i = 0, l = 0, u = 0;
1720 switch (BuiltinID) {
1721 default: return false;
1722 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1723 case SystemZ::BI__builtin_s390_verimb:
1724 case SystemZ::BI__builtin_s390_verimh:
1725 case SystemZ::BI__builtin_s390_verimf:
1726 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1727 case SystemZ::BI__builtin_s390_vfaeb:
1728 case SystemZ::BI__builtin_s390_vfaeh:
1729 case SystemZ::BI__builtin_s390_vfaef:
1730 case SystemZ::BI__builtin_s390_vfaebs:
1731 case SystemZ::BI__builtin_s390_vfaehs:
1732 case SystemZ::BI__builtin_s390_vfaefs:
1733 case SystemZ::BI__builtin_s390_vfaezb:
1734 case SystemZ::BI__builtin_s390_vfaezh:
1735 case SystemZ::BI__builtin_s390_vfaezf:
1736 case SystemZ::BI__builtin_s390_vfaezbs:
1737 case SystemZ::BI__builtin_s390_vfaezhs:
1738 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1739 case SystemZ::BI__builtin_s390_vfidb:
1740 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1741 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1742 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1743 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1744 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1745 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1746 case SystemZ::BI__builtin_s390_vstrcb:
1747 case SystemZ::BI__builtin_s390_vstrch:
1748 case SystemZ::BI__builtin_s390_vstrcf:
1749 case SystemZ::BI__builtin_s390_vstrczb:
1750 case SystemZ::BI__builtin_s390_vstrczh:
1751 case SystemZ::BI__builtin_s390_vstrczf:
1752 case SystemZ::BI__builtin_s390_vstrcbs:
1753 case SystemZ::BI__builtin_s390_vstrchs:
1754 case SystemZ::BI__builtin_s390_vstrcfs:
1755 case SystemZ::BI__builtin_s390_vstrczbs:
1756 case SystemZ::BI__builtin_s390_vstrczhs:
1757 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1758 }
1759 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001760}
1761
Craig Topper5ba2c502015-11-07 08:08:31 +00001762/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1763/// This checks that the target supports __builtin_cpu_supports and
1764/// that the string argument is constant and valid.
1765static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1766 Expr *Arg = TheCall->getArg(0);
1767
1768 // Check if the argument is a string literal.
1769 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1770 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1771 << Arg->getSourceRange();
1772
1773 // Check the contents of the string.
1774 StringRef Feature =
1775 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1776 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1777 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1778 << Arg->getSourceRange();
1779 return false;
1780}
1781
Craig Toppera7e253e2016-09-23 04:48:31 +00001782// Check if the rounding mode is legal.
1783bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1784 // Indicates if this instruction has rounding control or just SAE.
1785 bool HasRC = false;
1786
1787 unsigned ArgNum = 0;
1788 switch (BuiltinID) {
1789 default:
1790 return false;
1791 case X86::BI__builtin_ia32_vcvttsd2si32:
1792 case X86::BI__builtin_ia32_vcvttsd2si64:
1793 case X86::BI__builtin_ia32_vcvttsd2usi32:
1794 case X86::BI__builtin_ia32_vcvttsd2usi64:
1795 case X86::BI__builtin_ia32_vcvttss2si32:
1796 case X86::BI__builtin_ia32_vcvttss2si64:
1797 case X86::BI__builtin_ia32_vcvttss2usi32:
1798 case X86::BI__builtin_ia32_vcvttss2usi64:
1799 ArgNum = 1;
1800 break;
1801 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1802 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1803 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1804 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1805 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1806 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1807 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1808 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1809 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1810 case X86::BI__builtin_ia32_exp2pd_mask:
1811 case X86::BI__builtin_ia32_exp2ps_mask:
1812 case X86::BI__builtin_ia32_getexppd512_mask:
1813 case X86::BI__builtin_ia32_getexpps512_mask:
1814 case X86::BI__builtin_ia32_rcp28pd_mask:
1815 case X86::BI__builtin_ia32_rcp28ps_mask:
1816 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1817 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1818 case X86::BI__builtin_ia32_vcomisd:
1819 case X86::BI__builtin_ia32_vcomiss:
1820 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1821 ArgNum = 3;
1822 break;
1823 case X86::BI__builtin_ia32_cmppd512_mask:
1824 case X86::BI__builtin_ia32_cmpps512_mask:
1825 case X86::BI__builtin_ia32_cmpsd_mask:
1826 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001827 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001828 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1829 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001830 case X86::BI__builtin_ia32_maxpd512_mask:
1831 case X86::BI__builtin_ia32_maxps512_mask:
1832 case X86::BI__builtin_ia32_maxsd_round_mask:
1833 case X86::BI__builtin_ia32_maxss_round_mask:
1834 case X86::BI__builtin_ia32_minpd512_mask:
1835 case X86::BI__builtin_ia32_minps512_mask:
1836 case X86::BI__builtin_ia32_minsd_round_mask:
1837 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001838 case X86::BI__builtin_ia32_rcp28sd_round_mask:
1839 case X86::BI__builtin_ia32_rcp28ss_round_mask:
1840 case X86::BI__builtin_ia32_reducepd512_mask:
1841 case X86::BI__builtin_ia32_reduceps512_mask:
1842 case X86::BI__builtin_ia32_rndscalepd_mask:
1843 case X86::BI__builtin_ia32_rndscaleps_mask:
1844 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1845 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1846 ArgNum = 4;
1847 break;
1848 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001849 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001850 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001851 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001852 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001853 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001854 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001855 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001856 case X86::BI__builtin_ia32_rangepd512_mask:
1857 case X86::BI__builtin_ia32_rangeps512_mask:
1858 case X86::BI__builtin_ia32_rangesd128_round_mask:
1859 case X86::BI__builtin_ia32_rangess128_round_mask:
1860 case X86::BI__builtin_ia32_reducesd_mask:
1861 case X86::BI__builtin_ia32_reducess_mask:
1862 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1863 case X86::BI__builtin_ia32_rndscaless_round_mask:
1864 ArgNum = 5;
1865 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00001866 case X86::BI__builtin_ia32_vcvtsd2si64:
1867 case X86::BI__builtin_ia32_vcvtsd2si32:
1868 case X86::BI__builtin_ia32_vcvtsd2usi32:
1869 case X86::BI__builtin_ia32_vcvtsd2usi64:
1870 case X86::BI__builtin_ia32_vcvtss2si32:
1871 case X86::BI__builtin_ia32_vcvtss2si64:
1872 case X86::BI__builtin_ia32_vcvtss2usi32:
1873 case X86::BI__builtin_ia32_vcvtss2usi64:
1874 ArgNum = 1;
1875 HasRC = true;
1876 break;
Craig Topper8e066312016-11-07 07:01:09 +00001877 case X86::BI__builtin_ia32_cvtsi2sd64:
1878 case X86::BI__builtin_ia32_cvtsi2ss32:
1879 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00001880 case X86::BI__builtin_ia32_cvtusi2sd64:
1881 case X86::BI__builtin_ia32_cvtusi2ss32:
1882 case X86::BI__builtin_ia32_cvtusi2ss64:
1883 ArgNum = 2;
1884 HasRC = true;
1885 break;
1886 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1887 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1888 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1889 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1890 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1891 case X86::BI__builtin_ia32_cvtps2qq512_mask:
1892 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1893 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1894 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1895 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1896 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001897 case X86::BI__builtin_ia32_sqrtpd512_mask:
1898 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001899 ArgNum = 3;
1900 HasRC = true;
1901 break;
1902 case X86::BI__builtin_ia32_addpd512_mask:
1903 case X86::BI__builtin_ia32_addps512_mask:
1904 case X86::BI__builtin_ia32_divpd512_mask:
1905 case X86::BI__builtin_ia32_divps512_mask:
1906 case X86::BI__builtin_ia32_mulpd512_mask:
1907 case X86::BI__builtin_ia32_mulps512_mask:
1908 case X86::BI__builtin_ia32_subpd512_mask:
1909 case X86::BI__builtin_ia32_subps512_mask:
1910 case X86::BI__builtin_ia32_addss_round_mask:
1911 case X86::BI__builtin_ia32_addsd_round_mask:
1912 case X86::BI__builtin_ia32_divss_round_mask:
1913 case X86::BI__builtin_ia32_divsd_round_mask:
1914 case X86::BI__builtin_ia32_mulss_round_mask:
1915 case X86::BI__builtin_ia32_mulsd_round_mask:
1916 case X86::BI__builtin_ia32_subss_round_mask:
1917 case X86::BI__builtin_ia32_subsd_round_mask:
1918 case X86::BI__builtin_ia32_scalefpd512_mask:
1919 case X86::BI__builtin_ia32_scalefps512_mask:
1920 case X86::BI__builtin_ia32_scalefsd_round_mask:
1921 case X86::BI__builtin_ia32_scalefss_round_mask:
1922 case X86::BI__builtin_ia32_getmantpd512_mask:
1923 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001924 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
1925 case X86::BI__builtin_ia32_sqrtsd_round_mask:
1926 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001927 case X86::BI__builtin_ia32_vfmaddpd512_mask:
1928 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1929 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1930 case X86::BI__builtin_ia32_vfmaddps512_mask:
1931 case X86::BI__builtin_ia32_vfmaddps512_mask3:
1932 case X86::BI__builtin_ia32_vfmaddps512_maskz:
1933 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1934 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1935 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1936 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1937 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1938 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1939 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1940 case X86::BI__builtin_ia32_vfmsubps512_mask3:
1941 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1942 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1943 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1944 case X86::BI__builtin_ia32_vfnmaddps512_mask:
1945 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1946 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1947 case X86::BI__builtin_ia32_vfnmsubps512_mask:
1948 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1949 case X86::BI__builtin_ia32_vfmaddsd3_mask:
1950 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1951 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1952 case X86::BI__builtin_ia32_vfmaddss3_mask:
1953 case X86::BI__builtin_ia32_vfmaddss3_maskz:
1954 case X86::BI__builtin_ia32_vfmaddss3_mask3:
1955 ArgNum = 4;
1956 HasRC = true;
1957 break;
1958 case X86::BI__builtin_ia32_getmantsd_round_mask:
1959 case X86::BI__builtin_ia32_getmantss_round_mask:
1960 ArgNum = 5;
1961 HasRC = true;
1962 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00001963 }
1964
1965 llvm::APSInt Result;
1966
1967 // We can't check the value of a dependent argument.
1968 Expr *Arg = TheCall->getArg(ArgNum);
1969 if (Arg->isTypeDependent() || Arg->isValueDependent())
1970 return false;
1971
1972 // Check constant-ness first.
1973 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1974 return true;
1975
1976 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1977 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1978 // combined with ROUND_NO_EXC.
1979 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1980 Result == 8/*ROUND_NO_EXC*/ ||
1981 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1982 return false;
1983
1984 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1985 << Arg->getSourceRange();
1986}
1987
Craig Topperdf5beb22017-03-13 17:16:50 +00001988// Check if the gather/scatter scale is legal.
1989bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
1990 CallExpr *TheCall) {
1991 unsigned ArgNum = 0;
1992 switch (BuiltinID) {
1993 default:
1994 return false;
1995 case X86::BI__builtin_ia32_gatherpfdpd:
1996 case X86::BI__builtin_ia32_gatherpfdps:
1997 case X86::BI__builtin_ia32_gatherpfqpd:
1998 case X86::BI__builtin_ia32_gatherpfqps:
1999 case X86::BI__builtin_ia32_scatterpfdpd:
2000 case X86::BI__builtin_ia32_scatterpfdps:
2001 case X86::BI__builtin_ia32_scatterpfqpd:
2002 case X86::BI__builtin_ia32_scatterpfqps:
2003 ArgNum = 3;
2004 break;
2005 case X86::BI__builtin_ia32_gatherd_pd:
2006 case X86::BI__builtin_ia32_gatherd_pd256:
2007 case X86::BI__builtin_ia32_gatherq_pd:
2008 case X86::BI__builtin_ia32_gatherq_pd256:
2009 case X86::BI__builtin_ia32_gatherd_ps:
2010 case X86::BI__builtin_ia32_gatherd_ps256:
2011 case X86::BI__builtin_ia32_gatherq_ps:
2012 case X86::BI__builtin_ia32_gatherq_ps256:
2013 case X86::BI__builtin_ia32_gatherd_q:
2014 case X86::BI__builtin_ia32_gatherd_q256:
2015 case X86::BI__builtin_ia32_gatherq_q:
2016 case X86::BI__builtin_ia32_gatherq_q256:
2017 case X86::BI__builtin_ia32_gatherd_d:
2018 case X86::BI__builtin_ia32_gatherd_d256:
2019 case X86::BI__builtin_ia32_gatherq_d:
2020 case X86::BI__builtin_ia32_gatherq_d256:
2021 case X86::BI__builtin_ia32_gather3div2df:
2022 case X86::BI__builtin_ia32_gather3div2di:
2023 case X86::BI__builtin_ia32_gather3div4df:
2024 case X86::BI__builtin_ia32_gather3div4di:
2025 case X86::BI__builtin_ia32_gather3div4sf:
2026 case X86::BI__builtin_ia32_gather3div4si:
2027 case X86::BI__builtin_ia32_gather3div8sf:
2028 case X86::BI__builtin_ia32_gather3div8si:
2029 case X86::BI__builtin_ia32_gather3siv2df:
2030 case X86::BI__builtin_ia32_gather3siv2di:
2031 case X86::BI__builtin_ia32_gather3siv4df:
2032 case X86::BI__builtin_ia32_gather3siv4di:
2033 case X86::BI__builtin_ia32_gather3siv4sf:
2034 case X86::BI__builtin_ia32_gather3siv4si:
2035 case X86::BI__builtin_ia32_gather3siv8sf:
2036 case X86::BI__builtin_ia32_gather3siv8si:
2037 case X86::BI__builtin_ia32_gathersiv8df:
2038 case X86::BI__builtin_ia32_gathersiv16sf:
2039 case X86::BI__builtin_ia32_gatherdiv8df:
2040 case X86::BI__builtin_ia32_gatherdiv16sf:
2041 case X86::BI__builtin_ia32_gathersiv8di:
2042 case X86::BI__builtin_ia32_gathersiv16si:
2043 case X86::BI__builtin_ia32_gatherdiv8di:
2044 case X86::BI__builtin_ia32_gatherdiv16si:
2045 case X86::BI__builtin_ia32_scatterdiv2df:
2046 case X86::BI__builtin_ia32_scatterdiv2di:
2047 case X86::BI__builtin_ia32_scatterdiv4df:
2048 case X86::BI__builtin_ia32_scatterdiv4di:
2049 case X86::BI__builtin_ia32_scatterdiv4sf:
2050 case X86::BI__builtin_ia32_scatterdiv4si:
2051 case X86::BI__builtin_ia32_scatterdiv8sf:
2052 case X86::BI__builtin_ia32_scatterdiv8si:
2053 case X86::BI__builtin_ia32_scattersiv2df:
2054 case X86::BI__builtin_ia32_scattersiv2di:
2055 case X86::BI__builtin_ia32_scattersiv4df:
2056 case X86::BI__builtin_ia32_scattersiv4di:
2057 case X86::BI__builtin_ia32_scattersiv4sf:
2058 case X86::BI__builtin_ia32_scattersiv4si:
2059 case X86::BI__builtin_ia32_scattersiv8sf:
2060 case X86::BI__builtin_ia32_scattersiv8si:
2061 case X86::BI__builtin_ia32_scattersiv8df:
2062 case X86::BI__builtin_ia32_scattersiv16sf:
2063 case X86::BI__builtin_ia32_scatterdiv8df:
2064 case X86::BI__builtin_ia32_scatterdiv16sf:
2065 case X86::BI__builtin_ia32_scattersiv8di:
2066 case X86::BI__builtin_ia32_scattersiv16si:
2067 case X86::BI__builtin_ia32_scatterdiv8di:
2068 case X86::BI__builtin_ia32_scatterdiv16si:
2069 ArgNum = 4;
2070 break;
2071 }
2072
2073 llvm::APSInt Result;
2074
2075 // We can't check the value of a dependent argument.
2076 Expr *Arg = TheCall->getArg(ArgNum);
2077 if (Arg->isTypeDependent() || Arg->isValueDependent())
2078 return false;
2079
2080 // Check constant-ness first.
2081 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2082 return true;
2083
2084 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2085 return false;
2086
2087 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2088 << Arg->getSourceRange();
2089}
2090
Craig Topperf0ddc892016-09-23 04:48:27 +00002091bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2092 if (BuiltinID == X86::BI__builtin_cpu_supports)
2093 return SemaBuiltinCpuSupports(*this, TheCall);
2094
2095 if (BuiltinID == X86::BI__builtin_ms_va_start)
Reid Kleckner2b0fa122017-05-02 20:10:03 +00002096 return SemaBuiltinVAStart(BuiltinID, TheCall);
Craig Topperf0ddc892016-09-23 04:48:27 +00002097
Craig Toppera7e253e2016-09-23 04:48:31 +00002098 // If the intrinsic has rounding or SAE make sure its valid.
2099 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2100 return true;
2101
Craig Topperdf5beb22017-03-13 17:16:50 +00002102 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2103 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2104 return true;
2105
Craig Topperf0ddc892016-09-23 04:48:27 +00002106 // For intrinsics which take an immediate value as part of the instruction,
2107 // range check them here.
2108 int i = 0, l = 0, u = 0;
2109 switch (BuiltinID) {
2110 default:
2111 return false;
Richard Trieucc3949d2016-02-18 22:34:54 +00002112 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00002113 i = 1; l = 0; u = 3;
2114 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002115 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00002116 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2117 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2118 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2119 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002120 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002121 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002122 case X86::BI__builtin_ia32_vpermil2pd:
2123 case X86::BI__builtin_ia32_vpermil2pd256:
2124 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002125 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002126 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002127 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002128 case X86::BI__builtin_ia32_cmpb128_mask:
2129 case X86::BI__builtin_ia32_cmpw128_mask:
2130 case X86::BI__builtin_ia32_cmpd128_mask:
2131 case X86::BI__builtin_ia32_cmpq128_mask:
2132 case X86::BI__builtin_ia32_cmpb256_mask:
2133 case X86::BI__builtin_ia32_cmpw256_mask:
2134 case X86::BI__builtin_ia32_cmpd256_mask:
2135 case X86::BI__builtin_ia32_cmpq256_mask:
2136 case X86::BI__builtin_ia32_cmpb512_mask:
2137 case X86::BI__builtin_ia32_cmpw512_mask:
2138 case X86::BI__builtin_ia32_cmpd512_mask:
2139 case X86::BI__builtin_ia32_cmpq512_mask:
2140 case X86::BI__builtin_ia32_ucmpb128_mask:
2141 case X86::BI__builtin_ia32_ucmpw128_mask:
2142 case X86::BI__builtin_ia32_ucmpd128_mask:
2143 case X86::BI__builtin_ia32_ucmpq128_mask:
2144 case X86::BI__builtin_ia32_ucmpb256_mask:
2145 case X86::BI__builtin_ia32_ucmpw256_mask:
2146 case X86::BI__builtin_ia32_ucmpd256_mask:
2147 case X86::BI__builtin_ia32_ucmpq256_mask:
2148 case X86::BI__builtin_ia32_ucmpb512_mask:
2149 case X86::BI__builtin_ia32_ucmpw512_mask:
2150 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002151 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002152 case X86::BI__builtin_ia32_vpcomub:
2153 case X86::BI__builtin_ia32_vpcomuw:
2154 case X86::BI__builtin_ia32_vpcomud:
2155 case X86::BI__builtin_ia32_vpcomuq:
2156 case X86::BI__builtin_ia32_vpcomb:
2157 case X86::BI__builtin_ia32_vpcomw:
2158 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002159 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00002160 i = 2; l = 0; u = 7;
2161 break;
2162 case X86::BI__builtin_ia32_roundps:
2163 case X86::BI__builtin_ia32_roundpd:
2164 case X86::BI__builtin_ia32_roundps256:
2165 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002166 i = 1; l = 0; u = 15;
2167 break;
2168 case X86::BI__builtin_ia32_roundss:
2169 case X86::BI__builtin_ia32_roundsd:
2170 case X86::BI__builtin_ia32_rangepd128_mask:
2171 case X86::BI__builtin_ia32_rangepd256_mask:
2172 case X86::BI__builtin_ia32_rangepd512_mask:
2173 case X86::BI__builtin_ia32_rangeps128_mask:
2174 case X86::BI__builtin_ia32_rangeps256_mask:
2175 case X86::BI__builtin_ia32_rangeps512_mask:
2176 case X86::BI__builtin_ia32_getmantsd_round_mask:
2177 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002178 i = 2; l = 0; u = 15;
2179 break;
2180 case X86::BI__builtin_ia32_cmpps:
2181 case X86::BI__builtin_ia32_cmpss:
2182 case X86::BI__builtin_ia32_cmppd:
2183 case X86::BI__builtin_ia32_cmpsd:
2184 case X86::BI__builtin_ia32_cmpps256:
2185 case X86::BI__builtin_ia32_cmppd256:
2186 case X86::BI__builtin_ia32_cmpps128_mask:
2187 case X86::BI__builtin_ia32_cmppd128_mask:
2188 case X86::BI__builtin_ia32_cmpps256_mask:
2189 case X86::BI__builtin_ia32_cmppd256_mask:
2190 case X86::BI__builtin_ia32_cmpps512_mask:
2191 case X86::BI__builtin_ia32_cmppd512_mask:
2192 case X86::BI__builtin_ia32_cmpsd_mask:
2193 case X86::BI__builtin_ia32_cmpss_mask:
2194 i = 2; l = 0; u = 31;
2195 break;
2196 case X86::BI__builtin_ia32_xabort:
2197 i = 0; l = -128; u = 255;
2198 break;
2199 case X86::BI__builtin_ia32_pshufw:
2200 case X86::BI__builtin_ia32_aeskeygenassist128:
2201 i = 1; l = -128; u = 255;
2202 break;
2203 case X86::BI__builtin_ia32_vcvtps2ph:
2204 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper39c87102016-05-18 03:18:12 +00002205 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2206 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2207 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2208 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2209 case X86::BI__builtin_ia32_rndscaleps_mask:
2210 case X86::BI__builtin_ia32_rndscalepd_mask:
2211 case X86::BI__builtin_ia32_reducepd128_mask:
2212 case X86::BI__builtin_ia32_reducepd256_mask:
2213 case X86::BI__builtin_ia32_reducepd512_mask:
2214 case X86::BI__builtin_ia32_reduceps128_mask:
2215 case X86::BI__builtin_ia32_reduceps256_mask:
2216 case X86::BI__builtin_ia32_reduceps512_mask:
2217 case X86::BI__builtin_ia32_prold512_mask:
2218 case X86::BI__builtin_ia32_prolq512_mask:
2219 case X86::BI__builtin_ia32_prold128_mask:
2220 case X86::BI__builtin_ia32_prold256_mask:
2221 case X86::BI__builtin_ia32_prolq128_mask:
2222 case X86::BI__builtin_ia32_prolq256_mask:
2223 case X86::BI__builtin_ia32_prord128_mask:
2224 case X86::BI__builtin_ia32_prord256_mask:
2225 case X86::BI__builtin_ia32_prorq128_mask:
2226 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002227 case X86::BI__builtin_ia32_fpclasspd128_mask:
2228 case X86::BI__builtin_ia32_fpclasspd256_mask:
2229 case X86::BI__builtin_ia32_fpclassps128_mask:
2230 case X86::BI__builtin_ia32_fpclassps256_mask:
2231 case X86::BI__builtin_ia32_fpclassps512_mask:
2232 case X86::BI__builtin_ia32_fpclasspd512_mask:
2233 case X86::BI__builtin_ia32_fpclasssd_mask:
2234 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002235 i = 1; l = 0; u = 255;
2236 break;
2237 case X86::BI__builtin_ia32_palignr:
2238 case X86::BI__builtin_ia32_insertps128:
2239 case X86::BI__builtin_ia32_dpps:
2240 case X86::BI__builtin_ia32_dppd:
2241 case X86::BI__builtin_ia32_dpps256:
2242 case X86::BI__builtin_ia32_mpsadbw128:
2243 case X86::BI__builtin_ia32_mpsadbw256:
2244 case X86::BI__builtin_ia32_pcmpistrm128:
2245 case X86::BI__builtin_ia32_pcmpistri128:
2246 case X86::BI__builtin_ia32_pcmpistria128:
2247 case X86::BI__builtin_ia32_pcmpistric128:
2248 case X86::BI__builtin_ia32_pcmpistrio128:
2249 case X86::BI__builtin_ia32_pcmpistris128:
2250 case X86::BI__builtin_ia32_pcmpistriz128:
2251 case X86::BI__builtin_ia32_pclmulqdq128:
2252 case X86::BI__builtin_ia32_vperm2f128_pd256:
2253 case X86::BI__builtin_ia32_vperm2f128_ps256:
2254 case X86::BI__builtin_ia32_vperm2f128_si256:
2255 case X86::BI__builtin_ia32_permti256:
2256 i = 2; l = -128; u = 255;
2257 break;
2258 case X86::BI__builtin_ia32_palignr128:
2259 case X86::BI__builtin_ia32_palignr256:
Craig Topper39c87102016-05-18 03:18:12 +00002260 case X86::BI__builtin_ia32_palignr512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002261 case X86::BI__builtin_ia32_vcomisd:
2262 case X86::BI__builtin_ia32_vcomiss:
2263 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2264 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2265 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2266 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002267 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2268 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2269 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2270 i = 2; l = 0; u = 255;
2271 break;
2272 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2273 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2274 case X86::BI__builtin_ia32_fixupimmps512_mask:
2275 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2276 case X86::BI__builtin_ia32_fixupimmsd_mask:
2277 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2278 case X86::BI__builtin_ia32_fixupimmss_mask:
2279 case X86::BI__builtin_ia32_fixupimmss_maskz:
2280 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2281 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2282 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2283 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2284 case X86::BI__builtin_ia32_fixupimmps128_mask:
2285 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2286 case X86::BI__builtin_ia32_fixupimmps256_mask:
2287 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2288 case X86::BI__builtin_ia32_pternlogd512_mask:
2289 case X86::BI__builtin_ia32_pternlogd512_maskz:
2290 case X86::BI__builtin_ia32_pternlogq512_mask:
2291 case X86::BI__builtin_ia32_pternlogq512_maskz:
2292 case X86::BI__builtin_ia32_pternlogd128_mask:
2293 case X86::BI__builtin_ia32_pternlogd128_maskz:
2294 case X86::BI__builtin_ia32_pternlogd256_mask:
2295 case X86::BI__builtin_ia32_pternlogd256_maskz:
2296 case X86::BI__builtin_ia32_pternlogq128_mask:
2297 case X86::BI__builtin_ia32_pternlogq128_maskz:
2298 case X86::BI__builtin_ia32_pternlogq256_mask:
2299 case X86::BI__builtin_ia32_pternlogq256_maskz:
2300 i = 3; l = 0; u = 255;
2301 break;
Craig Topper9625db02017-03-12 22:19:10 +00002302 case X86::BI__builtin_ia32_gatherpfdpd:
2303 case X86::BI__builtin_ia32_gatherpfdps:
2304 case X86::BI__builtin_ia32_gatherpfqpd:
2305 case X86::BI__builtin_ia32_gatherpfqps:
2306 case X86::BI__builtin_ia32_scatterpfdpd:
2307 case X86::BI__builtin_ia32_scatterpfdps:
2308 case X86::BI__builtin_ia32_scatterpfqpd:
2309 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00002310 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00002311 break;
Craig Topper39c87102016-05-18 03:18:12 +00002312 case X86::BI__builtin_ia32_pcmpestrm128:
2313 case X86::BI__builtin_ia32_pcmpestri128:
2314 case X86::BI__builtin_ia32_pcmpestria128:
2315 case X86::BI__builtin_ia32_pcmpestric128:
2316 case X86::BI__builtin_ia32_pcmpestrio128:
2317 case X86::BI__builtin_ia32_pcmpestris128:
2318 case X86::BI__builtin_ia32_pcmpestriz128:
2319 i = 4; l = -128; u = 255;
2320 break;
2321 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2322 case X86::BI__builtin_ia32_rndscaless_round_mask:
2323 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002324 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002325 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002326 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002327}
2328
Richard Smith55ce3522012-06-25 20:30:08 +00002329/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2330/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2331/// Returns true when the format fits the function and the FormatStringInfo has
2332/// been populated.
2333bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2334 FormatStringInfo *FSI) {
2335 FSI->HasVAListArg = Format->getFirstArg() == 0;
2336 FSI->FormatIdx = Format->getFormatIdx() - 1;
2337 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002338
Richard Smith55ce3522012-06-25 20:30:08 +00002339 // The way the format attribute works in GCC, the implicit this argument
2340 // of member functions is counted. However, it doesn't appear in our own
2341 // lists, so decrement format_idx in that case.
2342 if (IsCXXMember) {
2343 if(FSI->FormatIdx == 0)
2344 return false;
2345 --FSI->FormatIdx;
2346 if (FSI->FirstDataArg != 0)
2347 --FSI->FirstDataArg;
2348 }
2349 return true;
2350}
Mike Stump11289f42009-09-09 15:08:12 +00002351
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002352/// Checks if a the given expression evaluates to null.
2353///
2354/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002355static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002356 // If the expression has non-null type, it doesn't evaluate to null.
2357 if (auto nullability
2358 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2359 if (*nullability == NullabilityKind::NonNull)
2360 return false;
2361 }
2362
Ted Kremeneka146db32014-01-17 06:24:47 +00002363 // As a special case, transparent unions initialized with zero are
2364 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002365 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002366 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2367 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002368 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002369 if (const InitListExpr *ILE =
2370 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002371 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002372 }
2373
2374 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002375 return (!Expr->isValueDependent() &&
2376 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2377 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002378}
2379
2380static void CheckNonNullArgument(Sema &S,
2381 const Expr *ArgExpr,
2382 SourceLocation CallSiteLoc) {
2383 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002384 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2385 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002386}
2387
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002388bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2389 FormatStringInfo FSI;
2390 if ((GetFormatStringType(Format) == FST_NSString) &&
2391 getFormatStringInfo(Format, false, &FSI)) {
2392 Idx = FSI.FormatIdx;
2393 return true;
2394 }
2395 return false;
2396}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002397/// \brief Diagnose use of %s directive in an NSString which is being passed
2398/// as formatting string to formatting method.
2399static void
2400DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2401 const NamedDecl *FDecl,
2402 Expr **Args,
2403 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002404 unsigned Idx = 0;
2405 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002406 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2407 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002408 Idx = 2;
2409 Format = true;
2410 }
2411 else
2412 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2413 if (S.GetFormatNSStringIdx(I, Idx)) {
2414 Format = true;
2415 break;
2416 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002417 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002418 if (!Format || NumArgs <= Idx)
2419 return;
2420 const Expr *FormatExpr = Args[Idx];
2421 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2422 FormatExpr = CSCE->getSubExpr();
2423 const StringLiteral *FormatString;
2424 if (const ObjCStringLiteral *OSL =
2425 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2426 FormatString = OSL->getString();
2427 else
2428 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2429 if (!FormatString)
2430 return;
2431 if (S.FormatStringHasSArg(FormatString)) {
2432 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2433 << "%s" << 1 << 1;
2434 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2435 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002436 }
2437}
2438
Douglas Gregorb4866e82015-06-19 18:13:19 +00002439/// Determine whether the given type has a non-null nullability annotation.
2440static bool isNonNullType(ASTContext &ctx, QualType type) {
2441 if (auto nullability = type->getNullability(ctx))
2442 return *nullability == NullabilityKind::NonNull;
2443
2444 return false;
2445}
2446
Ted Kremenek2bc73332014-01-17 06:24:43 +00002447static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002448 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002449 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002450 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002451 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002452 assert((FDecl || Proto) && "Need a function declaration or prototype");
2453
Ted Kremenek9aedc152014-01-17 06:24:56 +00002454 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002455 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002456 if (FDecl) {
2457 // Handle the nonnull attribute on the function/method declaration itself.
2458 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2459 if (!NonNull->args_size()) {
2460 // Easy case: all pointer arguments are nonnull.
2461 for (const auto *Arg : Args)
2462 if (S.isValidPointerAttrType(Arg->getType()))
2463 CheckNonNullArgument(S, Arg, CallSiteLoc);
2464 return;
2465 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002466
Douglas Gregorb4866e82015-06-19 18:13:19 +00002467 for (unsigned Val : NonNull->args()) {
2468 if (Val >= Args.size())
2469 continue;
2470 if (NonNullArgs.empty())
2471 NonNullArgs.resize(Args.size());
2472 NonNullArgs.set(Val);
2473 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002474 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002475 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002476
Douglas Gregorb4866e82015-06-19 18:13:19 +00002477 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2478 // Handle the nonnull attribute on the parameters of the
2479 // function/method.
2480 ArrayRef<ParmVarDecl*> parms;
2481 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2482 parms = FD->parameters();
2483 else
2484 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2485
2486 unsigned ParamIndex = 0;
2487 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2488 I != E; ++I, ++ParamIndex) {
2489 const ParmVarDecl *PVD = *I;
2490 if (PVD->hasAttr<NonNullAttr>() ||
2491 isNonNullType(S.Context, PVD->getType())) {
2492 if (NonNullArgs.empty())
2493 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002494
Douglas Gregorb4866e82015-06-19 18:13:19 +00002495 NonNullArgs.set(ParamIndex);
2496 }
2497 }
2498 } else {
2499 // If we have a non-function, non-method declaration but no
2500 // function prototype, try to dig out the function prototype.
2501 if (!Proto) {
2502 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2503 QualType type = VD->getType().getNonReferenceType();
2504 if (auto pointerType = type->getAs<PointerType>())
2505 type = pointerType->getPointeeType();
2506 else if (auto blockType = type->getAs<BlockPointerType>())
2507 type = blockType->getPointeeType();
2508 // FIXME: data member pointers?
2509
2510 // Dig out the function prototype, if there is one.
2511 Proto = type->getAs<FunctionProtoType>();
2512 }
2513 }
2514
2515 // Fill in non-null argument information from the nullability
2516 // information on the parameter types (if we have them).
2517 if (Proto) {
2518 unsigned Index = 0;
2519 for (auto paramType : Proto->getParamTypes()) {
2520 if (isNonNullType(S.Context, paramType)) {
2521 if (NonNullArgs.empty())
2522 NonNullArgs.resize(Args.size());
2523
2524 NonNullArgs.set(Index);
2525 }
2526
2527 ++Index;
2528 }
2529 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002530 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002531
Douglas Gregorb4866e82015-06-19 18:13:19 +00002532 // Check for non-null arguments.
2533 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2534 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002535 if (NonNullArgs[ArgIndex])
2536 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002537 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002538}
2539
Richard Smith55ce3522012-06-25 20:30:08 +00002540/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00002541/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2542/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002543void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00002544 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2545 bool IsMemberFunction, SourceLocation Loc,
2546 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002547 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002548 if (CurContext->isDependentContext())
2549 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002550
Ted Kremenekb8176da2010-09-09 04:33:05 +00002551 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002552 llvm::SmallBitVector CheckedVarArgs;
2553 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002554 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002555 // Only create vector if there are format attributes.
2556 CheckedVarArgs.resize(Args.size());
2557
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002558 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002559 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002560 }
Richard Smithd7293d72013-08-05 18:49:43 +00002561 }
Richard Smith55ce3522012-06-25 20:30:08 +00002562
2563 // Refuse POD arguments that weren't caught by the format string
2564 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00002565 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2566 if (CallType != VariadicDoesNotApply &&
2567 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002568 unsigned NumParams = Proto ? Proto->getNumParams()
2569 : FDecl && isa<FunctionDecl>(FDecl)
2570 ? cast<FunctionDecl>(FDecl)->getNumParams()
2571 : FDecl && isa<ObjCMethodDecl>(FDecl)
2572 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2573 : 0;
2574
Alp Toker9cacbab2014-01-20 20:26:09 +00002575 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002576 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002577 if (const Expr *Arg = Args[ArgIdx]) {
2578 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2579 checkVariadicArgument(Arg, CallType);
2580 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002581 }
Richard Smithd7293d72013-08-05 18:49:43 +00002582 }
Mike Stump11289f42009-09-09 15:08:12 +00002583
Douglas Gregorb4866e82015-06-19 18:13:19 +00002584 if (FDecl || Proto) {
2585 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002586
Richard Trieu41bc0992013-06-22 00:20:41 +00002587 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002588 if (FDecl) {
2589 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2590 CheckArgumentWithTypeTag(I, Args.data());
2591 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002592 }
George Burgess IVce6284b2017-01-28 02:19:40 +00002593
2594 if (FD)
2595 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00002596}
2597
2598/// CheckConstructorCall - Check a constructor call for correctness and safety
2599/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002600void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2601 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002602 const FunctionProtoType *Proto,
2603 SourceLocation Loc) {
2604 VariadicCallType CallType =
2605 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00002606 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2607 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002608}
2609
2610/// CheckFunctionCall - Check a direct function call for various correctness
2611/// and safety properties not strictly enforced by the C type system.
2612bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2613 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002614 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2615 isa<CXXMethodDecl>(FDecl);
2616 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2617 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002618 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2619 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002620 Expr** Args = TheCall->getArgs();
2621 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00002622
2623 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00002624 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002625 // If this is a call to a member operator, hide the first argument
2626 // from checkCall.
2627 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00002628 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00002629 ++Args;
2630 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00002631 } else if (IsMemberFunction)
2632 ImplicitThis =
2633 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2634
2635 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002636 IsMemberFunction, TheCall->getRParenLoc(),
2637 TheCall->getCallee()->getSourceRange(), CallType);
2638
2639 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2640 // None of the checks below are needed for functions that don't have
2641 // simple names (e.g., C++ conversion functions).
2642 if (!FnInfo)
2643 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002644
Richard Trieua7f30b12016-12-06 01:42:28 +00002645 CheckAbsoluteValueFunction(TheCall, FDecl);
2646 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00002647
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002648 if (getLangOpts().ObjC1)
2649 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002650
Anna Zaks22122702012-01-17 00:37:07 +00002651 unsigned CMId = FDecl->getMemoryFunctionKind();
2652 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002653 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002654
Anna Zaks201d4892012-01-13 21:52:01 +00002655 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002656 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002657 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002658 else if (CMId == Builtin::BIstrncat)
2659 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002660 else
Anna Zaks22122702012-01-17 00:37:07 +00002661 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002662
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002663 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002664}
2665
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002666bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002667 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002668 VariadicCallType CallType =
2669 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002670
George Burgess IVce6284b2017-01-28 02:19:40 +00002671 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2672 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002673 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002674
2675 return false;
2676}
2677
Richard Trieu664c4c62013-06-20 21:03:13 +00002678bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2679 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002680 QualType Ty;
2681 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002682 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002683 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002684 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002685 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002686 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002687
Douglas Gregorb4866e82015-06-19 18:13:19 +00002688 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2689 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002690 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002691
Richard Trieu664c4c62013-06-20 21:03:13 +00002692 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002693 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002694 CallType = VariadicDoesNotApply;
2695 } else if (Ty->isBlockPointerType()) {
2696 CallType = VariadicBlock;
2697 } else { // Ty->isFunctionPointerType()
2698 CallType = VariadicFunction;
2699 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002700
George Burgess IVce6284b2017-01-28 02:19:40 +00002701 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002702 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2703 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002704 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002705
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002706 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002707}
2708
Richard Trieu41bc0992013-06-22 00:20:41 +00002709/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2710/// such as function pointers returned from functions.
2711bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002712 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002713 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00002714 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002715 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002716 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002717 TheCall->getCallee()->getSourceRange(), CallType);
2718
2719 return false;
2720}
2721
Tim Northovere94a34c2014-03-11 10:49:14 +00002722static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002723 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002724 return false;
2725
JF Bastiendda2cb12016-04-18 18:01:49 +00002726 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002727 switch (Op) {
2728 case AtomicExpr::AO__c11_atomic_init:
2729 llvm_unreachable("There is no ordering argument for an init");
2730
2731 case AtomicExpr::AO__c11_atomic_load:
2732 case AtomicExpr::AO__atomic_load_n:
2733 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002734 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2735 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002736
2737 case AtomicExpr::AO__c11_atomic_store:
2738 case AtomicExpr::AO__atomic_store:
2739 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002740 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2741 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2742 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002743
2744 default:
2745 return true;
2746 }
2747}
2748
Richard Smithfeea8832012-04-12 05:08:17 +00002749ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2750 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002751 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2752 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002753
Richard Smithfeea8832012-04-12 05:08:17 +00002754 // All these operations take one of the following forms:
2755 enum {
2756 // C __c11_atomic_init(A *, C)
2757 Init,
2758 // C __c11_atomic_load(A *, int)
2759 Load,
2760 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002761 LoadCopy,
2762 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002763 Copy,
2764 // C __c11_atomic_add(A *, M, int)
2765 Arithmetic,
2766 // C __atomic_exchange_n(A *, CP, int)
2767 Xchg,
2768 // void __atomic_exchange(A *, C *, CP, int)
2769 GNUXchg,
2770 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2771 C11CmpXchg,
2772 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2773 GNUCmpXchg
2774 } Form = Init;
Eric Fiselier8d662442016-03-30 23:39:56 +00002775 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2776 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002777 // where:
2778 // C is an appropriate type,
2779 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2780 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2781 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2782 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002783
Gabor Horvath98bd0982015-03-16 09:59:54 +00002784 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2785 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2786 AtomicExpr::AO__atomic_load,
2787 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00002788 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2789 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2790 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2791 Op == AtomicExpr::AO__atomic_store_n ||
2792 Op == AtomicExpr::AO__atomic_exchange_n ||
2793 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2794 bool IsAddSub = false;
2795
2796 switch (Op) {
2797 case AtomicExpr::AO__c11_atomic_init:
2798 Form = Init;
2799 break;
2800
2801 case AtomicExpr::AO__c11_atomic_load:
2802 case AtomicExpr::AO__atomic_load_n:
2803 Form = Load;
2804 break;
2805
Richard Smithfeea8832012-04-12 05:08:17 +00002806 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002807 Form = LoadCopy;
2808 break;
2809
2810 case AtomicExpr::AO__c11_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002811 case AtomicExpr::AO__atomic_store:
2812 case AtomicExpr::AO__atomic_store_n:
2813 Form = Copy;
2814 break;
2815
2816 case AtomicExpr::AO__c11_atomic_fetch_add:
2817 case AtomicExpr::AO__c11_atomic_fetch_sub:
2818 case AtomicExpr::AO__atomic_fetch_add:
2819 case AtomicExpr::AO__atomic_fetch_sub:
2820 case AtomicExpr::AO__atomic_add_fetch:
2821 case AtomicExpr::AO__atomic_sub_fetch:
2822 IsAddSub = true;
2823 // Fall through.
2824 case AtomicExpr::AO__c11_atomic_fetch_and:
2825 case AtomicExpr::AO__c11_atomic_fetch_or:
2826 case AtomicExpr::AO__c11_atomic_fetch_xor:
2827 case AtomicExpr::AO__atomic_fetch_and:
2828 case AtomicExpr::AO__atomic_fetch_or:
2829 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00002830 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00002831 case AtomicExpr::AO__atomic_and_fetch:
2832 case AtomicExpr::AO__atomic_or_fetch:
2833 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00002834 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00002835 Form = Arithmetic;
2836 break;
2837
2838 case AtomicExpr::AO__c11_atomic_exchange:
2839 case AtomicExpr::AO__atomic_exchange_n:
2840 Form = Xchg;
2841 break;
2842
2843 case AtomicExpr::AO__atomic_exchange:
2844 Form = GNUXchg;
2845 break;
2846
2847 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2848 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2849 Form = C11CmpXchg;
2850 break;
2851
2852 case AtomicExpr::AO__atomic_compare_exchange:
2853 case AtomicExpr::AO__atomic_compare_exchange_n:
2854 Form = GNUCmpXchg;
2855 break;
2856 }
2857
2858 // Check we have the right number of arguments.
2859 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002860 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002861 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002862 << TheCall->getCallee()->getSourceRange();
2863 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00002864 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2865 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002866 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002867 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002868 << TheCall->getCallee()->getSourceRange();
2869 return ExprError();
2870 }
2871
Richard Smithfeea8832012-04-12 05:08:17 +00002872 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002873 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00002874 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2875 if (ConvertedPtr.isInvalid())
2876 return ExprError();
2877
2878 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002879 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2880 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00002881 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002882 << Ptr->getType() << Ptr->getSourceRange();
2883 return ExprError();
2884 }
2885
Richard Smithfeea8832012-04-12 05:08:17 +00002886 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2887 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2888 QualType ValType = AtomTy; // 'C'
2889 if (IsC11) {
2890 if (!AtomTy->isAtomicType()) {
2891 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2892 << Ptr->getType() << Ptr->getSourceRange();
2893 return ExprError();
2894 }
Richard Smithe00921a2012-09-15 06:09:58 +00002895 if (AtomTy.isConstQualified()) {
2896 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2897 << Ptr->getType() << Ptr->getSourceRange();
2898 return ExprError();
2899 }
Richard Smithfeea8832012-04-12 05:08:17 +00002900 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00002901 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002902 if (ValType.isConstQualified()) {
2903 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2904 << Ptr->getType() << Ptr->getSourceRange();
2905 return ExprError();
2906 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002907 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002908
Richard Smithfeea8832012-04-12 05:08:17 +00002909 // For an arithmetic operation, the implied arithmetic must be well-formed.
2910 if (Form == Arithmetic) {
2911 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2912 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2913 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2914 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2915 return ExprError();
2916 }
2917 if (!IsAddSub && !ValType->isIntegerType()) {
2918 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2919 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2920 return ExprError();
2921 }
David Majnemere85cff82015-01-28 05:48:06 +00002922 if (IsC11 && ValType->isPointerType() &&
2923 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2924 diag::err_incomplete_type)) {
2925 return ExprError();
2926 }
Richard Smithfeea8832012-04-12 05:08:17 +00002927 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2928 // For __atomic_*_n operations, the value type must be a scalar integral or
2929 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002930 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00002931 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2932 return ExprError();
2933 }
2934
Eli Friedmanaa769812013-09-11 03:49:34 +00002935 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2936 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00002937 // For GNU atomics, require a trivially-copyable type. This is not part of
2938 // the GNU atomics specification, but we enforce it for sanity.
2939 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002940 << Ptr->getType() << Ptr->getSourceRange();
2941 return ExprError();
2942 }
2943
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002944 switch (ValType.getObjCLifetime()) {
2945 case Qualifiers::OCL_None:
2946 case Qualifiers::OCL_ExplicitNone:
2947 // okay
2948 break;
2949
2950 case Qualifiers::OCL_Weak:
2951 case Qualifiers::OCL_Strong:
2952 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002953 // FIXME: Can this happen? By this point, ValType should be known
2954 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002955 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2956 << ValType << Ptr->getSourceRange();
2957 return ExprError();
2958 }
2959
David Majnemerc6eb6502015-06-03 00:26:35 +00002960 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2961 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00002962 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00002963 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00002964 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002965 QualType ResultType = ValType;
Eric Fiselier8d662442016-03-30 23:39:56 +00002966 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002967 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002968 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002969 ResultType = Context.BoolTy;
2970
Richard Smithfeea8832012-04-12 05:08:17 +00002971 // The type of a parameter passed 'by value'. In the GNU atomics, such
2972 // arguments are actually passed as pointers.
2973 QualType ByValType = ValType; // 'CP'
2974 if (!IsC11 && !IsN)
2975 ByValType = Ptr->getType();
2976
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002977 // The first argument --- the pointer --- has a fixed type; we
2978 // deduce the types of the rest of the arguments accordingly. Walk
2979 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002980 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002981 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002982 if (i < NumVals[Form] + 1) {
2983 switch (i) {
2984 case 1:
2985 // The second argument is the non-atomic operand. For arithmetic, this
2986 // is always passed by value, and for a compare_exchange it is always
2987 // passed by address. For the rest, GNU uses by-address and C11 uses
2988 // by-value.
2989 assert(Form != Load);
2990 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2991 Ty = ValType;
2992 else if (Form == Copy || Form == Xchg)
2993 Ty = ByValType;
2994 else if (Form == Arithmetic)
2995 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002996 else {
2997 Expr *ValArg = TheCall->getArg(i);
Alex Lorenz67522152016-11-23 16:57:03 +00002998 // Treat this argument as _Nonnull as we want to show a warning if
2999 // NULL is passed into it.
3000 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003001 unsigned AS = 0;
3002 // Keep address space of non-atomic pointer type.
3003 if (const PointerType *PtrTy =
3004 ValArg->getType()->getAs<PointerType>()) {
3005 AS = PtrTy->getPointeeType().getAddressSpace();
3006 }
3007 Ty = Context.getPointerType(
3008 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3009 }
Richard Smithfeea8832012-04-12 05:08:17 +00003010 break;
3011 case 2:
3012 // The third argument to compare_exchange / GNU exchange is a
3013 // (pointer to a) desired value.
3014 Ty = ByValType;
3015 break;
3016 case 3:
3017 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3018 Ty = Context.BoolTy;
3019 break;
3020 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003021 } else {
3022 // The order(s) are always converted to int.
3023 Ty = Context.IntTy;
3024 }
Richard Smithfeea8832012-04-12 05:08:17 +00003025
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003026 InitializedEntity Entity =
3027 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00003028 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003029 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3030 if (Arg.isInvalid())
3031 return true;
3032 TheCall->setArg(i, Arg.get());
3033 }
3034
Richard Smithfeea8832012-04-12 05:08:17 +00003035 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003036 SmallVector<Expr*, 5> SubExprs;
3037 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00003038 switch (Form) {
3039 case Init:
3040 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00003041 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003042 break;
3043 case Load:
3044 SubExprs.push_back(TheCall->getArg(1)); // Order
3045 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00003046 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00003047 case Copy:
3048 case Arithmetic:
3049 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003050 SubExprs.push_back(TheCall->getArg(2)); // Order
3051 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003052 break;
3053 case GNUXchg:
3054 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3055 SubExprs.push_back(TheCall->getArg(3)); // Order
3056 SubExprs.push_back(TheCall->getArg(1)); // Val1
3057 SubExprs.push_back(TheCall->getArg(2)); // Val2
3058 break;
3059 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003060 SubExprs.push_back(TheCall->getArg(3)); // Order
3061 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003062 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00003063 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00003064 break;
3065 case GNUCmpXchg:
3066 SubExprs.push_back(TheCall->getArg(4)); // Order
3067 SubExprs.push_back(TheCall->getArg(1)); // Val1
3068 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3069 SubExprs.push_back(TheCall->getArg(2)); // Val2
3070 SubExprs.push_back(TheCall->getArg(3)); // Weak
3071 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003072 }
Tim Northovere94a34c2014-03-11 10:49:14 +00003073
3074 if (SubExprs.size() >= 2 && Form != Init) {
3075 llvm::APSInt Result(32);
3076 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3077 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00003078 Diag(SubExprs[1]->getLocStart(),
3079 diag::warn_atomic_op_has_invalid_memory_order)
3080 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00003081 }
3082
Fariborz Jahanian615de762013-05-28 17:37:39 +00003083 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3084 SubExprs, ResultType, Op,
3085 TheCall->getRParenLoc());
3086
3087 if ((Op == AtomicExpr::AO__c11_atomic_load ||
3088 (Op == AtomicExpr::AO__c11_atomic_store)) &&
3089 Context.AtomicUsesUnsupportedLibcall(AE))
3090 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
3091 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003092
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003093 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003094}
3095
John McCall29ad95b2011-08-27 01:09:30 +00003096/// checkBuiltinArgument - Given a call to a builtin function, perform
3097/// normal type-checking on the given argument, updating the call in
3098/// place. This is useful when a builtin function requires custom
3099/// type-checking for some of its arguments but not necessarily all of
3100/// them.
3101///
3102/// Returns true on error.
3103static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3104 FunctionDecl *Fn = E->getDirectCallee();
3105 assert(Fn && "builtin call without direct callee!");
3106
3107 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3108 InitializedEntity Entity =
3109 InitializedEntity::InitializeParameter(S.Context, Param);
3110
3111 ExprResult Arg = E->getArg(0);
3112 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3113 if (Arg.isInvalid())
3114 return true;
3115
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003116 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003117 return false;
3118}
3119
Chris Lattnerdc046542009-05-08 06:58:22 +00003120/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3121/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3122/// type of its first argument. The main ActOnCallExpr routines have already
3123/// promoted the types of arguments because all of these calls are prototyped as
3124/// void(...).
3125///
3126/// This function goes through and does final semantic checking for these
3127/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003128ExprResult
3129Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003130 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003131 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3132 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3133
3134 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003135 if (TheCall->getNumArgs() < 1) {
3136 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3137 << 0 << 1 << TheCall->getNumArgs()
3138 << TheCall->getCallee()->getSourceRange();
3139 return ExprError();
3140 }
Mike Stump11289f42009-09-09 15:08:12 +00003141
Chris Lattnerdc046542009-05-08 06:58:22 +00003142 // Inspect the first argument of the atomic builtin. This should always be
3143 // a pointer type, whose element is an integral scalar or pointer type.
3144 // Because it is a pointer type, we don't have to worry about any implicit
3145 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003146 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003147 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003148 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3149 if (FirstArgResult.isInvalid())
3150 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003151 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003152 TheCall->setArg(0, FirstArg);
3153
John McCall31168b02011-06-15 23:02:42 +00003154 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3155 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003156 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3157 << FirstArg->getType() << FirstArg->getSourceRange();
3158 return ExprError();
3159 }
Mike Stump11289f42009-09-09 15:08:12 +00003160
John McCall31168b02011-06-15 23:02:42 +00003161 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003162 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003163 !ValType->isBlockPointerType()) {
3164 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3165 << FirstArg->getType() << FirstArg->getSourceRange();
3166 return ExprError();
3167 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003168
John McCall31168b02011-06-15 23:02:42 +00003169 switch (ValType.getObjCLifetime()) {
3170 case Qualifiers::OCL_None:
3171 case Qualifiers::OCL_ExplicitNone:
3172 // okay
3173 break;
3174
3175 case Qualifiers::OCL_Weak:
3176 case Qualifiers::OCL_Strong:
3177 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003178 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003179 << ValType << FirstArg->getSourceRange();
3180 return ExprError();
3181 }
3182
John McCallb50451a2011-10-05 07:41:44 +00003183 // Strip any qualifiers off ValType.
3184 ValType = ValType.getUnqualifiedType();
3185
Chandler Carruth3973af72010-07-18 20:54:12 +00003186 // The majority of builtins return a value, but a few have special return
3187 // types, so allow them to override appropriately below.
3188 QualType ResultType = ValType;
3189
Chris Lattnerdc046542009-05-08 06:58:22 +00003190 // We need to figure out which concrete builtin this maps onto. For example,
3191 // __sync_fetch_and_add with a 2 byte object turns into
3192 // __sync_fetch_and_add_2.
3193#define BUILTIN_ROW(x) \
3194 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3195 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003196
Chris Lattnerdc046542009-05-08 06:58:22 +00003197 static const unsigned BuiltinIndices[][5] = {
3198 BUILTIN_ROW(__sync_fetch_and_add),
3199 BUILTIN_ROW(__sync_fetch_and_sub),
3200 BUILTIN_ROW(__sync_fetch_and_or),
3201 BUILTIN_ROW(__sync_fetch_and_and),
3202 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003203 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003204
Chris Lattnerdc046542009-05-08 06:58:22 +00003205 BUILTIN_ROW(__sync_add_and_fetch),
3206 BUILTIN_ROW(__sync_sub_and_fetch),
3207 BUILTIN_ROW(__sync_and_and_fetch),
3208 BUILTIN_ROW(__sync_or_and_fetch),
3209 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003210 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003211
Chris Lattnerdc046542009-05-08 06:58:22 +00003212 BUILTIN_ROW(__sync_val_compare_and_swap),
3213 BUILTIN_ROW(__sync_bool_compare_and_swap),
3214 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003215 BUILTIN_ROW(__sync_lock_release),
3216 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003217 };
Mike Stump11289f42009-09-09 15:08:12 +00003218#undef BUILTIN_ROW
3219
Chris Lattnerdc046542009-05-08 06:58:22 +00003220 // Determine the index of the size.
3221 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003222 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003223 case 1: SizeIndex = 0; break;
3224 case 2: SizeIndex = 1; break;
3225 case 4: SizeIndex = 2; break;
3226 case 8: SizeIndex = 3; break;
3227 case 16: SizeIndex = 4; break;
3228 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003229 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3230 << FirstArg->getType() << FirstArg->getSourceRange();
3231 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003232 }
Mike Stump11289f42009-09-09 15:08:12 +00003233
Chris Lattnerdc046542009-05-08 06:58:22 +00003234 // Each of these builtins has one pointer argument, followed by some number of
3235 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3236 // that we ignore. Find out which row of BuiltinIndices to read from as well
3237 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003238 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003239 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003240 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003241 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003242 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003243 case Builtin::BI__sync_fetch_and_add:
3244 case Builtin::BI__sync_fetch_and_add_1:
3245 case Builtin::BI__sync_fetch_and_add_2:
3246 case Builtin::BI__sync_fetch_and_add_4:
3247 case Builtin::BI__sync_fetch_and_add_8:
3248 case Builtin::BI__sync_fetch_and_add_16:
3249 BuiltinIndex = 0;
3250 break;
3251
3252 case Builtin::BI__sync_fetch_and_sub:
3253 case Builtin::BI__sync_fetch_and_sub_1:
3254 case Builtin::BI__sync_fetch_and_sub_2:
3255 case Builtin::BI__sync_fetch_and_sub_4:
3256 case Builtin::BI__sync_fetch_and_sub_8:
3257 case Builtin::BI__sync_fetch_and_sub_16:
3258 BuiltinIndex = 1;
3259 break;
3260
3261 case Builtin::BI__sync_fetch_and_or:
3262 case Builtin::BI__sync_fetch_and_or_1:
3263 case Builtin::BI__sync_fetch_and_or_2:
3264 case Builtin::BI__sync_fetch_and_or_4:
3265 case Builtin::BI__sync_fetch_and_or_8:
3266 case Builtin::BI__sync_fetch_and_or_16:
3267 BuiltinIndex = 2;
3268 break;
3269
3270 case Builtin::BI__sync_fetch_and_and:
3271 case Builtin::BI__sync_fetch_and_and_1:
3272 case Builtin::BI__sync_fetch_and_and_2:
3273 case Builtin::BI__sync_fetch_and_and_4:
3274 case Builtin::BI__sync_fetch_and_and_8:
3275 case Builtin::BI__sync_fetch_and_and_16:
3276 BuiltinIndex = 3;
3277 break;
Mike Stump11289f42009-09-09 15:08:12 +00003278
Douglas Gregor73722482011-11-28 16:30:08 +00003279 case Builtin::BI__sync_fetch_and_xor:
3280 case Builtin::BI__sync_fetch_and_xor_1:
3281 case Builtin::BI__sync_fetch_and_xor_2:
3282 case Builtin::BI__sync_fetch_and_xor_4:
3283 case Builtin::BI__sync_fetch_and_xor_8:
3284 case Builtin::BI__sync_fetch_and_xor_16:
3285 BuiltinIndex = 4;
3286 break;
3287
Hal Finkeld2208b52014-10-02 20:53:50 +00003288 case Builtin::BI__sync_fetch_and_nand:
3289 case Builtin::BI__sync_fetch_and_nand_1:
3290 case Builtin::BI__sync_fetch_and_nand_2:
3291 case Builtin::BI__sync_fetch_and_nand_4:
3292 case Builtin::BI__sync_fetch_and_nand_8:
3293 case Builtin::BI__sync_fetch_and_nand_16:
3294 BuiltinIndex = 5;
3295 WarnAboutSemanticsChange = true;
3296 break;
3297
Douglas Gregor73722482011-11-28 16:30:08 +00003298 case Builtin::BI__sync_add_and_fetch:
3299 case Builtin::BI__sync_add_and_fetch_1:
3300 case Builtin::BI__sync_add_and_fetch_2:
3301 case Builtin::BI__sync_add_and_fetch_4:
3302 case Builtin::BI__sync_add_and_fetch_8:
3303 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003304 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003305 break;
3306
3307 case Builtin::BI__sync_sub_and_fetch:
3308 case Builtin::BI__sync_sub_and_fetch_1:
3309 case Builtin::BI__sync_sub_and_fetch_2:
3310 case Builtin::BI__sync_sub_and_fetch_4:
3311 case Builtin::BI__sync_sub_and_fetch_8:
3312 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003313 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003314 break;
3315
3316 case Builtin::BI__sync_and_and_fetch:
3317 case Builtin::BI__sync_and_and_fetch_1:
3318 case Builtin::BI__sync_and_and_fetch_2:
3319 case Builtin::BI__sync_and_and_fetch_4:
3320 case Builtin::BI__sync_and_and_fetch_8:
3321 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003322 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003323 break;
3324
3325 case Builtin::BI__sync_or_and_fetch:
3326 case Builtin::BI__sync_or_and_fetch_1:
3327 case Builtin::BI__sync_or_and_fetch_2:
3328 case Builtin::BI__sync_or_and_fetch_4:
3329 case Builtin::BI__sync_or_and_fetch_8:
3330 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003331 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003332 break;
3333
3334 case Builtin::BI__sync_xor_and_fetch:
3335 case Builtin::BI__sync_xor_and_fetch_1:
3336 case Builtin::BI__sync_xor_and_fetch_2:
3337 case Builtin::BI__sync_xor_and_fetch_4:
3338 case Builtin::BI__sync_xor_and_fetch_8:
3339 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003340 BuiltinIndex = 10;
3341 break;
3342
3343 case Builtin::BI__sync_nand_and_fetch:
3344 case Builtin::BI__sync_nand_and_fetch_1:
3345 case Builtin::BI__sync_nand_and_fetch_2:
3346 case Builtin::BI__sync_nand_and_fetch_4:
3347 case Builtin::BI__sync_nand_and_fetch_8:
3348 case Builtin::BI__sync_nand_and_fetch_16:
3349 BuiltinIndex = 11;
3350 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003351 break;
Mike Stump11289f42009-09-09 15:08:12 +00003352
Chris Lattnerdc046542009-05-08 06:58:22 +00003353 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003354 case Builtin::BI__sync_val_compare_and_swap_1:
3355 case Builtin::BI__sync_val_compare_and_swap_2:
3356 case Builtin::BI__sync_val_compare_and_swap_4:
3357 case Builtin::BI__sync_val_compare_and_swap_8:
3358 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003359 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003360 NumFixed = 2;
3361 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003362
Chris Lattnerdc046542009-05-08 06:58:22 +00003363 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003364 case Builtin::BI__sync_bool_compare_and_swap_1:
3365 case Builtin::BI__sync_bool_compare_and_swap_2:
3366 case Builtin::BI__sync_bool_compare_and_swap_4:
3367 case Builtin::BI__sync_bool_compare_and_swap_8:
3368 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003369 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003370 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003371 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003372 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003373
3374 case Builtin::BI__sync_lock_test_and_set:
3375 case Builtin::BI__sync_lock_test_and_set_1:
3376 case Builtin::BI__sync_lock_test_and_set_2:
3377 case Builtin::BI__sync_lock_test_and_set_4:
3378 case Builtin::BI__sync_lock_test_and_set_8:
3379 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003380 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003381 break;
3382
Chris Lattnerdc046542009-05-08 06:58:22 +00003383 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003384 case Builtin::BI__sync_lock_release_1:
3385 case Builtin::BI__sync_lock_release_2:
3386 case Builtin::BI__sync_lock_release_4:
3387 case Builtin::BI__sync_lock_release_8:
3388 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003389 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003390 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003391 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003392 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003393
3394 case Builtin::BI__sync_swap:
3395 case Builtin::BI__sync_swap_1:
3396 case Builtin::BI__sync_swap_2:
3397 case Builtin::BI__sync_swap_4:
3398 case Builtin::BI__sync_swap_8:
3399 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003400 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003401 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003402 }
Mike Stump11289f42009-09-09 15:08:12 +00003403
Chris Lattnerdc046542009-05-08 06:58:22 +00003404 // Now that we know how many fixed arguments we expect, first check that we
3405 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003406 if (TheCall->getNumArgs() < 1+NumFixed) {
3407 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3408 << 0 << 1+NumFixed << TheCall->getNumArgs()
3409 << TheCall->getCallee()->getSourceRange();
3410 return ExprError();
3411 }
Mike Stump11289f42009-09-09 15:08:12 +00003412
Hal Finkeld2208b52014-10-02 20:53:50 +00003413 if (WarnAboutSemanticsChange) {
3414 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3415 << TheCall->getCallee()->getSourceRange();
3416 }
3417
Chris Lattner5b9241b2009-05-08 15:36:58 +00003418 // Get the decl for the concrete builtin from this, we can tell what the
3419 // concrete integer type we should convert to is.
3420 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003421 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003422 FunctionDecl *NewBuiltinDecl;
3423 if (NewBuiltinID == BuiltinID)
3424 NewBuiltinDecl = FDecl;
3425 else {
3426 // Perform builtin lookup to avoid redeclaring it.
3427 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3428 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3429 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3430 assert(Res.getFoundDecl());
3431 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003432 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003433 return ExprError();
3434 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003435
John McCallcf142162010-08-07 06:22:56 +00003436 // The first argument --- the pointer --- has a fixed type; we
3437 // deduce the types of the rest of the arguments accordingly. Walk
3438 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003439 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003440 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003441
Chris Lattnerdc046542009-05-08 06:58:22 +00003442 // GCC does an implicit conversion to the pointer or integer ValType. This
3443 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003444 // Initialize the argument.
3445 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3446 ValType, /*consume*/ false);
3447 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003448 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003449 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003450
Chris Lattnerdc046542009-05-08 06:58:22 +00003451 // Okay, we have something that *can* be converted to the right type. Check
3452 // to see if there is a potentially weird extension going on here. This can
3453 // happen when you do an atomic operation on something like an char* and
3454 // pass in 42. The 42 gets converted to char. This is even more strange
3455 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003456 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003457 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003458 }
Mike Stump11289f42009-09-09 15:08:12 +00003459
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003460 ASTContext& Context = this->getASTContext();
3461
3462 // Create a new DeclRefExpr to refer to the new decl.
3463 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3464 Context,
3465 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003466 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003467 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003468 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003469 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003470 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003471 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003472
Chris Lattnerdc046542009-05-08 06:58:22 +00003473 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003474 // FIXME: This loses syntactic information.
3475 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3476 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3477 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003478 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003479
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003480 // Change the result type of the call to match the original value type. This
3481 // is arbitrary, but the codegen for these builtins ins design to handle it
3482 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003483 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003484
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003485 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003486}
3487
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003488/// SemaBuiltinNontemporalOverloaded - We have a call to
3489/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3490/// overloaded function based on the pointer type of its last argument.
3491///
3492/// This function goes through and does final semantic checking for these
3493/// builtins.
3494ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3495 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3496 DeclRefExpr *DRE =
3497 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3498 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3499 unsigned BuiltinID = FDecl->getBuiltinID();
3500 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3501 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3502 "Unexpected nontemporal load/store builtin!");
3503 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3504 unsigned numArgs = isStore ? 2 : 1;
3505
3506 // Ensure that we have the proper number of arguments.
3507 if (checkArgCount(*this, TheCall, numArgs))
3508 return ExprError();
3509
3510 // Inspect the last argument of the nontemporal builtin. This should always
3511 // be a pointer type, from which we imply the type of the memory access.
3512 // Because it is a pointer type, we don't have to worry about any implicit
3513 // casts here.
3514 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3515 ExprResult PointerArgResult =
3516 DefaultFunctionArrayLvalueConversion(PointerArg);
3517
3518 if (PointerArgResult.isInvalid())
3519 return ExprError();
3520 PointerArg = PointerArgResult.get();
3521 TheCall->setArg(numArgs - 1, PointerArg);
3522
3523 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3524 if (!pointerType) {
3525 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3526 << PointerArg->getType() << PointerArg->getSourceRange();
3527 return ExprError();
3528 }
3529
3530 QualType ValType = pointerType->getPointeeType();
3531
3532 // Strip any qualifiers off ValType.
3533 ValType = ValType.getUnqualifiedType();
3534 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3535 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3536 !ValType->isVectorType()) {
3537 Diag(DRE->getLocStart(),
3538 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3539 << PointerArg->getType() << PointerArg->getSourceRange();
3540 return ExprError();
3541 }
3542
3543 if (!isStore) {
3544 TheCall->setType(ValType);
3545 return TheCallResult;
3546 }
3547
3548 ExprResult ValArg = TheCall->getArg(0);
3549 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3550 Context, ValType, /*consume*/ false);
3551 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3552 if (ValArg.isInvalid())
3553 return ExprError();
3554
3555 TheCall->setArg(0, ValArg.get());
3556 TheCall->setType(Context.VoidTy);
3557 return TheCallResult;
3558}
3559
Chris Lattner6436fb62009-02-18 06:01:06 +00003560/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003561/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003562/// Note: It might also make sense to do the UTF-16 conversion here (would
3563/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003564bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003565 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003566 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3567
Douglas Gregorfb65e592011-07-27 05:40:30 +00003568 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003569 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3570 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003571 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003572 }
Mike Stump11289f42009-09-09 15:08:12 +00003573
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003574 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003575 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003576 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00003577 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3578 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3579 llvm::UTF16 *ToPtr = &ToBuf[0];
3580
3581 llvm::ConversionResult Result =
3582 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3583 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003584 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00003585 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003586 Diag(Arg->getLocStart(),
3587 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3588 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003589 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003590}
3591
Mehdi Amini06d367c2016-10-24 20:39:34 +00003592/// CheckObjCString - Checks that the format string argument to the os_log()
3593/// and os_trace() functions is correct, and converts it to const char *.
3594ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3595 Arg = Arg->IgnoreParenCasts();
3596 auto *Literal = dyn_cast<StringLiteral>(Arg);
3597 if (!Literal) {
3598 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3599 Literal = ObjcLiteral->getString();
3600 }
3601 }
3602
3603 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3604 return ExprError(
3605 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3606 << Arg->getSourceRange());
3607 }
3608
3609 ExprResult Result(Literal);
3610 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3611 InitializedEntity Entity =
3612 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3613 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3614 return Result;
3615}
3616
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003617/// Check that the user is calling the appropriate va_start builtin for the
3618/// target and calling convention.
3619static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3620 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3621 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
3622 bool IsWindows = TT.isOSWindows();
3623 bool IsMSVAStart = BuiltinID == X86::BI__builtin_ms_va_start;
3624 if (IsX64) {
3625 clang::CallingConv CC = CC_C;
3626 if (const FunctionDecl *FD = S.getCurFunctionDecl())
3627 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3628 if (IsMSVAStart) {
3629 // Don't allow this in System V ABI functions.
3630 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_X86_64Win64))
3631 return S.Diag(Fn->getLocStart(),
3632 diag::err_ms_va_start_used_in_sysv_function);
3633 } else {
3634 // On x86-64 Unix, don't allow this in Win64 ABI functions.
3635 // On x64 Windows, don't allow this in System V ABI functions.
3636 // (Yes, that means there's no corresponding way to support variadic
3637 // System V ABI functions on Windows.)
3638 if ((IsWindows && CC == CC_X86_64SysV) ||
3639 (!IsWindows && CC == CC_X86_64Win64))
3640 return S.Diag(Fn->getLocStart(),
3641 diag::err_va_start_used_in_wrong_abi_function)
3642 << !IsWindows;
3643 }
3644 return false;
3645 }
3646
3647 if (IsMSVAStart)
3648 return S.Diag(Fn->getLocStart(), diag::err_x86_builtin_64_only);
3649 return false;
3650}
3651
3652static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3653 ParmVarDecl **LastParam = nullptr) {
3654 // Determine whether the current function, block, or obj-c method is variadic
3655 // and get its parameter list.
3656 bool IsVariadic = false;
3657 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00003658 DeclContext *Caller = S.CurContext;
3659 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3660 IsVariadic = Block->isVariadic();
3661 Params = Block->parameters();
3662 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003663 IsVariadic = FD->isVariadic();
3664 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003665 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003666 IsVariadic = MD->isVariadic();
3667 // FIXME: This isn't correct for methods (results in bogus warning).
3668 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003669 } else if (isa<CapturedDecl>(Caller)) {
3670 // We don't support va_start in a CapturedDecl.
3671 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3672 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003673 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003674 // This must be some other declcontext that parses exprs.
3675 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3676 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003677 }
3678
3679 if (!IsVariadic) {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003680 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003681 return true;
3682 }
3683
3684 if (LastParam)
3685 *LastParam = Params.empty() ? nullptr : Params.back();
3686
3687 return false;
3688}
3689
Charles Davisc7d5c942015-09-17 20:55:33 +00003690/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3691/// for validity. Emit an error and return true on failure; return false
3692/// on success.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003693bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003694 Expr *Fn = TheCall->getCallee();
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003695
3696 if (checkVAStartABI(*this, BuiltinID, Fn))
3697 return true;
3698
Chris Lattner08464942007-12-28 05:29:59 +00003699 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003700 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003701 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003702 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3703 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003704 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003705 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003706 return true;
3707 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003708
3709 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003710 return Diag(TheCall->getLocEnd(),
3711 diag::err_typecheck_call_too_few_args_at_least)
3712 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003713 }
3714
John McCall29ad95b2011-08-27 01:09:30 +00003715 // Type-check the first argument normally.
3716 if (checkBuiltinArgument(*this, TheCall, 0))
3717 return true;
3718
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003719 // Check that the current function is variadic, and get its last parameter.
3720 ParmVarDecl *LastParam;
3721 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
Chris Lattner43be2e62007-12-19 23:59:04 +00003722 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003723
Chris Lattner43be2e62007-12-19 23:59:04 +00003724 // Verify that the second argument to the builtin is the last argument of the
3725 // current function or method.
3726 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003727 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003728
Nico Weber9eea7642013-05-24 23:31:57 +00003729 // These are valid if SecondArgIsLastNamedArgument is false after the next
3730 // block.
3731 QualType Type;
3732 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003733 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003734
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003735 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3736 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003737 SecondArgIsLastNamedArgument = PV == LastParam;
Nico Weber9eea7642013-05-24 23:31:57 +00003738
3739 Type = PV->getType();
3740 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003741 IsCRegister =
3742 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003743 }
3744 }
Mike Stump11289f42009-09-09 15:08:12 +00003745
Chris Lattner43be2e62007-12-19 23:59:04 +00003746 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003747 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003748 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003749 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00003750 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3751 // Promotable integers are UB, but enumerations need a bit of
3752 // extra checking to see what their promotable type actually is.
3753 if (!Type->isPromotableIntegerType())
3754 return false;
3755 if (!Type->isEnumeralType())
3756 return true;
3757 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3758 return !(ED &&
3759 Context.typesAreCompatible(ED->getPromotionType(), Type));
3760 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00003761 unsigned Reason = 0;
3762 if (Type->isReferenceType()) Reason = 1;
3763 else if (IsCRegister) Reason = 2;
3764 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003765 Diag(ParamLoc, diag::note_parameter_type) << Type;
3766 }
3767
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003768 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003769 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003770}
Chris Lattner43be2e62007-12-19 23:59:04 +00003771
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003772bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3773 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3774 // const char *named_addr);
3775
3776 Expr *Func = Call->getCallee();
3777
3778 if (Call->getNumArgs() < 3)
3779 return Diag(Call->getLocEnd(),
3780 diag::err_typecheck_call_too_few_args_at_least)
3781 << 0 /*function call*/ << 3 << Call->getNumArgs();
3782
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003783 // Type-check the first argument normally.
3784 if (checkBuiltinArgument(*this, Call, 0))
3785 return true;
3786
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003787 // Check that the current function is variadic.
3788 if (checkVAStartIsInVariadicFunction(*this, Func))
3789 return true;
3790
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003791 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003792 unsigned ArgNo;
3793 QualType Type;
3794 } ArgumentTypes[] = {
3795 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3796 { 2, Context.getSizeType() },
3797 };
3798
3799 for (const auto &AT : ArgumentTypes) {
3800 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3801 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3802 continue;
3803 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3804 << Arg->getType() << AT.Type << 1 /* different class */
3805 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3806 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3807 }
3808
3809 return false;
3810}
3811
Chris Lattner2da14fb2007-12-20 00:26:33 +00003812/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3813/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003814bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3815 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003816 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003817 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003818 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003819 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003820 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003821 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003822 << SourceRange(TheCall->getArg(2)->getLocStart(),
3823 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003824
John Wiegley01296292011-04-08 18:41:53 +00003825 ExprResult OrigArg0 = TheCall->getArg(0);
3826 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003827
Chris Lattner2da14fb2007-12-20 00:26:33 +00003828 // Do standard promotions between the two arguments, returning their common
3829 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003830 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003831 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3832 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003833
3834 // Make sure any conversions are pushed back into the call; this is
3835 // type safe since unordered compare builtins are declared as "_Bool
3836 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003837 TheCall->setArg(0, OrigArg0.get());
3838 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003839
John Wiegley01296292011-04-08 18:41:53 +00003840 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003841 return false;
3842
Chris Lattner2da14fb2007-12-20 00:26:33 +00003843 // If the common type isn't a real floating type, then the arguments were
3844 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003845 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00003846 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003847 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00003848 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3849 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003850
Chris Lattner2da14fb2007-12-20 00:26:33 +00003851 return false;
3852}
3853
Benjamin Kramer634fc102010-02-15 22:42:31 +00003854/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3855/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00003856/// to check everything. We expect the last argument to be a floating point
3857/// value.
3858bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3859 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00003860 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003861 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00003862 if (TheCall->getNumArgs() > NumArgs)
3863 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003864 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003865 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00003866 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003867 (*(TheCall->arg_end()-1))->getLocEnd());
3868
Benjamin Kramer64aae502010-02-16 10:07:31 +00003869 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00003870
Eli Friedman7e4faac2009-08-31 20:06:00 +00003871 if (OrigArg->isTypeDependent())
3872 return false;
3873
Chris Lattner68784ef2010-05-06 05:50:07 +00003874 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00003875 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00003876 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003877 diag::err_typecheck_call_invalid_unary_fp)
3878 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003879
Neil Hickey88c0fac2016-12-13 16:22:50 +00003880 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00003881 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00003882 // Only remove standard FloatCasts, leaving other casts inplace
3883 if (Cast->getCastKind() == CK_FloatingCast) {
3884 Expr *CastArg = Cast->getSubExpr();
3885 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3886 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
3887 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
3888 "promotion from float to either float or double is the only expected cast here");
3889 Cast->setSubExpr(nullptr);
3890 TheCall->setArg(NumArgs-1, CastArg);
3891 }
Chris Lattner68784ef2010-05-06 05:50:07 +00003892 }
3893 }
3894
Eli Friedman7e4faac2009-08-31 20:06:00 +00003895 return false;
3896}
3897
Tony Jiangbbc48e92017-05-24 15:13:32 +00003898// Customized Sema Checking for VSX builtins that have the following signature:
3899// vector [...] builtinName(vector [...], vector [...], const int);
3900// Which takes the same type of vectors (any legal vector type) for the first
3901// two arguments and takes compile time constant for the third argument.
3902// Example builtins are :
3903// vector double vec_xxpermdi(vector double, vector double, int);
3904// vector short vec_xxsldwi(vector short, vector short, int);
3905bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
3906 unsigned ExpectedNumArgs = 3;
3907 if (TheCall->getNumArgs() < ExpectedNumArgs)
3908 return Diag(TheCall->getLocEnd(),
3909 diag::err_typecheck_call_too_few_args_at_least)
3910 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
3911 << TheCall->getSourceRange();
3912
3913 if (TheCall->getNumArgs() > ExpectedNumArgs)
3914 return Diag(TheCall->getLocEnd(),
3915 diag::err_typecheck_call_too_many_args_at_most)
3916 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
3917 << TheCall->getSourceRange();
3918
3919 // Check the third argument is a compile time constant
3920 llvm::APSInt Value;
3921 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
3922 return Diag(TheCall->getLocStart(),
3923 diag::err_vsx_builtin_nonconstant_argument)
3924 << 3 /* argument index */ << TheCall->getDirectCallee()
3925 << SourceRange(TheCall->getArg(2)->getLocStart(),
3926 TheCall->getArg(2)->getLocEnd());
3927
3928 QualType Arg1Ty = TheCall->getArg(0)->getType();
3929 QualType Arg2Ty = TheCall->getArg(1)->getType();
3930
3931 // Check the type of argument 1 and argument 2 are vectors.
3932 SourceLocation BuiltinLoc = TheCall->getLocStart();
3933 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
3934 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
3935 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
3936 << TheCall->getDirectCallee()
3937 << SourceRange(TheCall->getArg(0)->getLocStart(),
3938 TheCall->getArg(1)->getLocEnd());
3939 }
3940
3941 // Check the first two arguments are the same type.
3942 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
3943 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
3944 << TheCall->getDirectCallee()
3945 << SourceRange(TheCall->getArg(0)->getLocStart(),
3946 TheCall->getArg(1)->getLocEnd());
3947 }
3948
3949 // When default clang type checking is turned off and the customized type
3950 // checking is used, the returning type of the function must be explicitly
3951 // set. Otherwise it is _Bool by default.
3952 TheCall->setType(Arg1Ty);
3953
3954 return false;
3955}
3956
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003957/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3958// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00003959ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00003960 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003961 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00003962 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00003963 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3964 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003965
Nate Begemana0110022010-06-08 00:16:34 +00003966 // Determine which of the following types of shufflevector we're checking:
3967 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00003968 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00003969 QualType resType = TheCall->getArg(0)->getType();
3970 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00003971
Douglas Gregorc25f7662009-05-19 22:10:17 +00003972 if (!TheCall->getArg(0)->isTypeDependent() &&
3973 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00003974 QualType LHSType = TheCall->getArg(0)->getType();
3975 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00003976
Craig Topperbaca3892013-07-29 06:47:04 +00003977 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3978 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00003979 diag::err_vec_builtin_non_vector)
3980 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00003981 << SourceRange(TheCall->getArg(0)->getLocStart(),
3982 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003983
Nate Begemana0110022010-06-08 00:16:34 +00003984 numElements = LHSType->getAs<VectorType>()->getNumElements();
3985 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00003986
Nate Begemana0110022010-06-08 00:16:34 +00003987 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3988 // with mask. If so, verify that RHS is an integer vector type with the
3989 // same number of elts as lhs.
3990 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00003991 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00003992 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00003993 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00003994 diag::err_vec_builtin_incompatible_vector)
3995 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00003996 << SourceRange(TheCall->getArg(1)->getLocStart(),
3997 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003998 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00003999 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004000 diag::err_vec_builtin_incompatible_vector)
4001 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004002 << SourceRange(TheCall->getArg(0)->getLocStart(),
4003 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00004004 } else if (numElements != numResElements) {
4005 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00004006 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00004007 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004008 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004009 }
4010
4011 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00004012 if (TheCall->getArg(i)->isTypeDependent() ||
4013 TheCall->getArg(i)->isValueDependent())
4014 continue;
4015
Nate Begemana0110022010-06-08 00:16:34 +00004016 llvm::APSInt Result(32);
4017 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4018 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004019 diag::err_shufflevector_nonconstant_argument)
4020 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004021
Craig Topper50ad5b72013-08-03 17:40:38 +00004022 // Allow -1 which will be translated to undef in the IR.
4023 if (Result.isSigned() && Result.isAllOnesValue())
4024 continue;
4025
Chris Lattner7ab824e2008-08-10 02:05:13 +00004026 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004027 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004028 diag::err_shufflevector_argument_too_large)
4029 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004030 }
4031
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004032 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004033
Chris Lattner7ab824e2008-08-10 02:05:13 +00004034 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004035 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00004036 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004037 }
4038
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004039 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4040 TheCall->getCallee()->getLocStart(),
4041 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004042}
Chris Lattner43be2e62007-12-19 23:59:04 +00004043
Hal Finkelc4d7c822013-09-18 03:29:45 +00004044/// SemaConvertVectorExpr - Handle __builtin_convertvector
4045ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4046 SourceLocation BuiltinLoc,
4047 SourceLocation RParenLoc) {
4048 ExprValueKind VK = VK_RValue;
4049 ExprObjectKind OK = OK_Ordinary;
4050 QualType DstTy = TInfo->getType();
4051 QualType SrcTy = E->getType();
4052
4053 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4054 return ExprError(Diag(BuiltinLoc,
4055 diag::err_convertvector_non_vector)
4056 << E->getSourceRange());
4057 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4058 return ExprError(Diag(BuiltinLoc,
4059 diag::err_convertvector_non_vector_type));
4060
4061 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4062 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4063 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4064 if (SrcElts != DstElts)
4065 return ExprError(Diag(BuiltinLoc,
4066 diag::err_convertvector_incompatible_vector)
4067 << E->getSourceRange());
4068 }
4069
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004070 return new (Context)
4071 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00004072}
4073
Daniel Dunbarb7257262008-07-21 22:59:13 +00004074/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4075// This is declared to take (const void*, ...) and can take two
4076// optional constant int args.
4077bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00004078 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004079
Chris Lattner3b054132008-11-19 05:08:23 +00004080 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004081 return Diag(TheCall->getLocEnd(),
4082 diag::err_typecheck_call_too_many_args_at_most)
4083 << 0 /*function call*/ << 3 << NumArgs
4084 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004085
4086 // Argument 0 is checked for us and the remaining arguments must be
4087 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00004088 for (unsigned i = 1; i != NumArgs; ++i)
4089 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004090 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004091
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004092 return false;
4093}
4094
Hal Finkelf0417332014-07-17 14:25:55 +00004095/// SemaBuiltinAssume - Handle __assume (MS Extension).
4096// __assume does not evaluate its arguments, and should warn if its argument
4097// has side effects.
4098bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4099 Expr *Arg = TheCall->getArg(0);
4100 if (Arg->isInstantiationDependent()) return false;
4101
4102 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00004103 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00004104 << Arg->getSourceRange()
4105 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4106
4107 return false;
4108}
4109
David Majnemer86b1bfa2016-10-31 18:07:57 +00004110/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00004111/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4112/// than 8.
4113bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4114 // The alignment must be a constant integer.
4115 Expr *Arg = TheCall->getArg(1);
4116
4117 // We can't check the value of a dependent argument.
4118 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00004119 if (const auto *UE =
4120 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4121 if (UE->getKind() == UETT_AlignOf)
4122 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4123 << Arg->getSourceRange();
4124
David Majnemer51169932016-10-31 05:37:48 +00004125 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4126
4127 if (!Result.isPowerOf2())
4128 return Diag(TheCall->getLocStart(),
4129 diag::err_alignment_not_power_of_two)
4130 << Arg->getSourceRange();
4131
4132 if (Result < Context.getCharWidth())
4133 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4134 << (unsigned)Context.getCharWidth()
4135 << Arg->getSourceRange();
4136
4137 if (Result > INT32_MAX)
4138 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4139 << INT32_MAX
4140 << Arg->getSourceRange();
4141 }
4142
4143 return false;
4144}
4145
4146/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00004147/// as (const void*, size_t, ...) and can take one optional constant int arg.
4148bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4149 unsigned NumArgs = TheCall->getNumArgs();
4150
4151 if (NumArgs > 3)
4152 return Diag(TheCall->getLocEnd(),
4153 diag::err_typecheck_call_too_many_args_at_most)
4154 << 0 /*function call*/ << 3 << NumArgs
4155 << TheCall->getSourceRange();
4156
4157 // The alignment must be a constant integer.
4158 Expr *Arg = TheCall->getArg(1);
4159
4160 // We can't check the value of a dependent argument.
4161 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4162 llvm::APSInt Result;
4163 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4164 return true;
4165
4166 if (!Result.isPowerOf2())
4167 return Diag(TheCall->getLocStart(),
4168 diag::err_alignment_not_power_of_two)
4169 << Arg->getSourceRange();
4170 }
4171
4172 if (NumArgs > 2) {
4173 ExprResult Arg(TheCall->getArg(2));
4174 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4175 Context.getSizeType(), false);
4176 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4177 if (Arg.isInvalid()) return true;
4178 TheCall->setArg(2, Arg.get());
4179 }
Hal Finkelf0417332014-07-17 14:25:55 +00004180
4181 return false;
4182}
4183
Mehdi Amini06d367c2016-10-24 20:39:34 +00004184bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4185 unsigned BuiltinID =
4186 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4187 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4188
4189 unsigned NumArgs = TheCall->getNumArgs();
4190 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4191 if (NumArgs < NumRequiredArgs) {
4192 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4193 << 0 /* function call */ << NumRequiredArgs << NumArgs
4194 << TheCall->getSourceRange();
4195 }
4196 if (NumArgs >= NumRequiredArgs + 0x100) {
4197 return Diag(TheCall->getLocEnd(),
4198 diag::err_typecheck_call_too_many_args_at_most)
4199 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4200 << TheCall->getSourceRange();
4201 }
4202 unsigned i = 0;
4203
4204 // For formatting call, check buffer arg.
4205 if (!IsSizeCall) {
4206 ExprResult Arg(TheCall->getArg(i));
4207 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4208 Context, Context.VoidPtrTy, false);
4209 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4210 if (Arg.isInvalid())
4211 return true;
4212 TheCall->setArg(i, Arg.get());
4213 i++;
4214 }
4215
4216 // Check string literal arg.
4217 unsigned FormatIdx = i;
4218 {
4219 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4220 if (Arg.isInvalid())
4221 return true;
4222 TheCall->setArg(i, Arg.get());
4223 i++;
4224 }
4225
4226 // Make sure variadic args are scalar.
4227 unsigned FirstDataArg = i;
4228 while (i < NumArgs) {
4229 ExprResult Arg = DefaultVariadicArgumentPromotion(
4230 TheCall->getArg(i), VariadicFunction, nullptr);
4231 if (Arg.isInvalid())
4232 return true;
4233 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4234 if (ArgSize.getQuantity() >= 0x100) {
4235 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4236 << i << (int)ArgSize.getQuantity() << 0xff
4237 << TheCall->getSourceRange();
4238 }
4239 TheCall->setArg(i, Arg.get());
4240 i++;
4241 }
4242
4243 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4244 // call to avoid duplicate diagnostics.
4245 if (!IsSizeCall) {
4246 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4247 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4248 bool Success = CheckFormatArguments(
4249 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4250 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4251 CheckedVarArgs);
4252 if (!Success)
4253 return true;
4254 }
4255
4256 if (IsSizeCall) {
4257 TheCall->setType(Context.getSizeType());
4258 } else {
4259 TheCall->setType(Context.VoidPtrTy);
4260 }
4261 return false;
4262}
4263
Eric Christopher8d0c6212010-04-17 02:26:23 +00004264/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4265/// TheCall is a constant expression.
4266bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4267 llvm::APSInt &Result) {
4268 Expr *Arg = TheCall->getArg(ArgNum);
4269 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4270 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4271
4272 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4273
4274 if (!Arg->isIntegerConstantExpr(Result, Context))
4275 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004276 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004277
Chris Lattnerd545ad12009-09-23 06:06:36 +00004278 return false;
4279}
4280
Richard Sandiford28940af2014-04-16 08:47:51 +00004281/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4282/// TheCall is a constant expression in the range [Low, High].
4283bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4284 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004285 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004286
4287 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004288 Expr *Arg = TheCall->getArg(ArgNum);
4289 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004290 return false;
4291
Eric Christopher8d0c6212010-04-17 02:26:23 +00004292 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004293 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004294 return true;
4295
Richard Sandiford28940af2014-04-16 08:47:51 +00004296 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004297 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004298 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004299
4300 return false;
4301}
4302
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004303/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4304/// TheCall is a constant expression is a multiple of Num..
4305bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4306 unsigned Num) {
4307 llvm::APSInt Result;
4308
4309 // We can't check the value of a dependent argument.
4310 Expr *Arg = TheCall->getArg(ArgNum);
4311 if (Arg->isTypeDependent() || Arg->isValueDependent())
4312 return false;
4313
4314 // Check constant-ness first.
4315 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4316 return true;
4317
4318 if (Result.getSExtValue() % Num != 0)
4319 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4320 << Num << Arg->getSourceRange();
4321
4322 return false;
4323}
4324
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004325/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4326/// TheCall is an ARM/AArch64 special register string literal.
4327bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4328 int ArgNum, unsigned ExpectedFieldNum,
4329 bool AllowName) {
4330 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4331 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4332 BuiltinID == ARM::BI__builtin_arm_rsr ||
4333 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4334 BuiltinID == ARM::BI__builtin_arm_wsr ||
4335 BuiltinID == ARM::BI__builtin_arm_wsrp;
4336 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4337 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4338 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4339 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4340 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4341 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4342 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4343
4344 // We can't check the value of a dependent argument.
4345 Expr *Arg = TheCall->getArg(ArgNum);
4346 if (Arg->isTypeDependent() || Arg->isValueDependent())
4347 return false;
4348
4349 // Check if the argument is a string literal.
4350 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4351 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4352 << Arg->getSourceRange();
4353
4354 // Check the type of special register given.
4355 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4356 SmallVector<StringRef, 6> Fields;
4357 Reg.split(Fields, ":");
4358
4359 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4360 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4361 << Arg->getSourceRange();
4362
4363 // If the string is the name of a register then we cannot check that it is
4364 // valid here but if the string is of one the forms described in ACLE then we
4365 // can check that the supplied fields are integers and within the valid
4366 // ranges.
4367 if (Fields.size() > 1) {
4368 bool FiveFields = Fields.size() == 5;
4369
4370 bool ValidString = true;
4371 if (IsARMBuiltin) {
4372 ValidString &= Fields[0].startswith_lower("cp") ||
4373 Fields[0].startswith_lower("p");
4374 if (ValidString)
4375 Fields[0] =
4376 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4377
4378 ValidString &= Fields[2].startswith_lower("c");
4379 if (ValidString)
4380 Fields[2] = Fields[2].drop_front(1);
4381
4382 if (FiveFields) {
4383 ValidString &= Fields[3].startswith_lower("c");
4384 if (ValidString)
4385 Fields[3] = Fields[3].drop_front(1);
4386 }
4387 }
4388
4389 SmallVector<int, 5> Ranges;
4390 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00004391 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004392 else
4393 Ranges.append({15, 7, 15});
4394
4395 for (unsigned i=0; i<Fields.size(); ++i) {
4396 int IntField;
4397 ValidString &= !Fields[i].getAsInteger(10, IntField);
4398 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4399 }
4400
4401 if (!ValidString)
4402 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4403 << Arg->getSourceRange();
4404
4405 } else if (IsAArch64Builtin && Fields.size() == 1) {
4406 // If the register name is one of those that appear in the condition below
4407 // and the special register builtin being used is one of the write builtins,
4408 // then we require that the argument provided for writing to the register
4409 // is an integer constant expression. This is because it will be lowered to
4410 // an MSR (immediate) instruction, so we need to know the immediate at
4411 // compile time.
4412 if (TheCall->getNumArgs() != 2)
4413 return false;
4414
4415 std::string RegLower = Reg.lower();
4416 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4417 RegLower != "pan" && RegLower != "uao")
4418 return false;
4419
4420 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4421 }
4422
4423 return false;
4424}
4425
Eli Friedmanc97d0142009-05-03 06:04:26 +00004426/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004427/// This checks that the target supports __builtin_longjmp and
4428/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004429bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004430 if (!Context.getTargetInfo().hasSjLjLowering())
4431 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4432 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4433
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004434 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004435 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004436
Eric Christopher8d0c6212010-04-17 02:26:23 +00004437 // TODO: This is less than ideal. Overload this to take a value.
4438 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4439 return true;
4440
4441 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004442 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4443 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4444
4445 return false;
4446}
4447
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004448/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4449/// This checks that the target supports __builtin_setjmp.
4450bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4451 if (!Context.getTargetInfo().hasSjLjLowering())
4452 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4453 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4454 return false;
4455}
4456
Richard Smithd7293d72013-08-05 18:49:43 +00004457namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004458class UncoveredArgHandler {
4459 enum { Unknown = -1, AllCovered = -2 };
4460 signed FirstUncoveredArg;
4461 SmallVector<const Expr *, 4> DiagnosticExprs;
4462
4463public:
4464 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4465
4466 bool hasUncoveredArg() const {
4467 return (FirstUncoveredArg >= 0);
4468 }
4469
4470 unsigned getUncoveredArg() const {
4471 assert(hasUncoveredArg() && "no uncovered argument");
4472 return FirstUncoveredArg;
4473 }
4474
4475 void setAllCovered() {
4476 // A string has been found with all arguments covered, so clear out
4477 // the diagnostics.
4478 DiagnosticExprs.clear();
4479 FirstUncoveredArg = AllCovered;
4480 }
4481
4482 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4483 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4484
4485 // Don't update if a previous string covers all arguments.
4486 if (FirstUncoveredArg == AllCovered)
4487 return;
4488
4489 // UncoveredArgHandler tracks the highest uncovered argument index
4490 // and with it all the strings that match this index.
4491 if (NewFirstUncoveredArg == FirstUncoveredArg)
4492 DiagnosticExprs.push_back(StrExpr);
4493 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4494 DiagnosticExprs.clear();
4495 DiagnosticExprs.push_back(StrExpr);
4496 FirstUncoveredArg = NewFirstUncoveredArg;
4497 }
4498 }
4499
4500 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4501};
4502
Richard Smithd7293d72013-08-05 18:49:43 +00004503enum StringLiteralCheckType {
4504 SLCT_NotALiteral,
4505 SLCT_UncheckedLiteral,
4506 SLCT_CheckedLiteral
4507};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004508} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00004509
Stephen Hines648c3692016-09-16 01:07:04 +00004510static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4511 BinaryOperatorKind BinOpKind,
4512 bool AddendIsRight) {
4513 unsigned BitWidth = Offset.getBitWidth();
4514 unsigned AddendBitWidth = Addend.getBitWidth();
4515 // There might be negative interim results.
4516 if (Addend.isUnsigned()) {
4517 Addend = Addend.zext(++AddendBitWidth);
4518 Addend.setIsSigned(true);
4519 }
4520 // Adjust the bit width of the APSInts.
4521 if (AddendBitWidth > BitWidth) {
4522 Offset = Offset.sext(AddendBitWidth);
4523 BitWidth = AddendBitWidth;
4524 } else if (BitWidth > AddendBitWidth) {
4525 Addend = Addend.sext(BitWidth);
4526 }
4527
4528 bool Ov = false;
4529 llvm::APSInt ResOffset = Offset;
4530 if (BinOpKind == BO_Add)
4531 ResOffset = Offset.sadd_ov(Addend, Ov);
4532 else {
4533 assert(AddendIsRight && BinOpKind == BO_Sub &&
4534 "operator must be add or sub with addend on the right");
4535 ResOffset = Offset.ssub_ov(Addend, Ov);
4536 }
4537
4538 // We add an offset to a pointer here so we should support an offset as big as
4539 // possible.
4540 if (Ov) {
4541 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00004542 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00004543 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4544 return;
4545 }
4546
4547 Offset = ResOffset;
4548}
4549
4550namespace {
4551// This is a wrapper class around StringLiteral to support offsetted string
4552// literals as format strings. It takes the offset into account when returning
4553// the string and its length or the source locations to display notes correctly.
4554class FormatStringLiteral {
4555 const StringLiteral *FExpr;
4556 int64_t Offset;
4557
4558 public:
4559 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4560 : FExpr(fexpr), Offset(Offset) {}
4561
4562 StringRef getString() const {
4563 return FExpr->getString().drop_front(Offset);
4564 }
4565
4566 unsigned getByteLength() const {
4567 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4568 }
4569 unsigned getLength() const { return FExpr->getLength() - Offset; }
4570 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4571
4572 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4573
4574 QualType getType() const { return FExpr->getType(); }
4575
4576 bool isAscii() const { return FExpr->isAscii(); }
4577 bool isWide() const { return FExpr->isWide(); }
4578 bool isUTF8() const { return FExpr->isUTF8(); }
4579 bool isUTF16() const { return FExpr->isUTF16(); }
4580 bool isUTF32() const { return FExpr->isUTF32(); }
4581 bool isPascal() const { return FExpr->isPascal(); }
4582
4583 SourceLocation getLocationOfByte(
4584 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4585 const TargetInfo &Target, unsigned *StartToken = nullptr,
4586 unsigned *StartTokenByteOffset = nullptr) const {
4587 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4588 StartToken, StartTokenByteOffset);
4589 }
4590
4591 SourceLocation getLocStart() const LLVM_READONLY {
4592 return FExpr->getLocStart().getLocWithOffset(Offset);
4593 }
4594 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4595};
4596} // end anonymous namespace
4597
4598static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004599 const Expr *OrigFormatExpr,
4600 ArrayRef<const Expr *> Args,
4601 bool HasVAListArg, unsigned format_idx,
4602 unsigned firstDataArg,
4603 Sema::FormatStringType Type,
4604 bool inFunctionCall,
4605 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004606 llvm::SmallBitVector &CheckedVarArgs,
4607 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004608
Richard Smith55ce3522012-06-25 20:30:08 +00004609// Determine if an expression is a string literal or constant string.
4610// If this function returns false on the arguments to a function expecting a
4611// format string, we will usually need to emit a warning.
4612// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00004613static StringLiteralCheckType
4614checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4615 bool HasVAListArg, unsigned format_idx,
4616 unsigned firstDataArg, Sema::FormatStringType Type,
4617 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004618 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004619 UncoveredArgHandler &UncoveredArg,
4620 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00004621 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00004622 assert(Offset.isSigned() && "invalid offset");
4623
Douglas Gregorc25f7662009-05-19 22:10:17 +00004624 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00004625 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004626
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004627 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00004628
Richard Smithd7293d72013-08-05 18:49:43 +00004629 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00004630 // Technically -Wformat-nonliteral does not warn about this case.
4631 // The behavior of printf and friends in this case is implementation
4632 // dependent. Ideally if the format string cannot be null then
4633 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00004634 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00004635
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004636 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00004637 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004638 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00004639 // The expression is a literal if both sub-expressions were, and it was
4640 // completely checked only if both sub-expressions were checked.
4641 const AbstractConditionalOperator *C =
4642 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004643
4644 // Determine whether it is necessary to check both sub-expressions, for
4645 // example, because the condition expression is a constant that can be
4646 // evaluated at compile time.
4647 bool CheckLeft = true, CheckRight = true;
4648
4649 bool Cond;
4650 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4651 if (Cond)
4652 CheckRight = false;
4653 else
4654 CheckLeft = false;
4655 }
4656
Stephen Hines648c3692016-09-16 01:07:04 +00004657 // We need to maintain the offsets for the right and the left hand side
4658 // separately to check if every possible indexed expression is a valid
4659 // string literal. They might have different offsets for different string
4660 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004661 StringLiteralCheckType Left;
4662 if (!CheckLeft)
4663 Left = SLCT_UncheckedLiteral;
4664 else {
4665 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4666 HasVAListArg, format_idx, firstDataArg,
4667 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004668 CheckedVarArgs, UncoveredArg, Offset);
4669 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004670 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004671 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004672 }
4673
Richard Smith55ce3522012-06-25 20:30:08 +00004674 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004675 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004676 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004677 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004678 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004679
4680 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004681 }
4682
4683 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00004684 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4685 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004686 }
4687
John McCallc07a0c72011-02-17 10:25:35 +00004688 case Stmt::OpaqueValueExprClass:
4689 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4690 E = src;
4691 goto tryAgain;
4692 }
Richard Smith55ce3522012-06-25 20:30:08 +00004693 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004694
Ted Kremeneka8890832011-02-24 23:03:04 +00004695 case Stmt::PredefinedExprClass:
4696 // While __func__, etc., are technically not string literals, they
4697 // cannot contain format specifiers and thus are not a security
4698 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004699 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004700
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004701 case Stmt::DeclRefExprClass: {
4702 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004703
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004704 // As an exception, do not flag errors for variables binding to
4705 // const string literals.
4706 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4707 bool isConstant = false;
4708 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004709
Richard Smithd7293d72013-08-05 18:49:43 +00004710 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4711 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004712 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004713 isConstant = T.isConstant(S.Context) &&
4714 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004715 } else if (T->isObjCObjectPointerType()) {
4716 // In ObjC, there is usually no "const ObjectPointer" type,
4717 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004718 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004719 }
Mike Stump11289f42009-09-09 15:08:12 +00004720
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004721 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004722 if (const Expr *Init = VD->getAnyInitializer()) {
4723 // Look through initializers like const char c[] = { "foo" }
4724 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4725 if (InitList->isStringLiteralInit())
4726 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4727 }
Richard Smithd7293d72013-08-05 18:49:43 +00004728 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004729 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004730 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004731 /*InFunctionCall*/ false, CheckedVarArgs,
4732 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004733 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004734 }
Mike Stump11289f42009-09-09 15:08:12 +00004735
Anders Carlssonb012ca92009-06-28 19:55:58 +00004736 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4737 // special check to see if the format string is a function parameter
4738 // of the function calling the printf function. If the function
4739 // has an attribute indicating it is a printf-like function, then we
4740 // should suppress warnings concerning non-literals being used in a call
4741 // to a vprintf function. For example:
4742 //
4743 // void
4744 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4745 // va_list ap;
4746 // va_start(ap, fmt);
4747 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4748 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00004749 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004750 if (HasVAListArg) {
4751 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4752 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4753 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004754 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004755 // adjust for implicit parameter
4756 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4757 if (MD->isInstance())
4758 ++PVIndex;
4759 // We also check if the formats are compatible.
4760 // We can't pass a 'scanf' string to a 'printf' function.
4761 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00004762 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00004763 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004764 }
4765 }
4766 }
4767 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004768 }
Mike Stump11289f42009-09-09 15:08:12 +00004769
Richard Smith55ce3522012-06-25 20:30:08 +00004770 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004771 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004772
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004773 case Stmt::CallExprClass:
4774 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004775 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004776 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4777 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4778 unsigned ArgIndex = FA->getFormatIdx();
4779 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4780 if (MD->isInstance())
4781 --ArgIndex;
4782 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00004783
Richard Smithd7293d72013-08-05 18:49:43 +00004784 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004785 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00004786 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004787 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004788 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4789 unsigned BuiltinID = FD->getBuiltinID();
4790 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4791 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4792 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00004793 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004794 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004795 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004796 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004797 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004798 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004799 }
4800 }
Mike Stump11289f42009-09-09 15:08:12 +00004801
Richard Smith55ce3522012-06-25 20:30:08 +00004802 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004803 }
Alex Lorenzd9007142016-10-24 09:42:34 +00004804 case Stmt::ObjCMessageExprClass: {
4805 const auto *ME = cast<ObjCMessageExpr>(E);
4806 if (const auto *ND = ME->getMethodDecl()) {
4807 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4808 unsigned ArgIndex = FA->getFormatIdx();
4809 const Expr *Arg = ME->getArg(ArgIndex - 1);
4810 return checkFormatStringExpr(
4811 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4812 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4813 }
4814 }
4815
4816 return SLCT_NotALiteral;
4817 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004818 case Stmt::ObjCStringLiteralClass:
4819 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00004820 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004821
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004822 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004823 StrE = ObjCFExpr->getString();
4824 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004825 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004826
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004827 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00004828 if (Offset.isNegative() || Offset > StrE->getLength()) {
4829 // TODO: It would be better to have an explicit warning for out of
4830 // bounds literals.
4831 return SLCT_NotALiteral;
4832 }
4833 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4834 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004835 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004836 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00004837 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004838 }
Mike Stump11289f42009-09-09 15:08:12 +00004839
Richard Smith55ce3522012-06-25 20:30:08 +00004840 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004841 }
Stephen Hines648c3692016-09-16 01:07:04 +00004842 case Stmt::BinaryOperatorClass: {
4843 llvm::APSInt LResult;
4844 llvm::APSInt RResult;
4845
4846 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4847
4848 // A string literal + an int offset is still a string literal.
4849 if (BinOp->isAdditiveOp()) {
4850 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4851 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4852
4853 if (LIsInt != RIsInt) {
4854 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4855
4856 if (LIsInt) {
4857 if (BinOpKind == BO_Add) {
4858 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4859 E = BinOp->getRHS();
4860 goto tryAgain;
4861 }
4862 } else {
4863 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4864 E = BinOp->getLHS();
4865 goto tryAgain;
4866 }
4867 }
Stephen Hines648c3692016-09-16 01:07:04 +00004868 }
George Burgess IVd273aab2016-09-22 00:00:26 +00004869
4870 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00004871 }
4872 case Stmt::UnaryOperatorClass: {
4873 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4874 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4875 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4876 llvm::APSInt IndexResult;
4877 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4878 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4879 E = ASE->getBase();
4880 goto tryAgain;
4881 }
4882 }
4883
4884 return SLCT_NotALiteral;
4885 }
Mike Stump11289f42009-09-09 15:08:12 +00004886
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004887 default:
Richard Smith55ce3522012-06-25 20:30:08 +00004888 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004889 }
4890}
4891
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004892Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00004893 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00004894 .Case("scanf", FST_Scanf)
4895 .Cases("printf", "printf0", FST_Printf)
4896 .Cases("NSString", "CFString", FST_NSString)
4897 .Case("strftime", FST_Strftime)
4898 .Case("strfmon", FST_Strfmon)
4899 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4900 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4901 .Case("os_trace", FST_OSLog)
4902 .Case("os_log", FST_OSLog)
4903 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004904}
4905
Jordan Rose3e0ec582012-07-19 18:10:23 +00004906/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00004907/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00004908/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004909bool Sema::CheckFormatArguments(const FormatAttr *Format,
4910 ArrayRef<const Expr *> Args,
4911 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004912 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004913 SourceLocation Loc, SourceRange Range,
4914 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00004915 FormatStringInfo FSI;
4916 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004917 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00004918 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00004919 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00004920 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004921}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00004922
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004923bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004924 bool HasVAListArg, unsigned format_idx,
4925 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004926 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004927 SourceLocation Loc, SourceRange Range,
4928 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004929 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004930 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004931 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00004932 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004933 }
Mike Stump11289f42009-09-09 15:08:12 +00004934
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004935 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004936
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004937 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00004938 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004939 // Dynamically generated format strings are difficult to
4940 // automatically vet at compile time. Requiring that format strings
4941 // are string literals: (1) permits the checking of format strings by
4942 // the compiler and thereby (2) can practically remove the source of
4943 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00004944
Mike Stump11289f42009-09-09 15:08:12 +00004945 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00004946 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00004947 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00004948 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004949 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00004950 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00004951 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4952 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004953 /*IsFunctionCall*/ true, CheckedVarArgs,
4954 UncoveredArg,
4955 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004956
4957 // Generate a diagnostic where an uncovered argument is detected.
4958 if (UncoveredArg.hasUncoveredArg()) {
4959 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4960 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4961 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4962 }
4963
Richard Smith55ce3522012-06-25 20:30:08 +00004964 if (CT != SLCT_NotALiteral)
4965 // Literal format string found, check done!
4966 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00004967
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004968 // Strftime is particular as it always uses a single 'time' argument,
4969 // so it is safe to pass a non-literal string.
4970 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00004971 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004972
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004973 // Do not emit diag when the string param is a macro expansion and the
4974 // format is either NSString or CFString. This is a hack to prevent
4975 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4976 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004977 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4978 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00004979 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004980
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004981 // If there are no arguments specified, warn with -Wformat-security, otherwise
4982 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004983 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00004984 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4985 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004986 switch (Type) {
4987 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004988 break;
4989 case FST_Kprintf:
4990 case FST_FreeBSDKPrintf:
4991 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00004992 Diag(FormatLoc, diag::note_format_security_fixit)
4993 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004994 break;
4995 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00004996 Diag(FormatLoc, diag::note_format_security_fixit)
4997 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004998 break;
4999 }
5000 } else {
5001 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005002 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005003 }
Richard Smith55ce3522012-06-25 20:30:08 +00005004 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005005}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005006
Ted Kremenekab278de2010-01-28 23:39:18 +00005007namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00005008class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5009protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00005010 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00005011 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00005012 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005013 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00005014 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00005015 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00005016 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00005017 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005018 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00005019 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00005020 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00005021 bool usesPositionalArgs;
5022 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005023 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00005024 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00005025 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005026 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005027
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005028public:
Stephen Hines648c3692016-09-16 01:07:04 +00005029 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005030 const Expr *origFormatExpr,
5031 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005032 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005033 ArrayRef<const Expr *> Args, unsigned formatIdx,
5034 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005035 llvm::SmallBitVector &CheckedVarArgs,
5036 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005037 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5038 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5039 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5040 usesPositionalArgs(false), atFirstArg(true),
5041 inFunctionCall(inFunctionCall), CallType(callType),
5042 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00005043 CoveredArgs.resize(numDataArgs);
5044 CoveredArgs.reset();
5045 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005046
Ted Kremenek019d2242010-01-29 01:50:07 +00005047 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005048
Ted Kremenek02087932010-07-16 02:11:22 +00005049 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005050 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005051
Jordan Rose92303592012-09-08 04:00:03 +00005052 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005053 const analyze_format_string::FormatSpecifier &FS,
5054 const analyze_format_string::ConversionSpecifier &CS,
5055 const char *startSpecifier, unsigned specifierLen,
5056 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00005057
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005058 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005059 const analyze_format_string::FormatSpecifier &FS,
5060 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005061
5062 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005063 const analyze_format_string::ConversionSpecifier &CS,
5064 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005065
Craig Toppere14c0f82014-03-12 04:55:44 +00005066 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005067
Craig Toppere14c0f82014-03-12 04:55:44 +00005068 void HandleInvalidPosition(const char *startSpecifier,
5069 unsigned specifierLen,
5070 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005071
Craig Toppere14c0f82014-03-12 04:55:44 +00005072 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005073
Craig Toppere14c0f82014-03-12 04:55:44 +00005074 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005075
Richard Trieu03cf7b72011-10-28 00:41:25 +00005076 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00005077 static void
5078 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5079 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5080 bool IsStringLocation, Range StringRange,
5081 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005082
Ted Kremenek02087932010-07-16 02:11:22 +00005083protected:
Ted Kremenekce815422010-07-19 21:25:57 +00005084 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5085 const char *startSpec,
5086 unsigned specifierLen,
5087 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005088
5089 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5090 const char *startSpec,
5091 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00005092
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005093 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00005094 CharSourceRange getSpecifierRange(const char *startSpecifier,
5095 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00005096 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005097
Ted Kremenek5739de72010-01-29 01:06:55 +00005098 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005099
5100 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5101 const analyze_format_string::ConversionSpecifier &CS,
5102 const char *startSpecifier, unsigned specifierLen,
5103 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005104
5105 template <typename Range>
5106 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5107 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005108 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00005109};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005110} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005111
Ted Kremenek02087932010-07-16 02:11:22 +00005112SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00005113 return OrigFormatExpr->getSourceRange();
5114}
5115
Ted Kremenek02087932010-07-16 02:11:22 +00005116CharSourceRange CheckFormatHandler::
5117getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00005118 SourceLocation Start = getLocationOfByte(startSpecifier);
5119 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5120
5121 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00005122 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00005123
5124 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005125}
5126
Ted Kremenek02087932010-07-16 02:11:22 +00005127SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00005128 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5129 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00005130}
5131
Ted Kremenek02087932010-07-16 02:11:22 +00005132void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5133 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00005134 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5135 getLocationOfByte(startSpecifier),
5136 /*IsStringLocation*/true,
5137 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00005138}
5139
Jordan Rose92303592012-09-08 04:00:03 +00005140void CheckFormatHandler::HandleInvalidLengthModifier(
5141 const analyze_format_string::FormatSpecifier &FS,
5142 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00005143 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00005144 using namespace analyze_format_string;
5145
5146 const LengthModifier &LM = FS.getLengthModifier();
5147 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5148
5149 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005150 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00005151 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005152 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005153 getLocationOfByte(LM.getStart()),
5154 /*IsStringLocation*/true,
5155 getSpecifierRange(startSpecifier, specifierLen));
5156
5157 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5158 << FixedLM->toString()
5159 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5160
5161 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005162 FixItHint Hint;
5163 if (DiagID == diag::warn_format_nonsensical_length)
5164 Hint = FixItHint::CreateRemoval(LMRange);
5165
5166 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005167 getLocationOfByte(LM.getStart()),
5168 /*IsStringLocation*/true,
5169 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00005170 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00005171 }
5172}
5173
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005174void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005175 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005176 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005177 using namespace analyze_format_string;
5178
5179 const LengthModifier &LM = FS.getLengthModifier();
5180 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5181
5182 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005183 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005184 if (FixedLM) {
5185 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5186 << LM.toString() << 0,
5187 getLocationOfByte(LM.getStart()),
5188 /*IsStringLocation*/true,
5189 getSpecifierRange(startSpecifier, specifierLen));
5190
5191 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5192 << FixedLM->toString()
5193 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5194
5195 } else {
5196 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5197 << LM.toString() << 0,
5198 getLocationOfByte(LM.getStart()),
5199 /*IsStringLocation*/true,
5200 getSpecifierRange(startSpecifier, specifierLen));
5201 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005202}
5203
5204void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5205 const analyze_format_string::ConversionSpecifier &CS,
5206 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005207 using namespace analyze_format_string;
5208
5209 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005210 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005211 if (FixedCS) {
5212 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5213 << CS.toString() << /*conversion specifier*/1,
5214 getLocationOfByte(CS.getStart()),
5215 /*IsStringLocation*/true,
5216 getSpecifierRange(startSpecifier, specifierLen));
5217
5218 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5219 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5220 << FixedCS->toString()
5221 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5222 } else {
5223 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5224 << CS.toString() << /*conversion specifier*/1,
5225 getLocationOfByte(CS.getStart()),
5226 /*IsStringLocation*/true,
5227 getSpecifierRange(startSpecifier, specifierLen));
5228 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005229}
5230
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005231void CheckFormatHandler::HandlePosition(const char *startPos,
5232 unsigned posLen) {
5233 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5234 getLocationOfByte(startPos),
5235 /*IsStringLocation*/true,
5236 getSpecifierRange(startPos, posLen));
5237}
5238
Ted Kremenekd1668192010-02-27 01:41:03 +00005239void
Ted Kremenek02087932010-07-16 02:11:22 +00005240CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5241 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005242 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5243 << (unsigned) p,
5244 getLocationOfByte(startPos), /*IsStringLocation*/true,
5245 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005246}
5247
Ted Kremenek02087932010-07-16 02:11:22 +00005248void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005249 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005250 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5251 getLocationOfByte(startPos),
5252 /*IsStringLocation*/true,
5253 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005254}
5255
Ted Kremenek02087932010-07-16 02:11:22 +00005256void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005257 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005258 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005259 EmitFormatDiagnostic(
5260 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5261 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5262 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005263 }
Ted Kremenek02087932010-07-16 02:11:22 +00005264}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005265
Jordan Rose58bbe422012-07-19 18:10:08 +00005266// Note that this may return NULL if there was an error parsing or building
5267// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005268const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005269 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005270}
5271
5272void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005273 // Does the number of data arguments exceed the number of
5274 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005275 if (!HasVAListArg) {
5276 // Find any arguments that weren't covered.
5277 CoveredArgs.flip();
5278 signed notCoveredArg = CoveredArgs.find_first();
5279 if (notCoveredArg >= 0) {
5280 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005281 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5282 } else {
5283 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005284 }
5285 }
5286}
5287
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005288void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5289 const Expr *ArgExpr) {
5290 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5291 "Invalid state");
5292
5293 if (!ArgExpr)
5294 return;
5295
5296 SourceLocation Loc = ArgExpr->getLocStart();
5297
5298 if (S.getSourceManager().isInSystemMacro(Loc))
5299 return;
5300
5301 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5302 for (auto E : DiagnosticExprs)
5303 PDiag << E->getSourceRange();
5304
5305 CheckFormatHandler::EmitFormatDiagnostic(
5306 S, IsFunctionCall, DiagnosticExprs[0],
5307 PDiag, Loc, /*IsStringLocation*/false,
5308 DiagnosticExprs[0]->getSourceRange());
5309}
5310
Ted Kremenekce815422010-07-19 21:25:57 +00005311bool
5312CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5313 SourceLocation Loc,
5314 const char *startSpec,
5315 unsigned specifierLen,
5316 const char *csStart,
5317 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005318 bool keepGoing = true;
5319 if (argIndex < NumDataArgs) {
5320 // Consider the argument coverered, even though the specifier doesn't
5321 // make sense.
5322 CoveredArgs.set(argIndex);
5323 }
5324 else {
5325 // If argIndex exceeds the number of data arguments we
5326 // don't issue a warning because that is just a cascade of warnings (and
5327 // they may have intended '%%' anyway). We don't want to continue processing
5328 // the format string after this point, however, as we will like just get
5329 // gibberish when trying to match arguments.
5330 keepGoing = false;
5331 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005332
5333 StringRef Specifier(csStart, csLen);
5334
5335 // If the specifier in non-printable, it could be the first byte of a UTF-8
5336 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5337 // hex value.
5338 std::string CodePointStr;
5339 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005340 llvm::UTF32 CodePoint;
5341 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5342 const llvm::UTF8 *E =
5343 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5344 llvm::ConversionResult Result =
5345 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005346
Justin Lebar90910552016-09-30 00:38:45 +00005347 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005348 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005349 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005350 }
5351
5352 llvm::raw_string_ostream OS(CodePointStr);
5353 if (CodePoint < 256)
5354 OS << "\\x" << llvm::format("%02x", CodePoint);
5355 else if (CodePoint <= 0xFFFF)
5356 OS << "\\u" << llvm::format("%04x", CodePoint);
5357 else
5358 OS << "\\U" << llvm::format("%08x", CodePoint);
5359 OS.flush();
5360 Specifier = CodePointStr;
5361 }
5362
5363 EmitFormatDiagnostic(
5364 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5365 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5366
Ted Kremenekce815422010-07-19 21:25:57 +00005367 return keepGoing;
5368}
5369
Richard Trieu03cf7b72011-10-28 00:41:25 +00005370void
5371CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5372 const char *startSpec,
5373 unsigned specifierLen) {
5374 EmitFormatDiagnostic(
5375 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5376 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5377}
5378
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005379bool
5380CheckFormatHandler::CheckNumArgs(
5381 const analyze_format_string::FormatSpecifier &FS,
5382 const analyze_format_string::ConversionSpecifier &CS,
5383 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5384
5385 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005386 PartialDiagnostic PDiag = FS.usesPositionalArg()
5387 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5388 << (argIndex+1) << NumDataArgs)
5389 : S.PDiag(diag::warn_printf_insufficient_data_args);
5390 EmitFormatDiagnostic(
5391 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5392 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005393
5394 // Since more arguments than conversion tokens are given, by extension
5395 // all arguments are covered, so mark this as so.
5396 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005397 return false;
5398 }
5399 return true;
5400}
5401
Richard Trieu03cf7b72011-10-28 00:41:25 +00005402template<typename Range>
5403void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5404 SourceLocation Loc,
5405 bool IsStringLocation,
5406 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005407 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005408 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005409 Loc, IsStringLocation, StringRange, FixIt);
5410}
5411
5412/// \brief If the format string is not within the funcion call, emit a note
5413/// so that the function call and string are in diagnostic messages.
5414///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005415/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005416/// call and only one diagnostic message will be produced. Otherwise, an
5417/// extra note will be emitted pointing to location of the format string.
5418///
5419/// \param ArgumentExpr the expression that is passed as the format string
5420/// argument in the function call. Used for getting locations when two
5421/// diagnostics are emitted.
5422///
5423/// \param PDiag the callee should already have provided any strings for the
5424/// diagnostic message. This function only adds locations and fixits
5425/// to diagnostics.
5426///
5427/// \param Loc primary location for diagnostic. If two diagnostics are
5428/// required, one will be at Loc and a new SourceLocation will be created for
5429/// the other one.
5430///
5431/// \param IsStringLocation if true, Loc points to the format string should be
5432/// used for the note. Otherwise, Loc points to the argument list and will
5433/// be used with PDiag.
5434///
5435/// \param StringRange some or all of the string to highlight. This is
5436/// templated so it can accept either a CharSourceRange or a SourceRange.
5437///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005438/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005439template <typename Range>
5440void CheckFormatHandler::EmitFormatDiagnostic(
5441 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5442 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5443 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005444 if (InFunctionCall) {
5445 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5446 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005447 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00005448 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005449 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5450 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00005451
5452 const Sema::SemaDiagnosticBuilder &Note =
5453 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5454 diag::note_format_string_defined);
5455
5456 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005457 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005458 }
5459}
5460
Ted Kremenek02087932010-07-16 02:11:22 +00005461//===--- CHECK: Printf format string checking ------------------------------===//
5462
5463namespace {
5464class CheckPrintfHandler : public CheckFormatHandler {
5465public:
Stephen Hines648c3692016-09-16 01:07:04 +00005466 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005467 const Expr *origFormatExpr,
5468 const Sema::FormatStringType type, unsigned firstDataArg,
5469 unsigned numDataArgs, bool isObjC, const char *beg,
5470 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005471 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005472 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005473 llvm::SmallBitVector &CheckedVarArgs,
5474 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005475 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5476 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5477 inFunctionCall, CallType, CheckedVarArgs,
5478 UncoveredArg) {}
5479
5480 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5481
5482 /// Returns true if '%@' specifiers are allowed in the format string.
5483 bool allowsObjCArg() const {
5484 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5485 FSType == Sema::FST_OSTrace;
5486 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00005487
Ted Kremenek02087932010-07-16 02:11:22 +00005488 bool HandleInvalidPrintfConversionSpecifier(
5489 const analyze_printf::PrintfSpecifier &FS,
5490 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005491 unsigned specifierLen) override;
5492
Ted Kremenek02087932010-07-16 02:11:22 +00005493 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5494 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005495 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005496 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5497 const char *StartSpecifier,
5498 unsigned SpecifierLen,
5499 const Expr *E);
5500
Ted Kremenek02087932010-07-16 02:11:22 +00005501 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5502 const char *startSpecifier, unsigned specifierLen);
5503 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5504 const analyze_printf::OptionalAmount &Amt,
5505 unsigned type,
5506 const char *startSpecifier, unsigned specifierLen);
5507 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5508 const analyze_printf::OptionalFlag &flag,
5509 const char *startSpecifier, unsigned specifierLen);
5510 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5511 const analyze_printf::OptionalFlag &ignoredFlag,
5512 const analyze_printf::OptionalFlag &flag,
5513 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005514 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00005515 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00005516
5517 void HandleEmptyObjCModifierFlag(const char *startFlag,
5518 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005519
Ted Kremenek2b417712015-07-02 05:39:16 +00005520 void HandleInvalidObjCModifierFlag(const char *startFlag,
5521 unsigned flagLen) override;
5522
5523 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5524 const char *flagsEnd,
5525 const char *conversionPosition)
5526 override;
5527};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005528} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00005529
5530bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5531 const analyze_printf::PrintfSpecifier &FS,
5532 const char *startSpecifier,
5533 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005534 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005535 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005536
Ted Kremenekce815422010-07-19 21:25:57 +00005537 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5538 getLocationOfByte(CS.getStart()),
5539 startSpecifier, specifierLen,
5540 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00005541}
5542
Ted Kremenek02087932010-07-16 02:11:22 +00005543bool CheckPrintfHandler::HandleAmount(
5544 const analyze_format_string::OptionalAmount &Amt,
5545 unsigned k, const char *startSpecifier,
5546 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005547 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005548 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00005549 unsigned argIndex = Amt.getArgIndex();
5550 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005551 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5552 << k,
5553 getLocationOfByte(Amt.getStart()),
5554 /*IsStringLocation*/true,
5555 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005556 // Don't do any more checking. We will just emit
5557 // spurious errors.
5558 return false;
5559 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005560
Ted Kremenek5739de72010-01-29 01:06:55 +00005561 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00005562 // Although not in conformance with C99, we also allow the argument to be
5563 // an 'unsigned int' as that is a reasonably safe case. GCC also
5564 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00005565 CoveredArgs.set(argIndex);
5566 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005567 if (!Arg)
5568 return false;
5569
Ted Kremenek5739de72010-01-29 01:06:55 +00005570 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005571
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005572 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5573 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005574
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005575 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005576 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005577 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00005578 << T << Arg->getSourceRange(),
5579 getLocationOfByte(Amt.getStart()),
5580 /*IsStringLocation*/true,
5581 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005582 // Don't do any more checking. We will just emit
5583 // spurious errors.
5584 return false;
5585 }
5586 }
5587 }
5588 return true;
5589}
Ted Kremenek5739de72010-01-29 01:06:55 +00005590
Tom Careb49ec692010-06-17 19:00:27 +00005591void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00005592 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005593 const analyze_printf::OptionalAmount &Amt,
5594 unsigned type,
5595 const char *startSpecifier,
5596 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005597 const analyze_printf::PrintfConversionSpecifier &CS =
5598 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00005599
Richard Trieu03cf7b72011-10-28 00:41:25 +00005600 FixItHint fixit =
5601 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5602 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5603 Amt.getConstantLength()))
5604 : FixItHint();
5605
5606 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5607 << type << CS.toString(),
5608 getLocationOfByte(Amt.getStart()),
5609 /*IsStringLocation*/true,
5610 getSpecifierRange(startSpecifier, specifierLen),
5611 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00005612}
5613
Ted Kremenek02087932010-07-16 02:11:22 +00005614void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005615 const analyze_printf::OptionalFlag &flag,
5616 const char *startSpecifier,
5617 unsigned specifierLen) {
5618 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005619 const analyze_printf::PrintfConversionSpecifier &CS =
5620 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00005621 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5622 << flag.toString() << CS.toString(),
5623 getLocationOfByte(flag.getPosition()),
5624 /*IsStringLocation*/true,
5625 getSpecifierRange(startSpecifier, specifierLen),
5626 FixItHint::CreateRemoval(
5627 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005628}
5629
5630void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00005631 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005632 const analyze_printf::OptionalFlag &ignoredFlag,
5633 const analyze_printf::OptionalFlag &flag,
5634 const char *startSpecifier,
5635 unsigned specifierLen) {
5636 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005637 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5638 << ignoredFlag.toString() << flag.toString(),
5639 getLocationOfByte(ignoredFlag.getPosition()),
5640 /*IsStringLocation*/true,
5641 getSpecifierRange(startSpecifier, specifierLen),
5642 FixItHint::CreateRemoval(
5643 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005644}
5645
Ted Kremenek2b417712015-07-02 05:39:16 +00005646// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5647// bool IsStringLocation, Range StringRange,
5648// ArrayRef<FixItHint> Fixit = None);
5649
5650void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5651 unsigned flagLen) {
5652 // Warn about an empty flag.
5653 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5654 getLocationOfByte(startFlag),
5655 /*IsStringLocation*/true,
5656 getSpecifierRange(startFlag, flagLen));
5657}
5658
5659void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5660 unsigned flagLen) {
5661 // Warn about an invalid flag.
5662 auto Range = getSpecifierRange(startFlag, flagLen);
5663 StringRef flag(startFlag, flagLen);
5664 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5665 getLocationOfByte(startFlag),
5666 /*IsStringLocation*/true,
5667 Range, FixItHint::CreateRemoval(Range));
5668}
5669
5670void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5671 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5672 // Warn about using '[...]' without a '@' conversion.
5673 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5674 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5675 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5676 getLocationOfByte(conversionPosition),
5677 /*IsStringLocation*/true,
5678 Range, FixItHint::CreateRemoval(Range));
5679}
5680
Richard Smith55ce3522012-06-25 20:30:08 +00005681// Determines if the specified is a C++ class or struct containing
5682// a member with the specified name and kind (e.g. a CXXMethodDecl named
5683// "c_str()").
5684template<typename MemberKind>
5685static llvm::SmallPtrSet<MemberKind*, 1>
5686CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5687 const RecordType *RT = Ty->getAs<RecordType>();
5688 llvm::SmallPtrSet<MemberKind*, 1> Results;
5689
5690 if (!RT)
5691 return Results;
5692 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005693 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005694 return Results;
5695
Alp Tokerb6cc5922014-05-03 03:45:55 +00005696 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005697 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005698 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005699
5700 // We just need to include all members of the right kind turned up by the
5701 // filter, at this point.
5702 if (S.LookupQualifiedName(R, RT->getDecl()))
5703 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5704 NamedDecl *decl = (*I)->getUnderlyingDecl();
5705 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5706 Results.insert(FK);
5707 }
5708 return Results;
5709}
5710
Richard Smith2868a732014-02-28 01:36:39 +00005711/// Check if we could call '.c_str()' on an object.
5712///
5713/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5714/// allow the call, or if it would be ambiguous).
5715bool Sema::hasCStrMethod(const Expr *E) {
5716 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5717 MethodSet Results =
5718 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5719 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5720 MI != ME; ++MI)
5721 if ((*MI)->getMinRequiredArguments() == 0)
5722 return true;
5723 return false;
5724}
5725
Richard Smith55ce3522012-06-25 20:30:08 +00005726// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005727// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00005728// Returns true when a c_str() conversion method is found.
5729bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00005730 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00005731 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5732
5733 MethodSet Results =
5734 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5735
5736 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5737 MI != ME; ++MI) {
5738 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00005739 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00005740 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00005741 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00005742 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00005743 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5744 << "c_str()"
5745 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5746 return true;
5747 }
5748 }
5749
5750 return false;
5751}
5752
Ted Kremenekab278de2010-01-28 23:39:18 +00005753bool
Ted Kremenek02087932010-07-16 02:11:22 +00005754CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00005755 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00005756 const char *startSpecifier,
5757 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005758 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00005759 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005760 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00005761
Ted Kremenek6cd69422010-07-19 22:01:06 +00005762 if (FS.consumesDataArgument()) {
5763 if (atFirstArg) {
5764 atFirstArg = false;
5765 usesPositionalArgs = FS.usesPositionalArg();
5766 }
5767 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005768 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5769 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005770 return false;
5771 }
Ted Kremenek5739de72010-01-29 01:06:55 +00005772 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005773
Ted Kremenekd1668192010-02-27 01:41:03 +00005774 // First check if the field width, precision, and conversion specifier
5775 // have matching data arguments.
5776 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5777 startSpecifier, specifierLen)) {
5778 return false;
5779 }
5780
5781 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5782 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005783 return false;
5784 }
5785
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005786 if (!CS.consumesDataArgument()) {
5787 // FIXME: Technically specifying a precision or field width here
5788 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00005789 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005790 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005791
Ted Kremenek4a49d982010-02-26 19:18:41 +00005792 // Consume the argument.
5793 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00005794 if (argIndex < NumDataArgs) {
5795 // The check to see if the argIndex is valid will come later.
5796 // We set the bit here because we may exit early from this
5797 // function if we encounter some other error.
5798 CoveredArgs.set(argIndex);
5799 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00005800
Dimitry Andric6b5ed342015-02-19 22:32:33 +00005801 // FreeBSD kernel extensions.
5802 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5803 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5804 // We need at least two arguments.
5805 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5806 return false;
5807
5808 // Claim the second argument.
5809 CoveredArgs.set(argIndex + 1);
5810
5811 // Type check the first argument (int for %b, pointer for %D)
5812 const Expr *Ex = getDataArg(argIndex);
5813 const analyze_printf::ArgType &AT =
5814 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5815 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5816 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5817 EmitFormatDiagnostic(
5818 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5819 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5820 << false << Ex->getSourceRange(),
5821 Ex->getLocStart(), /*IsStringLocation*/false,
5822 getSpecifierRange(startSpecifier, specifierLen));
5823
5824 // Type check the second argument (char * for both %b and %D)
5825 Ex = getDataArg(argIndex + 1);
5826 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5827 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5828 EmitFormatDiagnostic(
5829 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5830 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5831 << false << Ex->getSourceRange(),
5832 Ex->getLocStart(), /*IsStringLocation*/false,
5833 getSpecifierRange(startSpecifier, specifierLen));
5834
5835 return true;
5836 }
5837
Ted Kremenek4a49d982010-02-26 19:18:41 +00005838 // Check for using an Objective-C specific conversion specifier
5839 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00005840 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00005841 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5842 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00005843 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005844
Mehdi Amini06d367c2016-10-24 20:39:34 +00005845 // %P can only be used with os_log.
5846 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
5847 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5848 specifierLen);
5849 }
5850
5851 // %n is not allowed with os_log.
5852 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
5853 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
5854 getLocationOfByte(CS.getStart()),
5855 /*IsStringLocation*/ false,
5856 getSpecifierRange(startSpecifier, specifierLen));
5857
5858 return true;
5859 }
5860
5861 // Only scalars are allowed for os_trace.
5862 if (FSType == Sema::FST_OSTrace &&
5863 (CS.getKind() == ConversionSpecifier::PArg ||
5864 CS.getKind() == ConversionSpecifier::sArg ||
5865 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
5866 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5867 specifierLen);
5868 }
5869
5870 // Check for use of public/private annotation outside of os_log().
5871 if (FSType != Sema::FST_OSLog) {
5872 if (FS.isPublic().isSet()) {
5873 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5874 << "public",
5875 getLocationOfByte(FS.isPublic().getPosition()),
5876 /*IsStringLocation*/ false,
5877 getSpecifierRange(startSpecifier, specifierLen));
5878 }
5879 if (FS.isPrivate().isSet()) {
5880 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5881 << "private",
5882 getLocationOfByte(FS.isPrivate().getPosition()),
5883 /*IsStringLocation*/ false,
5884 getSpecifierRange(startSpecifier, specifierLen));
5885 }
5886 }
5887
Tom Careb49ec692010-06-17 19:00:27 +00005888 // Check for invalid use of field width
5889 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00005890 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00005891 startSpecifier, specifierLen);
5892 }
5893
5894 // Check for invalid use of precision
5895 if (!FS.hasValidPrecision()) {
5896 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5897 startSpecifier, specifierLen);
5898 }
5899
Mehdi Amini06d367c2016-10-24 20:39:34 +00005900 // Precision is mandatory for %P specifier.
5901 if (CS.getKind() == ConversionSpecifier::PArg &&
5902 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
5903 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
5904 getLocationOfByte(startSpecifier),
5905 /*IsStringLocation*/ false,
5906 getSpecifierRange(startSpecifier, specifierLen));
5907 }
5908
Tom Careb49ec692010-06-17 19:00:27 +00005909 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00005910 if (!FS.hasValidThousandsGroupingPrefix())
5911 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005912 if (!FS.hasValidLeadingZeros())
5913 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5914 if (!FS.hasValidPlusPrefix())
5915 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00005916 if (!FS.hasValidSpacePrefix())
5917 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005918 if (!FS.hasValidAlternativeForm())
5919 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5920 if (!FS.hasValidLeftJustified())
5921 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5922
5923 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00005924 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5925 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5926 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005927 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5928 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5929 startSpecifier, specifierLen);
5930
5931 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005932 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005933 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5934 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005935 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005936 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005937 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005938 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5939 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00005940
Jordan Rose92303592012-09-08 04:00:03 +00005941 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5942 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5943
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005944 // The remaining checks depend on the data arguments.
5945 if (HasVAListArg)
5946 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005947
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005948 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005949 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005950
Jordan Rose58bbe422012-07-19 18:10:08 +00005951 const Expr *Arg = getDataArg(argIndex);
5952 if (!Arg)
5953 return true;
5954
5955 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00005956}
5957
Jordan Roseaee34382012-09-05 22:56:26 +00005958static bool requiresParensToAddCast(const Expr *E) {
5959 // FIXME: We should have a general way to reason about operator
5960 // precedence and whether parens are actually needed here.
5961 // Take care of a few common cases where they aren't.
5962 const Expr *Inside = E->IgnoreImpCasts();
5963 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5964 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5965
5966 switch (Inside->getStmtClass()) {
5967 case Stmt::ArraySubscriptExprClass:
5968 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005969 case Stmt::CharacterLiteralClass:
5970 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005971 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005972 case Stmt::FloatingLiteralClass:
5973 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005974 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005975 case Stmt::ObjCArrayLiteralClass:
5976 case Stmt::ObjCBoolLiteralExprClass:
5977 case Stmt::ObjCBoxedExprClass:
5978 case Stmt::ObjCDictionaryLiteralClass:
5979 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005980 case Stmt::ObjCIvarRefExprClass:
5981 case Stmt::ObjCMessageExprClass:
5982 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005983 case Stmt::ObjCStringLiteralClass:
5984 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005985 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005986 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005987 case Stmt::UnaryOperatorClass:
5988 return false;
5989 default:
5990 return true;
5991 }
5992}
5993
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005994static std::pair<QualType, StringRef>
5995shouldNotPrintDirectly(const ASTContext &Context,
5996 QualType IntendedTy,
5997 const Expr *E) {
5998 // Use a 'while' to peel off layers of typedefs.
5999 QualType TyTy = IntendedTy;
6000 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6001 StringRef Name = UserTy->getDecl()->getName();
6002 QualType CastTy = llvm::StringSwitch<QualType>(Name)
6003 .Case("NSInteger", Context.LongTy)
6004 .Case("NSUInteger", Context.UnsignedLongTy)
6005 .Case("SInt32", Context.IntTy)
6006 .Case("UInt32", Context.UnsignedIntTy)
6007 .Default(QualType());
6008
6009 if (!CastTy.isNull())
6010 return std::make_pair(CastTy, Name);
6011
6012 TyTy = UserTy->desugar();
6013 }
6014
6015 // Strip parens if necessary.
6016 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6017 return shouldNotPrintDirectly(Context,
6018 PE->getSubExpr()->getType(),
6019 PE->getSubExpr());
6020
6021 // If this is a conditional expression, then its result type is constructed
6022 // via usual arithmetic conversions and thus there might be no necessary
6023 // typedef sugar there. Recurse to operands to check for NSInteger &
6024 // Co. usage condition.
6025 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6026 QualType TrueTy, FalseTy;
6027 StringRef TrueName, FalseName;
6028
6029 std::tie(TrueTy, TrueName) =
6030 shouldNotPrintDirectly(Context,
6031 CO->getTrueExpr()->getType(),
6032 CO->getTrueExpr());
6033 std::tie(FalseTy, FalseName) =
6034 shouldNotPrintDirectly(Context,
6035 CO->getFalseExpr()->getType(),
6036 CO->getFalseExpr());
6037
6038 if (TrueTy == FalseTy)
6039 return std::make_pair(TrueTy, TrueName);
6040 else if (TrueTy.isNull())
6041 return std::make_pair(FalseTy, FalseName);
6042 else if (FalseTy.isNull())
6043 return std::make_pair(TrueTy, TrueName);
6044 }
6045
6046 return std::make_pair(QualType(), StringRef());
6047}
6048
Richard Smith55ce3522012-06-25 20:30:08 +00006049bool
6050CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6051 const char *StartSpecifier,
6052 unsigned SpecifierLen,
6053 const Expr *E) {
6054 using namespace analyze_format_string;
6055 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006056 // Now type check the data expression that matches the
6057 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006058 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00006059 if (!AT.isValid())
6060 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00006061
Jordan Rose598ec092012-12-05 18:44:40 +00006062 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00006063 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6064 ExprTy = TET->getUnderlyingExpr()->getType();
6065 }
6066
Seth Cantrellb4802962015-03-04 03:12:10 +00006067 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6068
6069 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00006070 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006071 }
Jordan Rose98709982012-06-04 22:48:57 +00006072
Jordan Rose22b74712012-09-05 22:56:19 +00006073 // Look through argument promotions for our error message's reported type.
6074 // This includes the integral and floating promotions, but excludes array
6075 // and function pointer decay; seeing that an argument intended to be a
6076 // string has type 'char [6]' is probably more confusing than 'char *'.
6077 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6078 if (ICE->getCastKind() == CK_IntegralCast ||
6079 ICE->getCastKind() == CK_FloatingCast) {
6080 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006081 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006082
6083 // Check if we didn't match because of an implicit cast from a 'char'
6084 // or 'short' to an 'int'. This is done because printf is a varargs
6085 // function.
6086 if (ICE->getType() == S.Context.IntTy ||
6087 ICE->getType() == S.Context.UnsignedIntTy) {
6088 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006089 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006090 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006091 }
Jordan Rose98709982012-06-04 22:48:57 +00006092 }
Jordan Rose598ec092012-12-05 18:44:40 +00006093 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6094 // Special case for 'a', which has type 'int' in C.
6095 // Note, however, that we do /not/ want to treat multibyte constants like
6096 // 'MooV' as characters! This form is deprecated but still exists.
6097 if (ExprTy == S.Context.IntTy)
6098 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6099 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006100 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006101
Jordan Rosebc53ed12014-05-31 04:12:14 +00006102 // Look through enums to their underlying type.
6103 bool IsEnum = false;
6104 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6105 ExprTy = EnumTy->getDecl()->getIntegerType();
6106 IsEnum = true;
6107 }
6108
Jordan Rose0e5badd2012-12-05 18:44:49 +00006109 // %C in an Objective-C context prints a unichar, not a wchar_t.
6110 // If the argument is an integer of some kind, believe the %C and suggest
6111 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006112 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006113 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006114 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6115 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6116 !ExprTy->isCharType()) {
6117 // 'unichar' is defined as a typedef of unsigned short, but we should
6118 // prefer using the typedef if it is visible.
6119 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006120
6121 // While we are here, check if the value is an IntegerLiteral that happens
6122 // to be within the valid range.
6123 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6124 const llvm::APInt &V = IL->getValue();
6125 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6126 return true;
6127 }
6128
Jordan Rose0e5badd2012-12-05 18:44:49 +00006129 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6130 Sema::LookupOrdinaryName);
6131 if (S.LookupName(Result, S.getCurScope())) {
6132 NamedDecl *ND = Result.getFoundDecl();
6133 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6134 if (TD->getUnderlyingType() == IntendedTy)
6135 IntendedTy = S.Context.getTypedefType(TD);
6136 }
6137 }
6138 }
6139
6140 // Special-case some of Darwin's platform-independence types by suggesting
6141 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006142 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006143 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006144 QualType CastTy;
6145 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6146 if (!CastTy.isNull()) {
6147 IntendedTy = CastTy;
6148 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006149 }
6150 }
6151
Jordan Rose22b74712012-09-05 22:56:19 +00006152 // We may be able to offer a FixItHint if it is a supported type.
6153 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006154 bool success =
6155 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006156
Jordan Rose22b74712012-09-05 22:56:19 +00006157 if (success) {
6158 // Get the fix string from the fixed format specifier
6159 SmallString<16> buf;
6160 llvm::raw_svector_ostream os(buf);
6161 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006162
Jordan Roseaee34382012-09-05 22:56:26 +00006163 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6164
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006165 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00006166 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6167 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6168 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6169 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00006170 // In this case, the specifier is wrong and should be changed to match
6171 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006172 EmitFormatDiagnostic(S.PDiag(diag)
6173 << AT.getRepresentativeTypeName(S.Context)
6174 << IntendedTy << IsEnum << E->getSourceRange(),
6175 E->getLocStart(),
6176 /*IsStringLocation*/ false, SpecRange,
6177 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006178 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006179 // The canonical type for formatting this value is different from the
6180 // actual type of the expression. (This occurs, for example, with Darwin's
6181 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6182 // should be printed as 'long' for 64-bit compatibility.)
6183 // Rather than emitting a normal format/argument mismatch, we want to
6184 // add a cast to the recommended type (and correct the format string
6185 // if necessary).
6186 SmallString<16> CastBuf;
6187 llvm::raw_svector_ostream CastFix(CastBuf);
6188 CastFix << "(";
6189 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6190 CastFix << ")";
6191
6192 SmallVector<FixItHint,4> Hints;
6193 if (!AT.matchesType(S.Context, IntendedTy))
6194 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6195
6196 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6197 // If there's already a cast present, just replace it.
6198 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6199 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6200
6201 } else if (!requiresParensToAddCast(E)) {
6202 // If the expression has high enough precedence,
6203 // just write the C-style cast.
6204 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6205 CastFix.str()));
6206 } else {
6207 // Otherwise, add parens around the expression as well as the cast.
6208 CastFix << "(";
6209 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6210 CastFix.str()));
6211
Alp Tokerb6cc5922014-05-03 03:45:55 +00006212 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006213 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6214 }
6215
Jordan Rose0e5badd2012-12-05 18:44:49 +00006216 if (ShouldNotPrintDirectly) {
6217 // The expression has a type that should not be printed directly.
6218 // We extract the name from the typedef because we don't want to show
6219 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006220 StringRef Name;
6221 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6222 Name = TypedefTy->getDecl()->getName();
6223 else
6224 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006225 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006226 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006227 << E->getSourceRange(),
6228 E->getLocStart(), /*IsStringLocation=*/false,
6229 SpecRange, Hints);
6230 } else {
6231 // In this case, the expression could be printed using a different
6232 // specifier, but we've decided that the specifier is probably correct
6233 // and we should cast instead. Just use the normal warning message.
6234 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006235 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6236 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006237 << E->getSourceRange(),
6238 E->getLocStart(), /*IsStringLocation*/false,
6239 SpecRange, Hints);
6240 }
Jordan Roseaee34382012-09-05 22:56:26 +00006241 }
Jordan Rose22b74712012-09-05 22:56:19 +00006242 } else {
6243 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6244 SpecifierLen);
6245 // Since the warning for passing non-POD types to variadic functions
6246 // was deferred until now, we emit a warning for non-POD
6247 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006248 switch (S.isValidVarArgType(ExprTy)) {
6249 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006250 case Sema::VAK_ValidInCXX11: {
6251 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6252 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6253 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6254 }
Richard Smithd7293d72013-08-05 18:49:43 +00006255
Seth Cantrellb4802962015-03-04 03:12:10 +00006256 EmitFormatDiagnostic(
6257 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6258 << IsEnum << CSR << E->getSourceRange(),
6259 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6260 break;
6261 }
Richard Smithd7293d72013-08-05 18:49:43 +00006262 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006263 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006264 EmitFormatDiagnostic(
6265 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006266 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006267 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006268 << CallType
6269 << AT.getRepresentativeTypeName(S.Context)
6270 << CSR
6271 << E->getSourceRange(),
6272 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006273 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006274 break;
6275
6276 case Sema::VAK_Invalid:
6277 if (ExprTy->isObjCObjectType())
6278 EmitFormatDiagnostic(
6279 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6280 << S.getLangOpts().CPlusPlus11
6281 << ExprTy
6282 << CallType
6283 << AT.getRepresentativeTypeName(S.Context)
6284 << CSR
6285 << E->getSourceRange(),
6286 E->getLocStart(), /*IsStringLocation*/false, CSR);
6287 else
6288 // FIXME: If this is an initializer list, suggest removing the braces
6289 // or inserting a cast to the target type.
6290 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6291 << isa<InitListExpr>(E) << ExprTy << CallType
6292 << AT.getRepresentativeTypeName(S.Context)
6293 << E->getSourceRange();
6294 break;
6295 }
6296
6297 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6298 "format string specifier index out of range");
6299 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006300 }
6301
Ted Kremenekab278de2010-01-28 23:39:18 +00006302 return true;
6303}
6304
Ted Kremenek02087932010-07-16 02:11:22 +00006305//===--- CHECK: Scanf format string checking ------------------------------===//
6306
6307namespace {
6308class CheckScanfHandler : public CheckFormatHandler {
6309public:
Stephen Hines648c3692016-09-16 01:07:04 +00006310 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006311 const Expr *origFormatExpr, Sema::FormatStringType type,
6312 unsigned firstDataArg, unsigned numDataArgs,
6313 const char *beg, bool hasVAListArg,
6314 ArrayRef<const Expr *> Args, unsigned formatIdx,
6315 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006316 llvm::SmallBitVector &CheckedVarArgs,
6317 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006318 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6319 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6320 inFunctionCall, CallType, CheckedVarArgs,
6321 UncoveredArg) {}
6322
Ted Kremenek02087932010-07-16 02:11:22 +00006323 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6324 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006325 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006326
6327 bool HandleInvalidScanfConversionSpecifier(
6328 const analyze_scanf::ScanfSpecifier &FS,
6329 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006330 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006331
Craig Toppere14c0f82014-03-12 04:55:44 +00006332 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006333};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006334} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006335
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006336void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6337 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006338 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6339 getLocationOfByte(end), /*IsStringLocation*/true,
6340 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006341}
6342
Ted Kremenekce815422010-07-19 21:25:57 +00006343bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6344 const analyze_scanf::ScanfSpecifier &FS,
6345 const char *startSpecifier,
6346 unsigned specifierLen) {
6347
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006348 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006349 FS.getConversionSpecifier();
6350
6351 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6352 getLocationOfByte(CS.getStart()),
6353 startSpecifier, specifierLen,
6354 CS.getStart(), CS.getLength());
6355}
6356
Ted Kremenek02087932010-07-16 02:11:22 +00006357bool CheckScanfHandler::HandleScanfSpecifier(
6358 const analyze_scanf::ScanfSpecifier &FS,
6359 const char *startSpecifier,
6360 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006361 using namespace analyze_scanf;
6362 using namespace analyze_format_string;
6363
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006364 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006365
Ted Kremenek6cd69422010-07-19 22:01:06 +00006366 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6367 // be used to decide if we are using positional arguments consistently.
6368 if (FS.consumesDataArgument()) {
6369 if (atFirstArg) {
6370 atFirstArg = false;
6371 usesPositionalArgs = FS.usesPositionalArg();
6372 }
6373 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006374 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6375 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006376 return false;
6377 }
Ted Kremenek02087932010-07-16 02:11:22 +00006378 }
6379
6380 // Check if the field with is non-zero.
6381 const OptionalAmount &Amt = FS.getFieldWidth();
6382 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6383 if (Amt.getConstantAmount() == 0) {
6384 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6385 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006386 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6387 getLocationOfByte(Amt.getStart()),
6388 /*IsStringLocation*/true, R,
6389 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006390 }
6391 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006392
Ted Kremenek02087932010-07-16 02:11:22 +00006393 if (!FS.consumesDataArgument()) {
6394 // FIXME: Technically specifying a precision or field width here
6395 // makes no sense. Worth issuing a warning at some point.
6396 return true;
6397 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006398
Ted Kremenek02087932010-07-16 02:11:22 +00006399 // Consume the argument.
6400 unsigned argIndex = FS.getArgIndex();
6401 if (argIndex < NumDataArgs) {
6402 // The check to see if the argIndex is valid will come later.
6403 // We set the bit here because we may exit early from this
6404 // function if we encounter some other error.
6405 CoveredArgs.set(argIndex);
6406 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006407
Ted Kremenek4407ea42010-07-20 20:04:47 +00006408 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006409 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006410 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6411 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006412 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006413 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006414 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006415 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6416 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006417
Jordan Rose92303592012-09-08 04:00:03 +00006418 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6419 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6420
Ted Kremenek02087932010-07-16 02:11:22 +00006421 // The remaining checks depend on the data arguments.
6422 if (HasVAListArg)
6423 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006424
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006425 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006426 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006427
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006428 // Check that the argument type matches the format specifier.
6429 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006430 if (!Ex)
6431 return true;
6432
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006433 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006434
6435 if (!AT.isValid()) {
6436 return true;
6437 }
6438
Seth Cantrellb4802962015-03-04 03:12:10 +00006439 analyze_format_string::ArgType::MatchKind match =
6440 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006441 if (match == analyze_format_string::ArgType::Match) {
6442 return true;
6443 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006444
Seth Cantrell79340072015-03-04 05:58:08 +00006445 ScanfSpecifier fixedFS = FS;
6446 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6447 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006448
Seth Cantrell79340072015-03-04 05:58:08 +00006449 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6450 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6451 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6452 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006453
Seth Cantrell79340072015-03-04 05:58:08 +00006454 if (success) {
6455 // Get the fix string from the fixed format specifier.
6456 SmallString<128> buf;
6457 llvm::raw_svector_ostream os(buf);
6458 fixedFS.toString(os);
6459
6460 EmitFormatDiagnostic(
6461 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6462 << Ex->getType() << false << Ex->getSourceRange(),
6463 Ex->getLocStart(),
6464 /*IsStringLocation*/ false,
6465 getSpecifierRange(startSpecifier, specifierLen),
6466 FixItHint::CreateReplacement(
6467 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6468 } else {
6469 EmitFormatDiagnostic(S.PDiag(diag)
6470 << AT.getRepresentativeTypeName(S.Context)
6471 << Ex->getType() << false << Ex->getSourceRange(),
6472 Ex->getLocStart(),
6473 /*IsStringLocation*/ false,
6474 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006475 }
6476
Ted Kremenek02087932010-07-16 02:11:22 +00006477 return true;
6478}
6479
Stephen Hines648c3692016-09-16 01:07:04 +00006480static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006481 const Expr *OrigFormatExpr,
6482 ArrayRef<const Expr *> Args,
6483 bool HasVAListArg, unsigned format_idx,
6484 unsigned firstDataArg,
6485 Sema::FormatStringType Type,
6486 bool inFunctionCall,
6487 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006488 llvm::SmallBitVector &CheckedVarArgs,
6489 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00006490 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00006491 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006492 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006493 S, inFunctionCall, Args[format_idx],
6494 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006495 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006496 return;
6497 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006498
Ted Kremenekab278de2010-01-28 23:39:18 +00006499 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006500 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00006501 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006502 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006503 const ConstantArrayType *T =
6504 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006505 assert(T && "String literal not of constant array type!");
6506 size_t TypeSize = T->getSize().getZExtValue();
6507 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006508 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006509
6510 // Emit a warning if the string literal is truncated and does not contain an
6511 // embedded null character.
6512 if (TypeSize <= StrRef.size() &&
6513 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6514 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006515 S, inFunctionCall, Args[format_idx],
6516 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006517 FExpr->getLocStart(),
6518 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6519 return;
6520 }
6521
Ted Kremenekab278de2010-01-28 23:39:18 +00006522 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006523 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006524 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006525 S, inFunctionCall, Args[format_idx],
6526 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006527 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006528 return;
6529 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006530
6531 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00006532 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6533 Type == Sema::FST_OSTrace) {
6534 CheckPrintfHandler H(
6535 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6536 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6537 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6538 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006539
Hans Wennborg23926bd2011-12-15 10:25:47 +00006540 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006541 S.getLangOpts(),
6542 S.Context.getTargetInfo(),
6543 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006544 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006545 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00006546 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6547 numDataArgs, Str, HasVAListArg, Args, format_idx,
6548 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006549
Hans Wennborg23926bd2011-12-15 10:25:47 +00006550 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006551 S.getLangOpts(),
6552 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006553 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006554 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006555}
6556
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006557bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6558 // Str - The format string. NOTE: this is NOT null-terminated!
6559 StringRef StrRef = FExpr->getString();
6560 const char *Str = StrRef.data();
6561 // Account for cases where the string literal is truncated in a declaration.
6562 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6563 assert(T && "String literal not of constant array type!");
6564 size_t TypeSize = T->getSize().getZExtValue();
6565 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6566 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6567 getLangOpts(),
6568 Context.getTargetInfo());
6569}
6570
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006571//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6572
6573// Returns the related absolute value function that is larger, of 0 if one
6574// does not exist.
6575static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6576 switch (AbsFunction) {
6577 default:
6578 return 0;
6579
6580 case Builtin::BI__builtin_abs:
6581 return Builtin::BI__builtin_labs;
6582 case Builtin::BI__builtin_labs:
6583 return Builtin::BI__builtin_llabs;
6584 case Builtin::BI__builtin_llabs:
6585 return 0;
6586
6587 case Builtin::BI__builtin_fabsf:
6588 return Builtin::BI__builtin_fabs;
6589 case Builtin::BI__builtin_fabs:
6590 return Builtin::BI__builtin_fabsl;
6591 case Builtin::BI__builtin_fabsl:
6592 return 0;
6593
6594 case Builtin::BI__builtin_cabsf:
6595 return Builtin::BI__builtin_cabs;
6596 case Builtin::BI__builtin_cabs:
6597 return Builtin::BI__builtin_cabsl;
6598 case Builtin::BI__builtin_cabsl:
6599 return 0;
6600
6601 case Builtin::BIabs:
6602 return Builtin::BIlabs;
6603 case Builtin::BIlabs:
6604 return Builtin::BIllabs;
6605 case Builtin::BIllabs:
6606 return 0;
6607
6608 case Builtin::BIfabsf:
6609 return Builtin::BIfabs;
6610 case Builtin::BIfabs:
6611 return Builtin::BIfabsl;
6612 case Builtin::BIfabsl:
6613 return 0;
6614
6615 case Builtin::BIcabsf:
6616 return Builtin::BIcabs;
6617 case Builtin::BIcabs:
6618 return Builtin::BIcabsl;
6619 case Builtin::BIcabsl:
6620 return 0;
6621 }
6622}
6623
6624// Returns the argument type of the absolute value function.
6625static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6626 unsigned AbsType) {
6627 if (AbsType == 0)
6628 return QualType();
6629
6630 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6631 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6632 if (Error != ASTContext::GE_None)
6633 return QualType();
6634
6635 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6636 if (!FT)
6637 return QualType();
6638
6639 if (FT->getNumParams() != 1)
6640 return QualType();
6641
6642 return FT->getParamType(0);
6643}
6644
6645// Returns the best absolute value function, or zero, based on type and
6646// current absolute value function.
6647static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6648 unsigned AbsFunctionKind) {
6649 unsigned BestKind = 0;
6650 uint64_t ArgSize = Context.getTypeSize(ArgType);
6651 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6652 Kind = getLargerAbsoluteValueFunction(Kind)) {
6653 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6654 if (Context.getTypeSize(ParamType) >= ArgSize) {
6655 if (BestKind == 0)
6656 BestKind = Kind;
6657 else if (Context.hasSameType(ParamType, ArgType)) {
6658 BestKind = Kind;
6659 break;
6660 }
6661 }
6662 }
6663 return BestKind;
6664}
6665
6666enum AbsoluteValueKind {
6667 AVK_Integer,
6668 AVK_Floating,
6669 AVK_Complex
6670};
6671
6672static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6673 if (T->isIntegralOrEnumerationType())
6674 return AVK_Integer;
6675 if (T->isRealFloatingType())
6676 return AVK_Floating;
6677 if (T->isAnyComplexType())
6678 return AVK_Complex;
6679
6680 llvm_unreachable("Type not integer, floating, or complex");
6681}
6682
6683// Changes the absolute value function to a different type. Preserves whether
6684// the function is a builtin.
6685static unsigned changeAbsFunction(unsigned AbsKind,
6686 AbsoluteValueKind ValueKind) {
6687 switch (ValueKind) {
6688 case AVK_Integer:
6689 switch (AbsKind) {
6690 default:
6691 return 0;
6692 case Builtin::BI__builtin_fabsf:
6693 case Builtin::BI__builtin_fabs:
6694 case Builtin::BI__builtin_fabsl:
6695 case Builtin::BI__builtin_cabsf:
6696 case Builtin::BI__builtin_cabs:
6697 case Builtin::BI__builtin_cabsl:
6698 return Builtin::BI__builtin_abs;
6699 case Builtin::BIfabsf:
6700 case Builtin::BIfabs:
6701 case Builtin::BIfabsl:
6702 case Builtin::BIcabsf:
6703 case Builtin::BIcabs:
6704 case Builtin::BIcabsl:
6705 return Builtin::BIabs;
6706 }
6707 case AVK_Floating:
6708 switch (AbsKind) {
6709 default:
6710 return 0;
6711 case Builtin::BI__builtin_abs:
6712 case Builtin::BI__builtin_labs:
6713 case Builtin::BI__builtin_llabs:
6714 case Builtin::BI__builtin_cabsf:
6715 case Builtin::BI__builtin_cabs:
6716 case Builtin::BI__builtin_cabsl:
6717 return Builtin::BI__builtin_fabsf;
6718 case Builtin::BIabs:
6719 case Builtin::BIlabs:
6720 case Builtin::BIllabs:
6721 case Builtin::BIcabsf:
6722 case Builtin::BIcabs:
6723 case Builtin::BIcabsl:
6724 return Builtin::BIfabsf;
6725 }
6726 case AVK_Complex:
6727 switch (AbsKind) {
6728 default:
6729 return 0;
6730 case Builtin::BI__builtin_abs:
6731 case Builtin::BI__builtin_labs:
6732 case Builtin::BI__builtin_llabs:
6733 case Builtin::BI__builtin_fabsf:
6734 case Builtin::BI__builtin_fabs:
6735 case Builtin::BI__builtin_fabsl:
6736 return Builtin::BI__builtin_cabsf;
6737 case Builtin::BIabs:
6738 case Builtin::BIlabs:
6739 case Builtin::BIllabs:
6740 case Builtin::BIfabsf:
6741 case Builtin::BIfabs:
6742 case Builtin::BIfabsl:
6743 return Builtin::BIcabsf;
6744 }
6745 }
6746 llvm_unreachable("Unable to convert function");
6747}
6748
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006749static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006750 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6751 if (!FnInfo)
6752 return 0;
6753
6754 switch (FDecl->getBuiltinID()) {
6755 default:
6756 return 0;
6757 case Builtin::BI__builtin_abs:
6758 case Builtin::BI__builtin_fabs:
6759 case Builtin::BI__builtin_fabsf:
6760 case Builtin::BI__builtin_fabsl:
6761 case Builtin::BI__builtin_labs:
6762 case Builtin::BI__builtin_llabs:
6763 case Builtin::BI__builtin_cabs:
6764 case Builtin::BI__builtin_cabsf:
6765 case Builtin::BI__builtin_cabsl:
6766 case Builtin::BIabs:
6767 case Builtin::BIlabs:
6768 case Builtin::BIllabs:
6769 case Builtin::BIfabs:
6770 case Builtin::BIfabsf:
6771 case Builtin::BIfabsl:
6772 case Builtin::BIcabs:
6773 case Builtin::BIcabsf:
6774 case Builtin::BIcabsl:
6775 return FDecl->getBuiltinID();
6776 }
6777 llvm_unreachable("Unknown Builtin type");
6778}
6779
6780// If the replacement is valid, emit a note with replacement function.
6781// Additionally, suggest including the proper header if not already included.
6782static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00006783 unsigned AbsKind, QualType ArgType) {
6784 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006785 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00006786 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006787 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6788 FunctionName = "std::abs";
6789 if (ArgType->isIntegralOrEnumerationType()) {
6790 HeaderName = "cstdlib";
6791 } else if (ArgType->isRealFloatingType()) {
6792 HeaderName = "cmath";
6793 } else {
6794 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006795 }
Richard Trieubeffb832014-04-15 23:47:53 +00006796
6797 // Lookup all std::abs
6798 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00006799 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00006800 R.suppressDiagnostics();
6801 S.LookupQualifiedName(R, Std);
6802
6803 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006804 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006805 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6806 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6807 } else {
6808 FDecl = dyn_cast<FunctionDecl>(I);
6809 }
6810 if (!FDecl)
6811 continue;
6812
6813 // Found std::abs(), check that they are the right ones.
6814 if (FDecl->getNumParams() != 1)
6815 continue;
6816
6817 // Check that the parameter type can handle the argument.
6818 QualType ParamType = FDecl->getParamDecl(0)->getType();
6819 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6820 S.Context.getTypeSize(ArgType) <=
6821 S.Context.getTypeSize(ParamType)) {
6822 // Found a function, don't need the header hint.
6823 EmitHeaderHint = false;
6824 break;
6825 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006826 }
Richard Trieubeffb832014-04-15 23:47:53 +00006827 }
6828 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00006829 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00006830 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6831
6832 if (HeaderName) {
6833 DeclarationName DN(&S.Context.Idents.get(FunctionName));
6834 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6835 R.suppressDiagnostics();
6836 S.LookupName(R, S.getCurScope());
6837
6838 if (R.isSingleResult()) {
6839 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6840 if (FD && FD->getBuiltinID() == AbsKind) {
6841 EmitHeaderHint = false;
6842 } else {
6843 return;
6844 }
6845 } else if (!R.empty()) {
6846 return;
6847 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006848 }
6849 }
6850
6851 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00006852 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006853
Richard Trieubeffb832014-04-15 23:47:53 +00006854 if (!HeaderName)
6855 return;
6856
6857 if (!EmitHeaderHint)
6858 return;
6859
Alp Toker5d96e0a2014-07-11 20:53:51 +00006860 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6861 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00006862}
6863
Richard Trieua7f30b12016-12-06 01:42:28 +00006864template <std::size_t StrLen>
6865static bool IsStdFunction(const FunctionDecl *FDecl,
6866 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00006867 if (!FDecl)
6868 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00006869 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00006870 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00006871 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00006872 return false;
6873
6874 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006875}
6876
6877// Warn when using the wrong abs() function.
6878void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00006879 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006880 if (Call->getNumArgs() != 1)
6881 return;
6882
6883 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00006884 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00006885 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006886 return;
6887
6888 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6889 QualType ParamType = Call->getArg(0)->getType();
6890
Alp Toker5d96e0a2014-07-11 20:53:51 +00006891 // Unsigned types cannot be negative. Suggest removing the absolute value
6892 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006893 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00006894 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00006895 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006896 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6897 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00006898 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006899 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6900 return;
6901 }
6902
David Majnemer7f77eb92015-11-15 03:04:34 +00006903 // Taking the absolute value of a pointer is very suspicious, they probably
6904 // wanted to index into an array, dereference a pointer, call a function, etc.
6905 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6906 unsigned DiagType = 0;
6907 if (ArgType->isFunctionType())
6908 DiagType = 1;
6909 else if (ArgType->isArrayType())
6910 DiagType = 2;
6911
6912 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6913 return;
6914 }
6915
Richard Trieubeffb832014-04-15 23:47:53 +00006916 // std::abs has overloads which prevent most of the absolute value problems
6917 // from occurring.
6918 if (IsStdAbs)
6919 return;
6920
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006921 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6922 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6923
6924 // The argument and parameter are the same kind. Check if they are the right
6925 // size.
6926 if (ArgValueKind == ParamValueKind) {
6927 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6928 return;
6929
6930 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6931 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6932 << FDecl << ArgType << ParamType;
6933
6934 if (NewAbsKind == 0)
6935 return;
6936
6937 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006938 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006939 return;
6940 }
6941
6942 // ArgValueKind != ParamValueKind
6943 // The wrong type of absolute value function was used. Attempt to find the
6944 // proper one.
6945 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6946 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6947 if (NewAbsKind == 0)
6948 return;
6949
6950 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6951 << FDecl << ParamValueKind << ArgValueKind;
6952
6953 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006954 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006955}
6956
Richard Trieu67c00712016-12-05 23:41:46 +00006957//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00006958void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
6959 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00006960 if (!Call || !FDecl) return;
6961
6962 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00006963 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00006964 if (Call->getExprLoc().isMacroID()) return;
6965
6966 // Only care about the one template argument, two function parameter std::max
6967 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00006968 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00006969 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
6970 if (!ArgList) return;
6971 if (ArgList->size() != 1) return;
6972
6973 // Check that template type argument is unsigned integer.
6974 const auto& TA = ArgList->get(0);
6975 if (TA.getKind() != TemplateArgument::Type) return;
6976 QualType ArgType = TA.getAsType();
6977 if (!ArgType->isUnsignedIntegerType()) return;
6978
6979 // See if either argument is a literal zero.
6980 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
6981 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
6982 if (!MTE) return false;
6983 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
6984 if (!Num) return false;
6985 if (Num->getValue() != 0) return false;
6986 return true;
6987 };
6988
6989 const Expr *FirstArg = Call->getArg(0);
6990 const Expr *SecondArg = Call->getArg(1);
6991 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
6992 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
6993
6994 // Only warn when exactly one argument is zero.
6995 if (IsFirstArgZero == IsSecondArgZero) return;
6996
6997 SourceRange FirstRange = FirstArg->getSourceRange();
6998 SourceRange SecondRange = SecondArg->getSourceRange();
6999
7000 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7001
7002 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7003 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7004
7005 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7006 SourceRange RemovalRange;
7007 if (IsFirstArgZero) {
7008 RemovalRange = SourceRange(FirstRange.getBegin(),
7009 SecondRange.getBegin().getLocWithOffset(-1));
7010 } else {
7011 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7012 SecondRange.getEnd());
7013 }
7014
7015 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7016 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7017 << FixItHint::CreateRemoval(RemovalRange);
7018}
7019
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007020//===--- CHECK: Standard memory functions ---------------------------------===//
7021
Nico Weber0e6daef2013-12-26 23:38:39 +00007022/// \brief Takes the expression passed to the size_t parameter of functions
7023/// such as memcmp, strncat, etc and warns if it's a comparison.
7024///
7025/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7026static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7027 IdentifierInfo *FnName,
7028 SourceLocation FnLoc,
7029 SourceLocation RParenLoc) {
7030 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7031 if (!Size)
7032 return false;
7033
7034 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
7035 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
7036 return false;
7037
Nico Weber0e6daef2013-12-26 23:38:39 +00007038 SourceRange SizeRange = Size->getSourceRange();
7039 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7040 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00007041 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007042 << FnName << FixItHint::CreateInsertion(
7043 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00007044 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00007045 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00007046 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00007047 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7048 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00007049
7050 return true;
7051}
7052
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007053/// \brief Determine whether the given type is or contains a dynamic class type
7054/// (e.g., whether it has a vtable).
7055static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7056 bool &IsContained) {
7057 // Look through array types while ignoring qualifiers.
7058 const Type *Ty = T->getBaseElementTypeUnsafe();
7059 IsContained = false;
7060
7061 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7062 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00007063 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007064 return nullptr;
7065
7066 if (RD->isDynamicClass())
7067 return RD;
7068
7069 // Check all the fields. If any bases were dynamic, the class is dynamic.
7070 // It's impossible for a class to transitively contain itself by value, so
7071 // infinite recursion is impossible.
7072 for (auto *FD : RD->fields()) {
7073 bool SubContained;
7074 if (const CXXRecordDecl *ContainedRD =
7075 getContainedDynamicClass(FD->getType(), SubContained)) {
7076 IsContained = true;
7077 return ContainedRD;
7078 }
7079 }
7080
7081 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007082}
7083
Chandler Carruth889ed862011-06-21 23:04:20 +00007084/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007085/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007086static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007087 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007088 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7089 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
7090 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007091
Craig Topperc3ec1492014-05-26 06:22:03 +00007092 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007093}
7094
Chandler Carruth889ed862011-06-21 23:04:20 +00007095/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007096static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007097 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7098 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7099 if (SizeOf->getKind() == clang::UETT_SizeOf)
7100 return SizeOf->getTypeOfArgument();
7101
7102 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007103}
7104
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007105/// \brief Check for dangerous or invalid arguments to memset().
7106///
Chandler Carruthac687262011-06-03 06:23:57 +00007107/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007108/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7109/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007110///
7111/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007112void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007113 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007114 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007115 assert(BId != 0);
7116
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007117 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007118 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007119 unsigned ExpectedNumArgs =
7120 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007121 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007122 return;
7123
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007124 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007125 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007126 unsigned LenArg =
7127 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007128 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007129
Nico Weber0e6daef2013-12-26 23:38:39 +00007130 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7131 Call->getLocStart(), Call->getRParenLoc()))
7132 return;
7133
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007134 // We have special checking when the length is a sizeof expression.
7135 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7136 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7137 llvm::FoldingSetNodeID SizeOfArgID;
7138
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007139 // Although widely used, 'bzero' is not a standard function. Be more strict
7140 // with the argument types before allowing diagnostics and only allow the
7141 // form bzero(ptr, sizeof(...)).
7142 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7143 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7144 return;
7145
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007146 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7147 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007148 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007149
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007150 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007151 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007152 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007153 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007154
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007155 // Never warn about void type pointers. This can be used to suppress
7156 // false positives.
7157 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007158 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007159
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007160 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7161 // actually comparing the expressions for equality. Because computing the
7162 // expression IDs can be expensive, we only do this if the diagnostic is
7163 // enabled.
7164 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007165 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7166 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007167 // We only compute IDs for expressions if the warning is enabled, and
7168 // cache the sizeof arg's ID.
7169 if (SizeOfArgID == llvm::FoldingSetNodeID())
7170 SizeOfArg->Profile(SizeOfArgID, Context, true);
7171 llvm::FoldingSetNodeID DestID;
7172 Dest->Profile(DestID, Context, true);
7173 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007174 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7175 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007176 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007177 StringRef ReadableName = FnName->getName();
7178
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007179 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007180 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007181 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007182 if (!PointeeTy->isIncompleteType() &&
7183 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007184 ActionIdx = 2; // If the pointee's size is sizeof(char),
7185 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007186
7187 // If the function is defined as a builtin macro, do not show macro
7188 // expansion.
7189 SourceLocation SL = SizeOfArg->getExprLoc();
7190 SourceRange DSR = Dest->getSourceRange();
7191 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007192 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007193
7194 if (SM.isMacroArgExpansion(SL)) {
7195 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7196 SL = SM.getSpellingLoc(SL);
7197 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7198 SM.getSpellingLoc(DSR.getEnd()));
7199 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7200 SM.getSpellingLoc(SSR.getEnd()));
7201 }
7202
Anna Zaksd08d9152012-05-30 23:14:52 +00007203 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007204 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007205 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007206 << PointeeTy
7207 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007208 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007209 << SSR);
7210 DiagRuntimeBehavior(SL, SizeOfArg,
7211 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7212 << ActionIdx
7213 << SSR);
7214
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007215 break;
7216 }
7217 }
7218
7219 // Also check for cases where the sizeof argument is the exact same
7220 // type as the memory argument, and where it points to a user-defined
7221 // record type.
7222 if (SizeOfArgTy != QualType()) {
7223 if (PointeeTy->isRecordType() &&
7224 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7225 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7226 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7227 << FnName << SizeOfArgTy << ArgIdx
7228 << PointeeTy << Dest->getSourceRange()
7229 << LenExpr->getSourceRange());
7230 break;
7231 }
Nico Weberc5e73862011-06-14 16:14:58 +00007232 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00007233 } else if (DestTy->isArrayType()) {
7234 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00007235 }
Nico Weberc5e73862011-06-14 16:14:58 +00007236
Nico Weberc44b35e2015-03-21 17:37:46 +00007237 if (PointeeTy == QualType())
7238 continue;
Anna Zaks22122702012-01-17 00:37:07 +00007239
Nico Weberc44b35e2015-03-21 17:37:46 +00007240 // Always complain about dynamic classes.
7241 bool IsContained;
7242 if (const CXXRecordDecl *ContainedRD =
7243 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00007244
Nico Weberc44b35e2015-03-21 17:37:46 +00007245 unsigned OperationType = 0;
7246 // "overwritten" if we're warning about the destination for any call
7247 // but memcmp; otherwise a verb appropriate to the call.
7248 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7249 if (BId == Builtin::BImemcpy)
7250 OperationType = 1;
7251 else if(BId == Builtin::BImemmove)
7252 OperationType = 2;
7253 else if (BId == Builtin::BImemcmp)
7254 OperationType = 3;
7255 }
7256
John McCall31168b02011-06-15 23:02:42 +00007257 DiagRuntimeBehavior(
7258 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007259 PDiag(diag::warn_dyn_class_memaccess)
7260 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7261 << FnName << IsContained << ContainedRD << OperationType
7262 << Call->getCallee()->getSourceRange());
7263 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7264 BId != Builtin::BImemset)
7265 DiagRuntimeBehavior(
7266 Dest->getExprLoc(), Dest,
7267 PDiag(diag::warn_arc_object_memaccess)
7268 << ArgIdx << FnName << PointeeTy
7269 << Call->getCallee()->getSourceRange());
7270 else
7271 continue;
7272
7273 DiagRuntimeBehavior(
7274 Dest->getExprLoc(), Dest,
7275 PDiag(diag::note_bad_memaccess_silence)
7276 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7277 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007278 }
7279}
7280
Ted Kremenek6865f772011-08-18 20:55:45 +00007281// A little helper routine: ignore addition and subtraction of integer literals.
7282// This intentionally does not ignore all integer constant expressions because
7283// we don't want to remove sizeof().
7284static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7285 Ex = Ex->IgnoreParenCasts();
7286
7287 for (;;) {
7288 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7289 if (!BO || !BO->isAdditiveOp())
7290 break;
7291
7292 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7293 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7294
7295 if (isa<IntegerLiteral>(RHS))
7296 Ex = LHS;
7297 else if (isa<IntegerLiteral>(LHS))
7298 Ex = RHS;
7299 else
7300 break;
7301 }
7302
7303 return Ex;
7304}
7305
Anna Zaks13b08572012-08-08 21:42:23 +00007306static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7307 ASTContext &Context) {
7308 // Only handle constant-sized or VLAs, but not flexible members.
7309 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7310 // Only issue the FIXIT for arrays of size > 1.
7311 if (CAT->getSize().getSExtValue() <= 1)
7312 return false;
7313 } else if (!Ty->isVariableArrayType()) {
7314 return false;
7315 }
7316 return true;
7317}
7318
Ted Kremenek6865f772011-08-18 20:55:45 +00007319// Warn if the user has made the 'size' argument to strlcpy or strlcat
7320// be the size of the source, instead of the destination.
7321void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7322 IdentifierInfo *FnName) {
7323
7324 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007325 unsigned NumArgs = Call->getNumArgs();
7326 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007327 return;
7328
7329 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7330 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007331 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007332
7333 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7334 Call->getLocStart(), Call->getRParenLoc()))
7335 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00007336
7337 // Look for 'strlcpy(dst, x, sizeof(x))'
7338 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7339 CompareWithSrc = Ex;
7340 else {
7341 // Look for 'strlcpy(dst, x, strlen(x))'
7342 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00007343 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7344 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00007345 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7346 }
7347 }
7348
7349 if (!CompareWithSrc)
7350 return;
7351
7352 // Determine if the argument to sizeof/strlen is equal to the source
7353 // argument. In principle there's all kinds of things you could do
7354 // here, for instance creating an == expression and evaluating it with
7355 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7356 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7357 if (!SrcArgDRE)
7358 return;
7359
7360 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7361 if (!CompareWithSrcDRE ||
7362 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7363 return;
7364
7365 const Expr *OriginalSizeArg = Call->getArg(2);
7366 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7367 << OriginalSizeArg->getSourceRange() << FnName;
7368
7369 // Output a FIXIT hint if the destination is an array (rather than a
7370 // pointer to an array). This could be enhanced to handle some
7371 // pointers if we know the actual size, like if DstArg is 'array+2'
7372 // we could say 'sizeof(array)-2'.
7373 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00007374 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00007375 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007376
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007377 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007378 llvm::raw_svector_ostream OS(sizeString);
7379 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007380 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00007381 OS << ")";
7382
7383 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7384 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7385 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00007386}
7387
Anna Zaks314cd092012-02-01 19:08:57 +00007388/// Check if two expressions refer to the same declaration.
7389static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7390 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7391 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7392 return D1->getDecl() == D2->getDecl();
7393 return false;
7394}
7395
7396static const Expr *getStrlenExprArg(const Expr *E) {
7397 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7398 const FunctionDecl *FD = CE->getDirectCallee();
7399 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00007400 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007401 return CE->getArg(0)->IgnoreParenCasts();
7402 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007403 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007404}
7405
7406// Warn on anti-patterns as the 'size' argument to strncat.
7407// The correct size argument should look like following:
7408// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7409void Sema::CheckStrncatArguments(const CallExpr *CE,
7410 IdentifierInfo *FnName) {
7411 // Don't crash if the user has the wrong number of arguments.
7412 if (CE->getNumArgs() < 3)
7413 return;
7414 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7415 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7416 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7417
Nico Weber0e6daef2013-12-26 23:38:39 +00007418 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7419 CE->getRParenLoc()))
7420 return;
7421
Anna Zaks314cd092012-02-01 19:08:57 +00007422 // Identify common expressions, which are wrongly used as the size argument
7423 // to strncat and may lead to buffer overflows.
7424 unsigned PatternType = 0;
7425 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7426 // - sizeof(dst)
7427 if (referToTheSameDecl(SizeOfArg, DstArg))
7428 PatternType = 1;
7429 // - sizeof(src)
7430 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7431 PatternType = 2;
7432 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7433 if (BE->getOpcode() == BO_Sub) {
7434 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7435 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7436 // - sizeof(dst) - strlen(dst)
7437 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7438 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7439 PatternType = 1;
7440 // - sizeof(src) - (anything)
7441 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7442 PatternType = 2;
7443 }
7444 }
7445
7446 if (PatternType == 0)
7447 return;
7448
Anna Zaks5069aa32012-02-03 01:27:37 +00007449 // Generate the diagnostic.
7450 SourceLocation SL = LenArg->getLocStart();
7451 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007452 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00007453
7454 // If the function is defined as a builtin macro, do not show macro expansion.
7455 if (SM.isMacroArgExpansion(SL)) {
7456 SL = SM.getSpellingLoc(SL);
7457 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7458 SM.getSpellingLoc(SR.getEnd()));
7459 }
7460
Anna Zaks13b08572012-08-08 21:42:23 +00007461 // Check if the destination is an array (rather than a pointer to an array).
7462 QualType DstTy = DstArg->getType();
7463 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7464 Context);
7465 if (!isKnownSizeArray) {
7466 if (PatternType == 1)
7467 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7468 else
7469 Diag(SL, diag::warn_strncat_src_size) << SR;
7470 return;
7471 }
7472
Anna Zaks314cd092012-02-01 19:08:57 +00007473 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00007474 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007475 else
Anna Zaks5069aa32012-02-03 01:27:37 +00007476 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007477
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007478 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00007479 llvm::raw_svector_ostream OS(sizeString);
7480 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007481 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007482 OS << ") - ";
7483 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007484 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007485 OS << ") - 1";
7486
Anna Zaks5069aa32012-02-03 01:27:37 +00007487 Diag(SL, diag::note_strncat_wrong_size)
7488 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00007489}
7490
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007491//===--- CHECK: Return Address of Stack Variable --------------------------===//
7492
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007493static const Expr *EvalVal(const Expr *E,
7494 SmallVectorImpl<const DeclRefExpr *> &refVars,
7495 const Decl *ParentDecl);
7496static const Expr *EvalAddr(const Expr *E,
7497 SmallVectorImpl<const DeclRefExpr *> &refVars,
7498 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007499
7500/// CheckReturnStackAddr - Check if a return statement returns the address
7501/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007502static void
7503CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7504 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00007505
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007506 const Expr *stackE = nullptr;
7507 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007508
7509 // Perform checking for returned stack addresses, local blocks,
7510 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00007511 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007512 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007513 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00007514 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007515 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007516 }
7517
Craig Topperc3ec1492014-05-26 06:22:03 +00007518 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007519 return; // Nothing suspicious was found.
7520
Simon Pilgrim750bde62017-03-31 11:00:53 +00007521 // Parameters are initialized in the calling scope, so taking the address
Richard Trieu81b6c562016-08-05 23:24:47 +00007522 // of a parameter reference doesn't need a warning.
7523 for (auto *DRE : refVars)
7524 if (isa<ParmVarDecl>(DRE->getDecl()))
7525 return;
7526
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007527 SourceLocation diagLoc;
7528 SourceRange diagRange;
7529 if (refVars.empty()) {
7530 diagLoc = stackE->getLocStart();
7531 diagRange = stackE->getSourceRange();
7532 } else {
7533 // We followed through a reference variable. 'stackE' contains the
7534 // problematic expression but we will warn at the return statement pointing
7535 // at the reference variable. We will later display the "trail" of
7536 // reference variables using notes.
7537 diagLoc = refVars[0]->getLocStart();
7538 diagRange = refVars[0]->getSourceRange();
7539 }
7540
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007541 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7542 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00007543 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007544 << DR->getDecl()->getDeclName() << diagRange;
7545 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007546 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007547 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007548 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007549 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00007550 // If there is an LValue->RValue conversion, then the value of the
7551 // reference type is used, not the reference.
7552 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7553 if (ICE->getCastKind() == CK_LValueToRValue) {
7554 return;
7555 }
7556 }
Craig Topperda7b27f2015-11-17 05:40:09 +00007557 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7558 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007559 }
7560
7561 // Display the "trail" of reference variables that we followed until we
7562 // found the problematic expression using notes.
7563 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007564 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007565 // If this var binds to another reference var, show the range of the next
7566 // var, otherwise the var binds to the problematic expression, in which case
7567 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007568 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7569 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007570 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7571 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007572 }
7573}
7574
7575/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7576/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007577/// to a location on the stack, a local block, an address of a label, or a
7578/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007579/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007580/// encounter a subexpression that (1) clearly does not lead to one of the
7581/// above problematic expressions (2) is something we cannot determine leads to
7582/// a problematic expression based on such local checking.
7583///
7584/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7585/// the expression that they point to. Such variables are added to the
7586/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007587///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007588/// EvalAddr processes expressions that are pointers that are used as
7589/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007590/// At the base case of the recursion is a check for the above problematic
7591/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007592///
7593/// This implementation handles:
7594///
7595/// * pointer-to-pointer casts
7596/// * implicit conversions from array references to pointers
7597/// * taking the address of fields
7598/// * arbitrary interplay between "&" and "*" operators
7599/// * pointer arithmetic from an address of a stack variable
7600/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007601static const Expr *EvalAddr(const Expr *E,
7602 SmallVectorImpl<const DeclRefExpr *> &refVars,
7603 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007604 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00007605 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007606
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007607 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00007608 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00007609 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007610 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00007611 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00007612
Peter Collingbourne91147592011-04-15 00:35:48 +00007613 E = E->IgnoreParens();
7614
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007615 // Our "symbolic interpreter" is just a dispatch off the currently
7616 // viewed AST node. We then recursively traverse the AST by calling
7617 // EvalAddr and EvalVal appropriately.
7618 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007619 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007620 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007621
Richard Smith40f08eb2014-01-30 22:05:38 +00007622 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00007623 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00007624 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00007625
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007626 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007627 // If this is a reference variable, follow through to the expression that
7628 // it points to.
7629 if (V->hasLocalStorage() &&
7630 V->getType()->isReferenceType() && V->hasInit()) {
7631 // Add the reference variable to the "trail".
7632 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007633 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007634 }
7635
Craig Topperc3ec1492014-05-26 06:22:03 +00007636 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007637 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007638
Chris Lattner934edb22007-12-28 05:31:15 +00007639 case Stmt::UnaryOperatorClass: {
7640 // The only unary operator that make sense to handle here
7641 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007642 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007643
John McCalle3027922010-08-25 11:45:40 +00007644 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007645 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007646 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007647 }
Mike Stump11289f42009-09-09 15:08:12 +00007648
Chris Lattner934edb22007-12-28 05:31:15 +00007649 case Stmt::BinaryOperatorClass: {
7650 // Handle pointer arithmetic. All other binary operators are not valid
7651 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007652 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00007653 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00007654
John McCalle3027922010-08-25 11:45:40 +00007655 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00007656 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007657
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007658 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00007659
7660 // Determine which argument is the real pointer base. It could be
7661 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007662 if (!Base->getType()->isPointerType())
7663 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00007664
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007665 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007666 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007667 }
Steve Naroff2752a172008-09-10 19:17:48 +00007668
Chris Lattner934edb22007-12-28 05:31:15 +00007669 // For conditional operators we need to see if either the LHS or RHS are
7670 // valid DeclRefExpr*s. If one of them is valid, we return it.
7671 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007672 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007673
Chris Lattner934edb22007-12-28 05:31:15 +00007674 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007675 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007676 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007677 // In C++, we can have a throw-expression, which has 'void' type.
7678 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007679 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007680 return LHS;
7681 }
Chris Lattner934edb22007-12-28 05:31:15 +00007682
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007683 // In C++, we can have a throw-expression, which has 'void' type.
7684 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00007685 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007686
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007687 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007688 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007689
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007690 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00007691 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007692 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00007693 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007694
7695 case Stmt::AddrLabelExprClass:
7696 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00007697
John McCall28fc7092011-11-10 05:35:25 +00007698 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007699 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7700 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00007701
Ted Kremenekc3b4c522008-08-07 00:49:01 +00007702 // For casts, we need to handle conversions from arrays to
7703 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00007704 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00007705 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007706 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00007707 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00007708 case Stmt::CXXStaticCastExprClass:
7709 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00007710 case Stmt::CXXConstCastExprClass:
7711 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007712 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00007713 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00007714 case CK_LValueToRValue:
7715 case CK_NoOp:
7716 case CK_BaseToDerived:
7717 case CK_DerivedToBase:
7718 case CK_UncheckedDerivedToBase:
7719 case CK_Dynamic:
7720 case CK_CPointerToObjCPointerCast:
7721 case CK_BlockPointerToObjCPointerCast:
7722 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007723 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007724
7725 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007726 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007727
Richard Trieudadefde2014-07-02 04:39:38 +00007728 case CK_BitCast:
7729 if (SubExpr->getType()->isAnyPointerType() ||
7730 SubExpr->getType()->isBlockPointerType() ||
7731 SubExpr->getType()->isObjCQualifiedIdType())
7732 return EvalAddr(SubExpr, refVars, ParentDecl);
7733 else
7734 return nullptr;
7735
Eli Friedman8195ad72012-02-23 23:04:32 +00007736 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007737 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00007738 }
Chris Lattner934edb22007-12-28 05:31:15 +00007739 }
Mike Stump11289f42009-09-09 15:08:12 +00007740
Douglas Gregorfe314812011-06-21 17:03:29 +00007741 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007742 if (const Expr *Result =
7743 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7744 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00007745 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00007746 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007747
Chris Lattner934edb22007-12-28 05:31:15 +00007748 // Everything else: we simply don't reason about them.
7749 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007750 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00007751 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007752}
Mike Stump11289f42009-09-09 15:08:12 +00007753
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007754/// EvalVal - This function is complements EvalAddr in the mutual recursion.
7755/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007756static const Expr *EvalVal(const Expr *E,
7757 SmallVectorImpl<const DeclRefExpr *> &refVars,
7758 const Decl *ParentDecl) {
7759 do {
7760 // We should only be called for evaluating non-pointer expressions, or
7761 // expressions with a pointer type that are not used as references but
7762 // instead
7763 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00007764
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007765 // Our "symbolic interpreter" is just a dispatch off the currently
7766 // viewed AST node. We then recursively traverse the AST by calling
7767 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00007768
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007769 E = E->IgnoreParens();
7770 switch (E->getStmtClass()) {
7771 case Stmt::ImplicitCastExprClass: {
7772 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7773 if (IE->getValueKind() == VK_LValue) {
7774 E = IE->getSubExpr();
7775 continue;
7776 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007777 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007778 }
Richard Smith40f08eb2014-01-30 22:05:38 +00007779
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007780 case Stmt::ExprWithCleanupsClass:
7781 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7782 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007783
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007784 case Stmt::DeclRefExprClass: {
7785 // When we hit a DeclRefExpr we are looking at code that refers to a
7786 // variable's name. If it's not a reference variable we check if it has
7787 // local storage within the function, and if so, return the expression.
7788 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7789
7790 // If we leave the immediate function, the lifetime isn't about to end.
7791 if (DR->refersToEnclosingVariableOrCapture())
7792 return nullptr;
7793
7794 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7795 // Check if it refers to itself, e.g. "int& i = i;".
7796 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007797 return DR;
7798
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007799 if (V->hasLocalStorage()) {
7800 if (!V->getType()->isReferenceType())
7801 return DR;
7802
7803 // Reference variable, follow through to the expression that
7804 // it points to.
7805 if (V->hasInit()) {
7806 // Add the reference variable to the "trail".
7807 refVars.push_back(DR);
7808 return EvalVal(V->getInit(), refVars, V);
7809 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007810 }
7811 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007812
7813 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007814 }
Mike Stump11289f42009-09-09 15:08:12 +00007815
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007816 case Stmt::UnaryOperatorClass: {
7817 // The only unary operator that make sense to handle here
7818 // is Deref. All others don't resolve to a "name." This includes
7819 // handling all sorts of rvalues passed to a unary operator.
7820 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007821
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007822 if (U->getOpcode() == UO_Deref)
7823 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007824
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007825 return nullptr;
7826 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007827
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007828 case Stmt::ArraySubscriptExprClass: {
7829 // Array subscripts are potential references to data on the stack. We
7830 // retrieve the DeclRefExpr* for the array variable if it indeed
7831 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00007832 const auto *ASE = cast<ArraySubscriptExpr>(E);
7833 if (ASE->isTypeDependent())
7834 return nullptr;
7835 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007836 }
Mike Stump11289f42009-09-09 15:08:12 +00007837
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007838 case Stmt::OMPArraySectionExprClass: {
7839 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7840 ParentDecl);
7841 }
Mike Stump11289f42009-09-09 15:08:12 +00007842
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007843 case Stmt::ConditionalOperatorClass: {
7844 // For conditional operators we need to see if either the LHS or RHS are
7845 // non-NULL Expr's. If one is non-NULL, we return it.
7846 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007847
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007848 // Handle the GNU extension for missing LHS.
7849 if (const Expr *LHSExpr = C->getLHS()) {
7850 // In C++, we can have a throw-expression, which has 'void' type.
7851 if (!LHSExpr->getType()->isVoidType())
7852 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7853 return LHS;
7854 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007855
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007856 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007857 if (C->getRHS()->getType()->isVoidType())
7858 return nullptr;
7859
7860 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007861 }
7862
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007863 // Accesses to members are potential references to data on the stack.
7864 case Stmt::MemberExprClass: {
7865 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00007866
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007867 // Check for indirect access. We only want direct field accesses.
7868 if (M->isArrow())
7869 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007870
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007871 // Check whether the member type is itself a reference, in which case
7872 // we're not going to refer to the member, but to what the member refers
7873 // to.
7874 if (M->getMemberDecl()->getType()->isReferenceType())
7875 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007876
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007877 return EvalVal(M->getBase(), refVars, ParentDecl);
7878 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00007879
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007880 case Stmt::MaterializeTemporaryExprClass:
7881 if (const Expr *Result =
7882 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7883 refVars, ParentDecl))
7884 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007885 return E;
7886
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007887 default:
7888 // Check that we don't return or take the address of a reference to a
7889 // temporary. This is only useful in C++.
7890 if (!E->isTypeDependent() && E->isRValue())
7891 return E;
7892
7893 // Everything else: we simply don't reason about them.
7894 return nullptr;
7895 }
7896 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007897}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007898
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007899void
7900Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7901 SourceLocation ReturnLoc,
7902 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00007903 const AttrVec *Attrs,
7904 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007905 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7906
7907 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00007908 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7909 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00007910 CheckNonNullExpr(*this, RetValExp))
7911 Diag(ReturnLoc, diag::warn_null_ret)
7912 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00007913
7914 // C++11 [basic.stc.dynamic.allocation]p4:
7915 // If an allocation function declared with a non-throwing
7916 // exception-specification fails to allocate storage, it shall return
7917 // a null pointer. Any other allocation function that fails to allocate
7918 // storage shall indicate failure only by throwing an exception [...]
7919 if (FD) {
7920 OverloadedOperatorKind Op = FD->getOverloadedOperator();
7921 if (Op == OO_New || Op == OO_Array_New) {
7922 const FunctionProtoType *Proto
7923 = FD->getType()->castAs<FunctionProtoType>();
7924 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7925 CheckNonNullExpr(*this, RetValExp))
7926 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7927 << FD << getLangOpts().CPlusPlus11;
7928 }
7929 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007930}
7931
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007932//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7933
7934/// Check for comparisons of floating point operands using != and ==.
7935/// Issue a warning if these are no self-comparisons, as they are not likely
7936/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00007937void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00007938 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7939 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007940
7941 // Special case: check for x == x (which is OK).
7942 // Do not emit warnings for such cases.
7943 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7944 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7945 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00007946 return;
Mike Stump11289f42009-09-09 15:08:12 +00007947
Ted Kremenekeda40e22007-11-29 00:59:04 +00007948 // Special case: check for comparisons against literals that can be exactly
7949 // represented by APFloat. In such cases, do not emit a warning. This
7950 // is a heuristic: often comparison against such literals are used to
7951 // detect if a value in a variable has not changed. This clearly can
7952 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00007953 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7954 if (FLL->isExact())
7955 return;
7956 } else
7957 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7958 if (FLR->isExact())
7959 return;
Mike Stump11289f42009-09-09 15:08:12 +00007960
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007961 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00007962 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007963 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007964 return;
Mike Stump11289f42009-09-09 15:08:12 +00007965
David Blaikie1f4ff152012-07-16 20:47:22 +00007966 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007967 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007968 return;
Mike Stump11289f42009-09-09 15:08:12 +00007969
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007970 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00007971 Diag(Loc, diag::warn_floatingpoint_eq)
7972 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007973}
John McCallca01b222010-01-04 23:21:16 +00007974
John McCall70aa5392010-01-06 05:24:50 +00007975//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7976//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00007977
John McCall70aa5392010-01-06 05:24:50 +00007978namespace {
John McCallca01b222010-01-04 23:21:16 +00007979
John McCall70aa5392010-01-06 05:24:50 +00007980/// Structure recording the 'active' range of an integer-valued
7981/// expression.
7982struct IntRange {
7983 /// The number of bits active in the int.
7984 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00007985
John McCall70aa5392010-01-06 05:24:50 +00007986 /// True if the int is known not to have negative values.
7987 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00007988
John McCall70aa5392010-01-06 05:24:50 +00007989 IntRange(unsigned Width, bool NonNegative)
7990 : Width(Width), NonNegative(NonNegative)
7991 {}
John McCallca01b222010-01-04 23:21:16 +00007992
John McCall817d4af2010-11-10 23:38:19 +00007993 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00007994 static IntRange forBoolType() {
7995 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00007996 }
7997
John McCall817d4af2010-11-10 23:38:19 +00007998 /// Returns the range of an opaque value of the given integral type.
7999 static IntRange forValueOfType(ASTContext &C, QualType T) {
8000 return forValueOfCanonicalType(C,
8001 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00008002 }
8003
John McCall817d4af2010-11-10 23:38:19 +00008004 /// Returns the range of an opaque value of a canonical integral type.
8005 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00008006 assert(T->isCanonicalUnqualified());
8007
8008 if (const VectorType *VT = dyn_cast<VectorType>(T))
8009 T = VT->getElementType().getTypePtr();
8010 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8011 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008012 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8013 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00008014
David Majnemer6a426652013-06-07 22:07:20 +00008015 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00008016 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00008017 EnumDecl *Enum = ET->getDecl();
8018 if (!Enum->isCompleteDefinition())
8019 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00008020
David Majnemer6a426652013-06-07 22:07:20 +00008021 unsigned NumPositive = Enum->getNumPositiveBits();
8022 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00008023
David Majnemer6a426652013-06-07 22:07:20 +00008024 if (NumNegative == 0)
8025 return IntRange(NumPositive, true/*NonNegative*/);
8026 else
8027 return IntRange(std::max(NumPositive + 1, NumNegative),
8028 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00008029 }
John McCall70aa5392010-01-06 05:24:50 +00008030
8031 const BuiltinType *BT = cast<BuiltinType>(T);
8032 assert(BT->isInteger());
8033
8034 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8035 }
8036
John McCall817d4af2010-11-10 23:38:19 +00008037 /// Returns the "target" range of a canonical integral type, i.e.
8038 /// the range of values expressible in the type.
8039 ///
8040 /// This matches forValueOfCanonicalType except that enums have the
8041 /// full range of their type, not the range of their enumerators.
8042 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8043 assert(T->isCanonicalUnqualified());
8044
8045 if (const VectorType *VT = dyn_cast<VectorType>(T))
8046 T = VT->getElementType().getTypePtr();
8047 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8048 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008049 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8050 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008051 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00008052 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008053
8054 const BuiltinType *BT = cast<BuiltinType>(T);
8055 assert(BT->isInteger());
8056
8057 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8058 }
8059
8060 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00008061 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00008062 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00008063 L.NonNegative && R.NonNegative);
8064 }
8065
John McCall817d4af2010-11-10 23:38:19 +00008066 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008067 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008068 return IntRange(std::min(L.Width, R.Width),
8069 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008070 }
8071};
8072
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008073IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008074 if (value.isSigned() && value.isNegative())
8075 return IntRange(value.getMinSignedBits(), false);
8076
8077 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008078 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008079
8080 // isNonNegative() just checks the sign bit without considering
8081 // signedness.
8082 return IntRange(value.getActiveBits(), true);
8083}
8084
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008085IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8086 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008087 if (result.isInt())
8088 return GetValueRange(C, result.getInt(), MaxWidth);
8089
8090 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008091 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8092 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8093 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8094 R = IntRange::join(R, El);
8095 }
John McCall70aa5392010-01-06 05:24:50 +00008096 return R;
8097 }
8098
8099 if (result.isComplexInt()) {
8100 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8101 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8102 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008103 }
8104
8105 // This can happen with lossless casts to intptr_t of "based" lvalues.
8106 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008107 // FIXME: The only reason we need to pass the type in here is to get
8108 // the sign right on this one case. It would be nice if APValue
8109 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008110 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008111 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008112}
John McCall70aa5392010-01-06 05:24:50 +00008113
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008114QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008115 QualType Ty = E->getType();
8116 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8117 Ty = AtomicRHS->getValueType();
8118 return Ty;
8119}
8120
John McCall70aa5392010-01-06 05:24:50 +00008121/// Pseudo-evaluate the given integer expression, estimating the
8122/// range of values it might take.
8123///
8124/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008125IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008126 E = E->IgnoreParens();
8127
8128 // Try a full evaluation first.
8129 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008130 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008131 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008132
8133 // I think we only want to look through implicit casts here; if the
8134 // user has an explicit widening cast, we should treat the value as
8135 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008136 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00008137 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00008138 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8139
Eli Friedmane6d33952013-07-08 20:20:06 +00008140 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00008141
George Burgess IVdf1ed002016-01-13 01:52:39 +00008142 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8143 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00008144
John McCall70aa5392010-01-06 05:24:50 +00008145 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00008146 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00008147 return OutputTypeRange;
8148
8149 IntRange SubRange
8150 = GetExprRange(C, CE->getSubExpr(),
8151 std::min(MaxWidth, OutputTypeRange.Width));
8152
8153 // Bail out if the subexpr's range is as wide as the cast type.
8154 if (SubRange.Width >= OutputTypeRange.Width)
8155 return OutputTypeRange;
8156
8157 // Otherwise, we take the smaller width, and we're non-negative if
8158 // either the output type or the subexpr is.
8159 return IntRange(SubRange.Width,
8160 SubRange.NonNegative || OutputTypeRange.NonNegative);
8161 }
8162
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008163 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008164 // If we can fold the condition, just take that operand.
8165 bool CondResult;
8166 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8167 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8168 : CO->getFalseExpr(),
8169 MaxWidth);
8170
8171 // Otherwise, conservatively merge.
8172 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8173 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8174 return IntRange::join(L, R);
8175 }
8176
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008177 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008178 switch (BO->getOpcode()) {
8179
8180 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00008181 case BO_LAnd:
8182 case BO_LOr:
8183 case BO_LT:
8184 case BO_GT:
8185 case BO_LE:
8186 case BO_GE:
8187 case BO_EQ:
8188 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00008189 return IntRange::forBoolType();
8190
John McCallc3688382011-07-13 06:35:24 +00008191 // The type of the assignments is the type of the LHS, so the RHS
8192 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00008193 case BO_MulAssign:
8194 case BO_DivAssign:
8195 case BO_RemAssign:
8196 case BO_AddAssign:
8197 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00008198 case BO_XorAssign:
8199 case BO_OrAssign:
8200 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00008201 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00008202
John McCallc3688382011-07-13 06:35:24 +00008203 // Simple assignments just pass through the RHS, which will have
8204 // been coerced to the LHS type.
8205 case BO_Assign:
8206 // TODO: bitfields?
8207 return GetExprRange(C, BO->getRHS(), MaxWidth);
8208
John McCall70aa5392010-01-06 05:24:50 +00008209 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008210 case BO_PtrMemD:
8211 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00008212 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008213
John McCall2ce81ad2010-01-06 22:07:33 +00008214 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00008215 case BO_And:
8216 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00008217 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8218 GetExprRange(C, BO->getRHS(), MaxWidth));
8219
John McCall70aa5392010-01-06 05:24:50 +00008220 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00008221 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00008222 // ...except that we want to treat '1 << (blah)' as logically
8223 // positive. It's an important idiom.
8224 if (IntegerLiteral *I
8225 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8226 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008227 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00008228 return IntRange(R.Width, /*NonNegative*/ true);
8229 }
8230 }
8231 // fallthrough
8232
John McCalle3027922010-08-25 11:45:40 +00008233 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00008234 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008235
John McCall2ce81ad2010-01-06 22:07:33 +00008236 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00008237 case BO_Shr:
8238 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00008239 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8240
8241 // If the shift amount is a positive constant, drop the width by
8242 // that much.
8243 llvm::APSInt shift;
8244 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8245 shift.isNonNegative()) {
8246 unsigned zext = shift.getZExtValue();
8247 if (zext >= L.Width)
8248 L.Width = (L.NonNegative ? 0 : 1);
8249 else
8250 L.Width -= zext;
8251 }
8252
8253 return L;
8254 }
8255
8256 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008257 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008258 return GetExprRange(C, BO->getRHS(), MaxWidth);
8259
John McCall2ce81ad2010-01-06 22:07:33 +00008260 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008261 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008262 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008263 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008264 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008265
John McCall51431812011-07-14 22:39:48 +00008266 // The width of a division result is mostly determined by the size
8267 // of the LHS.
8268 case BO_Div: {
8269 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008270 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008271 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8272
8273 // If the divisor is constant, use that.
8274 llvm::APSInt divisor;
8275 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8276 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8277 if (log2 >= L.Width)
8278 L.Width = (L.NonNegative ? 0 : 1);
8279 else
8280 L.Width = std::min(L.Width - log2, MaxWidth);
8281 return L;
8282 }
8283
8284 // Otherwise, just use the LHS's width.
8285 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8286 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8287 }
8288
8289 // The result of a remainder can't be larger than the result of
8290 // either side.
8291 case BO_Rem: {
8292 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008293 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008294 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8295 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8296
8297 IntRange meet = IntRange::meet(L, R);
8298 meet.Width = std::min(meet.Width, MaxWidth);
8299 return meet;
8300 }
8301
8302 // The default behavior is okay for these.
8303 case BO_Mul:
8304 case BO_Add:
8305 case BO_Xor:
8306 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008307 break;
8308 }
8309
John McCall51431812011-07-14 22:39:48 +00008310 // The default case is to treat the operation as if it were closed
8311 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008312 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8313 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8314 return IntRange::join(L, R);
8315 }
8316
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008317 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008318 switch (UO->getOpcode()) {
8319 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008320 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008321 return IntRange::forBoolType();
8322
8323 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008324 case UO_Deref:
8325 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00008326 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008327
8328 default:
8329 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8330 }
8331 }
8332
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008333 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00008334 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8335
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008336 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00008337 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00008338 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00008339
Eli Friedmane6d33952013-07-08 20:20:06 +00008340 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008341}
John McCall263a48b2010-01-04 23:31:57 +00008342
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008343IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008344 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00008345}
8346
John McCall263a48b2010-01-04 23:31:57 +00008347/// Checks whether the given value, which currently has the given
8348/// source semantics, has the same value when coerced through the
8349/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008350bool IsSameFloatAfterCast(const llvm::APFloat &value,
8351 const llvm::fltSemantics &Src,
8352 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008353 llvm::APFloat truncated = value;
8354
8355 bool ignored;
8356 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8357 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8358
8359 return truncated.bitwiseIsEqual(value);
8360}
8361
8362/// Checks whether the given value, which currently has the given
8363/// source semantics, has the same value when coerced through the
8364/// target semantics.
8365///
8366/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008367bool IsSameFloatAfterCast(const APValue &value,
8368 const llvm::fltSemantics &Src,
8369 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008370 if (value.isFloat())
8371 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8372
8373 if (value.isVector()) {
8374 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8375 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8376 return false;
8377 return true;
8378 }
8379
8380 assert(value.isComplexFloat());
8381 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8382 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8383}
8384
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008385void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008386
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008387bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00008388 // Suppress cases where we are comparing against an enum constant.
8389 if (const DeclRefExpr *DR =
8390 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8391 if (isa<EnumConstantDecl>(DR->getDecl()))
8392 return false;
8393
8394 // Suppress cases where the '0' value is expanded from a macro.
8395 if (E->getLocStart().isMacroID())
8396 return false;
8397
John McCallcc7e5bf2010-05-06 08:58:33 +00008398 llvm::APSInt Value;
8399 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8400}
8401
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008402bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00008403 // Strip off implicit integral promotions.
8404 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008405 if (ICE->getCastKind() != CK_IntegralCast &&
8406 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00008407 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008408 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00008409 }
8410
8411 return E->getType()->isEnumeralType();
8412}
8413
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008414void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00008415 // Disable warning in template instantiations.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008416 if (S.inTemplateInstantiation())
Richard Trieu36594562013-11-01 21:47:19 +00008417 return;
8418
John McCalle3027922010-08-25 11:45:40 +00008419 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00008420 if (E->isValueDependent())
8421 return;
8422
John McCalle3027922010-08-25 11:45:40 +00008423 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008424 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008425 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008426 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008427 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008428 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008429 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008430 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008431 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008432 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008433 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008434 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008435 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008436 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008437 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008438 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8439 }
8440}
8441
Benjamin Kramer7320b992016-06-15 14:20:56 +00008442void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8443 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008444 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00008445 // Disable warning in template instantiations.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008446 if (S.inTemplateInstantiation())
Richard Trieudd51d742013-11-01 21:19:43 +00008447 return;
8448
Richard Trieu0f097742014-04-04 04:13:47 +00008449 // TODO: Investigate using GetExprRange() to get tighter bounds
8450 // on the bit ranges.
8451 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00008452 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00008453 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00008454 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8455 unsigned OtherWidth = OtherRange.Width;
8456
8457 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8458
Richard Trieu560910c2012-11-14 22:50:24 +00008459 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00008460 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00008461 return;
8462
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008463 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00008464 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008465
Richard Trieu0f097742014-04-04 04:13:47 +00008466 // Used for diagnostic printout.
8467 enum {
8468 LiteralConstant = 0,
8469 CXXBoolLiteralTrue,
8470 CXXBoolLiteralFalse
8471 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008472
Richard Trieu0f097742014-04-04 04:13:47 +00008473 if (!OtherIsBooleanType) {
8474 QualType ConstantT = Constant->getType();
8475 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00008476
Richard Trieu0f097742014-04-04 04:13:47 +00008477 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8478 return;
8479 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8480 "comparison with non-integer type");
8481
8482 bool ConstantSigned = ConstantT->isSignedIntegerType();
8483 bool CommonSigned = CommonT->isSignedIntegerType();
8484
8485 bool EqualityOnly = false;
8486
8487 if (CommonSigned) {
8488 // The common type is signed, therefore no signed to unsigned conversion.
8489 if (!OtherRange.NonNegative) {
8490 // Check that the constant is representable in type OtherT.
8491 if (ConstantSigned) {
8492 if (OtherWidth >= Value.getMinSignedBits())
8493 return;
8494 } else { // !ConstantSigned
8495 if (OtherWidth >= Value.getActiveBits() + 1)
8496 return;
8497 }
8498 } else { // !OtherSigned
8499 // Check that the constant is representable in type OtherT.
8500 // Negative values are out of range.
8501 if (ConstantSigned) {
8502 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8503 return;
8504 } else { // !ConstantSigned
8505 if (OtherWidth >= Value.getActiveBits())
8506 return;
8507 }
Richard Trieu560910c2012-11-14 22:50:24 +00008508 }
Richard Trieu0f097742014-04-04 04:13:47 +00008509 } else { // !CommonSigned
8510 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00008511 if (OtherWidth >= Value.getActiveBits())
8512 return;
Craig Toppercf360162014-06-18 05:13:11 +00008513 } else { // OtherSigned
8514 assert(!ConstantSigned &&
8515 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00008516 // Check to see if the constant is representable in OtherT.
8517 if (OtherWidth > Value.getActiveBits())
8518 return;
8519 // Check to see if the constant is equivalent to a negative value
8520 // cast to CommonT.
8521 if (S.Context.getIntWidth(ConstantT) ==
8522 S.Context.getIntWidth(CommonT) &&
8523 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8524 return;
8525 // The constant value rests between values that OtherT can represent
8526 // after conversion. Relational comparison still works, but equality
8527 // comparisons will be tautological.
8528 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008529 }
8530 }
Richard Trieu0f097742014-04-04 04:13:47 +00008531
8532 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8533
8534 if (op == BO_EQ || op == BO_NE) {
8535 IsTrue = op == BO_NE;
8536 } else if (EqualityOnly) {
8537 return;
8538 } else if (RhsConstant) {
8539 if (op == BO_GT || op == BO_GE)
8540 IsTrue = !PositiveConstant;
8541 else // op == BO_LT || op == BO_LE
8542 IsTrue = PositiveConstant;
8543 } else {
8544 if (op == BO_LT || op == BO_LE)
8545 IsTrue = !PositiveConstant;
8546 else // op == BO_GT || op == BO_GE
8547 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008548 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008549 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00008550 // Other isKnownToHaveBooleanValue
8551 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8552 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8553 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8554
8555 static const struct LinkedConditions {
8556 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8557 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8558 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8559 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8560 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8561 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8562
8563 } TruthTable = {
8564 // Constant on LHS. | Constant on RHS. |
8565 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
8566 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8567 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8568 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8569 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8570 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8571 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8572 };
8573
8574 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8575
8576 enum ConstantValue ConstVal = Zero;
8577 if (Value.isUnsigned() || Value.isNonNegative()) {
8578 if (Value == 0) {
8579 LiteralOrBoolConstant =
8580 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8581 ConstVal = Zero;
8582 } else if (Value == 1) {
8583 LiteralOrBoolConstant =
8584 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8585 ConstVal = One;
8586 } else {
8587 LiteralOrBoolConstant = LiteralConstant;
8588 ConstVal = GT_One;
8589 }
8590 } else {
8591 ConstVal = LT_Zero;
8592 }
8593
8594 CompareBoolWithConstantResult CmpRes;
8595
8596 switch (op) {
8597 case BO_LT:
8598 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8599 break;
8600 case BO_GT:
8601 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8602 break;
8603 case BO_LE:
8604 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8605 break;
8606 case BO_GE:
8607 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8608 break;
8609 case BO_EQ:
8610 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8611 break;
8612 case BO_NE:
8613 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8614 break;
8615 default:
8616 CmpRes = Unkwn;
8617 break;
8618 }
8619
8620 if (CmpRes == AFals) {
8621 IsTrue = false;
8622 } else if (CmpRes == ATrue) {
8623 IsTrue = true;
8624 } else {
8625 return;
8626 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008627 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008628
8629 // If this is a comparison to an enum constant, include that
8630 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00008631 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008632 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8633 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8634
8635 SmallString<64> PrettySourceValue;
8636 llvm::raw_svector_ostream OS(PrettySourceValue);
8637 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00008638 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008639 else
8640 OS << Value;
8641
Richard Trieu0f097742014-04-04 04:13:47 +00008642 S.DiagRuntimeBehavior(
8643 E->getOperatorLoc(), E,
8644 S.PDiag(diag::warn_out_of_range_compare)
8645 << OS.str() << LiteralOrBoolConstant
8646 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8647 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008648}
8649
John McCallcc7e5bf2010-05-06 08:58:33 +00008650/// Analyze the operands of the given comparison. Implements the
8651/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008652void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00008653 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8654 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008655}
John McCall263a48b2010-01-04 23:31:57 +00008656
John McCallca01b222010-01-04 23:21:16 +00008657/// \brief Implements -Wsign-compare.
8658///
Richard Trieu82402a02011-09-15 21:56:47 +00008659/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008660void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008661 // The type the comparison is being performed in.
8662 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00008663
8664 // Only analyze comparison operators where both sides have been converted to
8665 // the same type.
8666 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8667 return AnalyzeImpConvsInComparison(S, E);
8668
8669 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00008670 if (E->isValueDependent())
8671 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008672
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008673 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8674 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008675
8676 bool IsComparisonConstant = false;
8677
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008678 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008679 // of 'true' or 'false'.
8680 if (T->isIntegralType(S.Context)) {
8681 llvm::APSInt RHSValue;
8682 bool IsRHSIntegralLiteral =
8683 RHS->isIntegerConstantExpr(RHSValue, S.Context);
8684 llvm::APSInt LHSValue;
8685 bool IsLHSIntegralLiteral =
8686 LHS->isIntegerConstantExpr(LHSValue, S.Context);
8687 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8688 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8689 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8690 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8691 else
8692 IsComparisonConstant =
8693 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008694 } else if (!T->hasUnsignedIntegerRepresentation())
8695 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008696
John McCallcc7e5bf2010-05-06 08:58:33 +00008697 // We don't do anything special if this isn't an unsigned integral
8698 // comparison: we're only interested in integral comparisons, and
8699 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00008700 //
8701 // We also don't care about value-dependent expressions or expressions
8702 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008703 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00008704 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008705
John McCallcc7e5bf2010-05-06 08:58:33 +00008706 // Check to see if one of the (unmodified) operands is of different
8707 // signedness.
8708 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00008709 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8710 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00008711 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00008712 signedOperand = LHS;
8713 unsignedOperand = RHS;
8714 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8715 signedOperand = RHS;
8716 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00008717 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00008718 CheckTrivialUnsignedComparison(S, E);
8719 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008720 }
8721
John McCallcc7e5bf2010-05-06 08:58:33 +00008722 // Otherwise, calculate the effective range of the signed operand.
8723 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00008724
John McCallcc7e5bf2010-05-06 08:58:33 +00008725 // Go ahead and analyze implicit conversions in the operands. Note
8726 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00008727 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8728 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00008729
John McCallcc7e5bf2010-05-06 08:58:33 +00008730 // If the signed range is non-negative, -Wsign-compare won't fire,
8731 // but we should still check for comparisons which are always true
8732 // or false.
8733 if (signedRange.NonNegative)
8734 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008735
8736 // For (in)equality comparisons, if the unsigned operand is a
8737 // constant which cannot collide with a overflowed signed operand,
8738 // then reinterpreting the signed operand as unsigned will not
8739 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00008740 if (E->isEqualityOp()) {
8741 unsigned comparisonWidth = S.Context.getIntWidth(T);
8742 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00008743
John McCallcc7e5bf2010-05-06 08:58:33 +00008744 // We should never be unable to prove that the unsigned operand is
8745 // non-negative.
8746 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8747
8748 if (unsignedRange.Width < comparisonWidth)
8749 return;
8750 }
8751
Douglas Gregorbfb4a212012-05-01 01:53:49 +00008752 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8753 S.PDiag(diag::warn_mixed_sign_comparison)
8754 << LHS->getType() << RHS->getType()
8755 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00008756}
8757
John McCall1f425642010-11-11 03:21:53 +00008758/// Analyzes an attempt to assign the given value to a bitfield.
8759///
8760/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008761bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8762 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00008763 assert(Bitfield->isBitField());
8764 if (Bitfield->isInvalidDecl())
8765 return false;
8766
John McCalldeebbcf2010-11-11 05:33:51 +00008767 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00008768 QualType BitfieldType = Bitfield->getType();
8769 if (BitfieldType->isBooleanType())
8770 return false;
8771
8772 if (BitfieldType->isEnumeralType()) {
8773 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
8774 // If the underlying enum type was not explicitly specified as an unsigned
8775 // type and the enum contain only positive values, MSVC++ will cause an
8776 // inconsistency by storing this as a signed type.
8777 if (S.getLangOpts().CPlusPlus11 &&
8778 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
8779 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
8780 BitfieldEnumDecl->getNumNegativeBits() == 0) {
8781 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
8782 << BitfieldEnumDecl->getNameAsString();
8783 }
8784 }
8785
John McCalldeebbcf2010-11-11 05:33:51 +00008786 if (Bitfield->getType()->isBooleanType())
8787 return false;
8788
Douglas Gregor789adec2011-02-04 13:09:01 +00008789 // Ignore value- or type-dependent expressions.
8790 if (Bitfield->getBitWidth()->isValueDependent() ||
8791 Bitfield->getBitWidth()->isTypeDependent() ||
8792 Init->isValueDependent() ||
8793 Init->isTypeDependent())
8794 return false;
8795
John McCall1f425642010-11-11 03:21:53 +00008796 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00008797 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00008798
Richard Smith5fab0c92011-12-28 19:48:30 +00008799 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00008800 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
8801 Expr::SE_AllowSideEffects)) {
8802 // The RHS is not constant. If the RHS has an enum type, make sure the
8803 // bitfield is wide enough to hold all the values of the enum without
8804 // truncation.
8805 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
8806 EnumDecl *ED = EnumTy->getDecl();
8807 bool SignedBitfield = BitfieldType->isSignedIntegerType();
8808
8809 // Enum types are implicitly signed on Windows, so check if there are any
8810 // negative enumerators to see if the enum was intended to be signed or
8811 // not.
8812 bool SignedEnum = ED->getNumNegativeBits() > 0;
8813
8814 // Check for surprising sign changes when assigning enum values to a
8815 // bitfield of different signedness. If the bitfield is signed and we
8816 // have exactly the right number of bits to store this unsigned enum,
8817 // suggest changing the enum to an unsigned type. This typically happens
8818 // on Windows where unfixed enums always use an underlying type of 'int'.
8819 unsigned DiagID = 0;
8820 if (SignedEnum && !SignedBitfield) {
8821 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
8822 } else if (SignedBitfield && !SignedEnum &&
8823 ED->getNumPositiveBits() == FieldWidth) {
8824 DiagID = diag::warn_signed_bitfield_enum_conversion;
8825 }
8826
8827 if (DiagID) {
8828 S.Diag(InitLoc, DiagID) << Bitfield << ED;
8829 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
8830 SourceRange TypeRange =
8831 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
8832 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
8833 << SignedEnum << TypeRange;
8834 }
8835
8836 // Compute the required bitwidth. If the enum has negative values, we need
8837 // one more bit than the normal number of positive bits to represent the
8838 // sign bit.
8839 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
8840 ED->getNumNegativeBits())
8841 : ED->getNumPositiveBits();
8842
8843 // Check the bitwidth.
8844 if (BitsNeeded > FieldWidth) {
8845 Expr *WidthExpr = Bitfield->getBitWidth();
8846 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
8847 << Bitfield << ED;
8848 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
8849 << BitsNeeded << ED << WidthExpr->getSourceRange();
8850 }
8851 }
8852
John McCall1f425642010-11-11 03:21:53 +00008853 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00008854 }
John McCall1f425642010-11-11 03:21:53 +00008855
John McCall1f425642010-11-11 03:21:53 +00008856 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00008857
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008858 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00008859 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008860 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8861 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00008862
John McCall1f425642010-11-11 03:21:53 +00008863 if (OriginalWidth <= FieldWidth)
8864 return false;
8865
Eli Friedmanc267a322012-01-26 23:11:39 +00008866 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00008867 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00008868 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00008869
Eli Friedmanc267a322012-01-26 23:11:39 +00008870 // Check whether the stored value is equal to the original value.
8871 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00008872 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00008873 return false;
8874
Eli Friedmanc267a322012-01-26 23:11:39 +00008875 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00008876 // therefore don't strictly fit into a signed bitfield of width 1.
8877 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00008878 return false;
8879
John McCall1f425642010-11-11 03:21:53 +00008880 std::string PrettyValue = Value.toString(10);
8881 std::string PrettyTrunc = TruncatedValue.toString(10);
8882
8883 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8884 << PrettyValue << PrettyTrunc << OriginalInit->getType()
8885 << Init->getSourceRange();
8886
8887 return true;
8888}
8889
John McCalld2a53122010-11-09 23:24:47 +00008890/// Analyze the given simple or compound assignment for warning-worthy
8891/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008892void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00008893 // Just recurse on the LHS.
8894 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8895
8896 // We want to recurse on the RHS as normal unless we're assigning to
8897 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00008898 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008899 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00008900 E->getOperatorLoc())) {
8901 // Recurse, ignoring any implicit conversions on the RHS.
8902 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8903 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00008904 }
8905 }
8906
8907 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8908}
8909
John McCall263a48b2010-01-04 23:31:57 +00008910/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008911void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8912 SourceLocation CContext, unsigned diag,
8913 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008914 if (pruneControlFlow) {
8915 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8916 S.PDiag(diag)
8917 << SourceType << T << E->getSourceRange()
8918 << SourceRange(CContext));
8919 return;
8920 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00008921 S.Diag(E->getExprLoc(), diag)
8922 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8923}
8924
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008925/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008926void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8927 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008928 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008929}
8930
Richard Trieube234c32016-04-21 21:04:55 +00008931
8932/// Diagnose an implicit cast from a floating point value to an integer value.
8933void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8934
8935 SourceLocation CContext) {
8936 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00008937 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00008938
8939 Expr *InnerE = E->IgnoreParenImpCasts();
8940 // We also want to warn on, e.g., "int i = -1.234"
8941 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8942 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8943 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8944
8945 const bool IsLiteral =
8946 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8947
8948 llvm::APFloat Value(0.0);
8949 bool IsConstant =
8950 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8951 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00008952 return DiagnoseImpCast(S, E, T, CContext,
8953 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00008954 }
8955
Chandler Carruth016ef402011-04-10 08:36:24 +00008956 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00008957
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00008958 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8959 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00008960 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8961 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00008962 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00008963 if (IsLiteral) return;
8964 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8965 PruneWarnings);
8966 }
8967
8968 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00008969 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00008970 // Warn on floating point literal to integer.
8971 DiagID = diag::warn_impcast_literal_float_to_integer;
8972 } else if (IntegerValue == 0) {
8973 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
8974 return DiagnoseImpCast(S, E, T, CContext,
8975 diag::warn_impcast_float_integer, PruneWarnings);
8976 }
8977 // Warn on non-zero to zero conversion.
8978 DiagID = diag::warn_impcast_float_to_integer_zero;
8979 } else {
8980 if (IntegerValue.isUnsigned()) {
8981 if (!IntegerValue.isMaxValue()) {
8982 return DiagnoseImpCast(S, E, T, CContext,
8983 diag::warn_impcast_float_integer, PruneWarnings);
8984 }
8985 } else { // IntegerValue.isSigned()
8986 if (!IntegerValue.isMaxSignedValue() &&
8987 !IntegerValue.isMinSignedValue()) {
8988 return DiagnoseImpCast(S, E, T, CContext,
8989 diag::warn_impcast_float_integer, PruneWarnings);
8990 }
8991 }
8992 // Warn on evaluatable floating point expression to integer conversion.
8993 DiagID = diag::warn_impcast_float_to_integer;
8994 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008995
Eli Friedman07185912013-08-29 23:44:43 +00008996 // FIXME: Force the precision of the source value down so we don't print
8997 // digits which are usually useless (we don't really care here if we
8998 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
8999 // would automatically print the shortest representation, but it's a bit
9000 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00009001 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00009002 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9003 precision = (precision * 59 + 195) / 196;
9004 Value.toString(PrettySourceValue, precision);
9005
David Blaikie9b88cc02012-05-15 17:18:27 +00009006 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00009007 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00009008 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00009009 else
David Blaikie9b88cc02012-05-15 17:18:27 +00009010 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00009011
Richard Trieube234c32016-04-21 21:04:55 +00009012 if (PruneWarnings) {
9013 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9014 S.PDiag(DiagID)
9015 << E->getType() << T.getUnqualifiedType()
9016 << PrettySourceValue << PrettyTargetValue
9017 << E->getSourceRange() << SourceRange(CContext));
9018 } else {
9019 S.Diag(E->getExprLoc(), DiagID)
9020 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9021 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9022 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009023}
9024
John McCall18a2c2c2010-11-09 22:22:12 +00009025std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
9026 if (!Range.Width) return "0";
9027
9028 llvm::APSInt ValueInRange = Value;
9029 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00009030 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00009031 return ValueInRange.toString(10);
9032}
9033
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009034bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009035 if (!isa<ImplicitCastExpr>(Ex))
9036 return false;
9037
9038 Expr *InnerE = Ex->IgnoreParenImpCasts();
9039 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9040 const Type *Source =
9041 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9042 if (Target->isDependentType())
9043 return false;
9044
9045 const BuiltinType *FloatCandidateBT =
9046 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9047 const Type *BoolCandidateType = ToBool ? Target : Source;
9048
9049 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9050 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9051}
9052
9053void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9054 SourceLocation CC) {
9055 unsigned NumArgs = TheCall->getNumArgs();
9056 for (unsigned i = 0; i < NumArgs; ++i) {
9057 Expr *CurrA = TheCall->getArg(i);
9058 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9059 continue;
9060
9061 bool IsSwapped = ((i > 0) &&
9062 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9063 IsSwapped |= ((i < (NumArgs - 1)) &&
9064 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9065 if (IsSwapped) {
9066 // Warn on this floating-point to bool conversion.
9067 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9068 CurrA->getType(), CC,
9069 diag::warn_impcast_floating_point_to_bool);
9070 }
9071 }
9072}
9073
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009074void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009075 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9076 E->getExprLoc()))
9077 return;
9078
Richard Trieu09d6b802016-01-08 23:35:06 +00009079 // Don't warn on functions which have return type nullptr_t.
9080 if (isa<CallExpr>(E))
9081 return;
9082
Richard Trieu5b993502014-10-15 03:42:06 +00009083 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9084 const Expr::NullPointerConstantKind NullKind =
9085 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9086 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9087 return;
9088
9089 // Return if target type is a safe conversion.
9090 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9091 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9092 return;
9093
9094 SourceLocation Loc = E->getSourceRange().getBegin();
9095
Richard Trieu0a5e1662016-02-13 00:58:53 +00009096 // Venture through the macro stacks to get to the source of macro arguments.
9097 // The new location is a better location than the complete location that was
9098 // passed in.
9099 while (S.SourceMgr.isMacroArgExpansion(Loc))
9100 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
9101
9102 while (S.SourceMgr.isMacroArgExpansion(CC))
9103 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
9104
Richard Trieu5b993502014-10-15 03:42:06 +00009105 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00009106 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9107 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9108 Loc, S.SourceMgr, S.getLangOpts());
9109 if (MacroName == "NULL")
9110 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00009111 }
9112
9113 // Only warn if the null and context location are in the same macro expansion.
9114 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9115 return;
9116
9117 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9118 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
9119 << FixItHint::CreateReplacement(Loc,
9120 S.getFixItZeroLiteralForType(T, Loc));
9121}
9122
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009123void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9124 ObjCArrayLiteral *ArrayLiteral);
9125void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9126 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00009127
9128/// Check a single element within a collection literal against the
9129/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009130void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
9131 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009132 // Skip a bitcast to 'id' or qualified 'id'.
9133 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9134 if (ICE->getCastKind() == CK_BitCast &&
9135 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9136 Element = ICE->getSubExpr();
9137 }
9138
9139 QualType ElementType = Element->getType();
9140 ExprResult ElementResult(Element);
9141 if (ElementType->getAs<ObjCObjectPointerType>() &&
9142 S.CheckSingleAssignmentConstraints(TargetElementType,
9143 ElementResult,
9144 false, false)
9145 != Sema::Compatible) {
9146 S.Diag(Element->getLocStart(),
9147 diag::warn_objc_collection_literal_element)
9148 << ElementType << ElementKind << TargetElementType
9149 << Element->getSourceRange();
9150 }
9151
9152 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9153 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9154 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9155 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9156}
9157
9158/// Check an Objective-C array literal being converted to the given
9159/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009160void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9161 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009162 if (!S.NSArrayDecl)
9163 return;
9164
9165 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9166 if (!TargetObjCPtr)
9167 return;
9168
9169 if (TargetObjCPtr->isUnspecialized() ||
9170 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9171 != S.NSArrayDecl->getCanonicalDecl())
9172 return;
9173
9174 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9175 if (TypeArgs.size() != 1)
9176 return;
9177
9178 QualType TargetElementType = TypeArgs[0];
9179 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9180 checkObjCCollectionLiteralElement(S, TargetElementType,
9181 ArrayLiteral->getElement(I),
9182 0);
9183 }
9184}
9185
9186/// Check an Objective-C dictionary literal being converted to the given
9187/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009188void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9189 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009190 if (!S.NSDictionaryDecl)
9191 return;
9192
9193 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9194 if (!TargetObjCPtr)
9195 return;
9196
9197 if (TargetObjCPtr->isUnspecialized() ||
9198 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9199 != S.NSDictionaryDecl->getCanonicalDecl())
9200 return;
9201
9202 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9203 if (TypeArgs.size() != 2)
9204 return;
9205
9206 QualType TargetKeyType = TypeArgs[0];
9207 QualType TargetObjectType = TypeArgs[1];
9208 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9209 auto Element = DictionaryLiteral->getKeyValueElement(I);
9210 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9211 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9212 }
9213}
9214
Richard Trieufc404c72016-02-05 23:02:38 +00009215// Helper function to filter out cases for constant width constant conversion.
9216// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009217bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9218 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00009219 // If initializing from a constant, and the constant starts with '0',
9220 // then it is a binary, octal, or hexadecimal. Allow these constants
9221 // to fill all the bits, even if there is a sign change.
9222 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9223 const char FirstLiteralCharacter =
9224 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9225 if (FirstLiteralCharacter == '0')
9226 return false;
9227 }
9228
9229 // If the CC location points to a '{', and the type is char, then assume
9230 // assume it is an array initialization.
9231 if (CC.isValid() && T->isCharType()) {
9232 const char FirstContextCharacter =
9233 S.getSourceManager().getCharacterData(CC)[0];
9234 if (FirstContextCharacter == '{')
9235 return false;
9236 }
9237
9238 return true;
9239}
9240
John McCallcc7e5bf2010-05-06 08:58:33 +00009241void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00009242 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009243 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00009244
John McCallcc7e5bf2010-05-06 08:58:33 +00009245 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9246 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9247 if (Source == Target) return;
9248 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00009249
Chandler Carruthc22845a2011-07-26 05:40:03 +00009250 // If the conversion context location is invalid don't complain. We also
9251 // don't want to emit a warning if the issue occurs from the expansion of
9252 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9253 // delay this check as long as possible. Once we detect we are in that
9254 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009255 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00009256 return;
9257
Richard Trieu021baa32011-09-23 20:10:00 +00009258 // Diagnose implicit casts to bool.
9259 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9260 if (isa<StringLiteral>(E))
9261 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00009262 // and expressions, for instance, assert(0 && "error here"), are
9263 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00009264 return DiagnoseImpCast(S, E, T, CC,
9265 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00009266 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9267 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9268 // This covers the literal expressions that evaluate to Objective-C
9269 // objects.
9270 return DiagnoseImpCast(S, E, T, CC,
9271 diag::warn_impcast_objective_c_literal_to_bool);
9272 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009273 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9274 // Warn on pointer to bool conversion that is always true.
9275 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9276 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00009277 }
Richard Trieu021baa32011-09-23 20:10:00 +00009278 }
John McCall263a48b2010-01-04 23:31:57 +00009279
Douglas Gregor5054cb02015-07-07 03:58:22 +00009280 // Check implicit casts from Objective-C collection literals to specialized
9281 // collection types, e.g., NSArray<NSString *> *.
9282 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9283 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9284 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9285 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9286
John McCall263a48b2010-01-04 23:31:57 +00009287 // Strip vector types.
9288 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009289 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009290 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009291 return;
John McCallacf0ee52010-10-08 02:01:28 +00009292 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009293 }
Chris Lattneree7286f2011-06-14 04:51:15 +00009294
9295 // If the vector cast is cast between two vectors of the same size, it is
9296 // a bitcast, not a conversion.
9297 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9298 return;
John McCall263a48b2010-01-04 23:31:57 +00009299
9300 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9301 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9302 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00009303 if (auto VecTy = dyn_cast<VectorType>(Target))
9304 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00009305
9306 // Strip complex types.
9307 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009308 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009309 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009310 return;
9311
John McCallacf0ee52010-10-08 02:01:28 +00009312 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009313 }
John McCall263a48b2010-01-04 23:31:57 +00009314
9315 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9316 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9317 }
9318
9319 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9320 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9321
9322 // If the source is floating point...
9323 if (SourceBT && SourceBT->isFloatingPoint()) {
9324 // ...and the target is floating point...
9325 if (TargetBT && TargetBT->isFloatingPoint()) {
9326 // ...then warn if we're dropping FP rank.
9327
9328 // Builtin FP kinds are ordered by increasing FP rank.
9329 if (SourceBT->getKind() > TargetBT->getKind()) {
9330 // Don't warn about float constants that are precisely
9331 // representable in the target type.
9332 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009333 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00009334 // Value might be a float, a float vector, or a float complex.
9335 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00009336 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9337 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00009338 return;
9339 }
9340
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009341 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009342 return;
9343
John McCallacf0ee52010-10-08 02:01:28 +00009344 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00009345 }
9346 // ... or possibly if we're increasing rank, too
9347 else if (TargetBT->getKind() > SourceBT->getKind()) {
9348 if (S.SourceMgr.isInSystemMacro(CC))
9349 return;
9350
9351 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00009352 }
9353 return;
9354 }
9355
Richard Trieube234c32016-04-21 21:04:55 +00009356 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00009357 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009358 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009359 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00009360
Richard Trieube234c32016-04-21 21:04:55 +00009361 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00009362 }
John McCall263a48b2010-01-04 23:31:57 +00009363
Richard Smith54894fd2015-12-30 01:06:52 +00009364 // Detect the case where a call result is converted from floating-point to
9365 // to bool, and the final argument to the call is converted from bool, to
9366 // discover this typo:
9367 //
9368 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9369 //
9370 // FIXME: This is an incredibly special case; is there some more general
9371 // way to detect this class of misplaced-parentheses bug?
9372 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009373 // Check last argument of function call to see if it is an
9374 // implicit cast from a type matching the type the result
9375 // is being cast to.
9376 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00009377 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009378 Expr *LastA = CEx->getArg(NumArgs - 1);
9379 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00009380 if (isa<ImplicitCastExpr>(LastA) &&
9381 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009382 // Warn on this floating-point to bool conversion
9383 DiagnoseImpCast(S, E, T, CC,
9384 diag::warn_impcast_floating_point_to_bool);
9385 }
9386 }
9387 }
John McCall263a48b2010-01-04 23:31:57 +00009388 return;
9389 }
9390
Richard Trieu5b993502014-10-15 03:42:06 +00009391 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00009392
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009393 S.DiscardMisalignedMemberAddress(Target, E);
9394
David Blaikie9366d2b2012-06-19 21:19:06 +00009395 if (!Source->isIntegerType() || !Target->isIntegerType())
9396 return;
9397
David Blaikie7555b6a2012-05-15 16:56:36 +00009398 // TODO: remove this early return once the false positives for constant->bool
9399 // in templates, macros, etc, are reduced or removed.
9400 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9401 return;
9402
John McCallcc7e5bf2010-05-06 08:58:33 +00009403 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00009404 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00009405
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009406 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00009407 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009408 // TODO: this should happen for bitfield stores, too.
9409 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00009410 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009411 if (S.SourceMgr.isInSystemMacro(CC))
9412 return;
9413
John McCall18a2c2c2010-11-09 22:22:12 +00009414 std::string PrettySourceValue = Value.toString(10);
9415 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009416
Ted Kremenek33ba9952011-10-22 02:37:33 +00009417 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9418 S.PDiag(diag::warn_impcast_integer_precision_constant)
9419 << PrettySourceValue << PrettyTargetValue
9420 << E->getType() << T << E->getSourceRange()
9421 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00009422 return;
9423 }
9424
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009425 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9426 if (S.SourceMgr.isInSystemMacro(CC))
9427 return;
9428
David Blaikie9455da02012-04-12 22:40:54 +00009429 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00009430 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9431 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00009432 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00009433 }
9434
Richard Trieudcb55572016-01-29 23:51:16 +00009435 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9436 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9437 // Warn when doing a signed to signed conversion, warn if the positive
9438 // source value is exactly the width of the target type, which will
9439 // cause a negative value to be stored.
9440
9441 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00009442 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9443 !S.SourceMgr.isInSystemMacro(CC)) {
9444 if (isSameWidthConstantConversion(S, E, T, CC)) {
9445 std::string PrettySourceValue = Value.toString(10);
9446 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00009447
Richard Trieufc404c72016-02-05 23:02:38 +00009448 S.DiagRuntimeBehavior(
9449 E->getExprLoc(), E,
9450 S.PDiag(diag::warn_impcast_integer_precision_constant)
9451 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9452 << E->getSourceRange() << clang::SourceRange(CC));
9453 return;
Richard Trieudcb55572016-01-29 23:51:16 +00009454 }
9455 }
Richard Trieufc404c72016-02-05 23:02:38 +00009456
Richard Trieudcb55572016-01-29 23:51:16 +00009457 // Fall through for non-constants to give a sign conversion warning.
9458 }
9459
John McCallcc7e5bf2010-05-06 08:58:33 +00009460 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9461 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9462 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009463 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009464 return;
9465
John McCallcc7e5bf2010-05-06 08:58:33 +00009466 unsigned DiagID = diag::warn_impcast_integer_sign;
9467
9468 // Traditionally, gcc has warned about this under -Wsign-compare.
9469 // We also want to warn about it in -Wconversion.
9470 // So if -Wconversion is off, use a completely identical diagnostic
9471 // in the sign-compare group.
9472 // The conditional-checking code will
9473 if (ICContext) {
9474 DiagID = diag::warn_impcast_integer_sign_conditional;
9475 *ICContext = true;
9476 }
9477
John McCallacf0ee52010-10-08 02:01:28 +00009478 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00009479 }
9480
Douglas Gregora78f1932011-02-22 02:45:07 +00009481 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00009482 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9483 // type, to give us better diagnostics.
9484 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009485 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00009486 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9487 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9488 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9489 SourceType = S.Context.getTypeDeclType(Enum);
9490 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9491 }
9492 }
9493
Douglas Gregora78f1932011-02-22 02:45:07 +00009494 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9495 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00009496 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9497 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009498 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009499 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009500 return;
9501
Douglas Gregor364f7db2011-03-12 00:14:31 +00009502 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00009503 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009504 }
John McCall263a48b2010-01-04 23:31:57 +00009505}
9506
David Blaikie18e9ac72012-05-15 21:57:38 +00009507void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9508 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009509
9510void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00009511 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009512 E = E->IgnoreParenImpCasts();
9513
9514 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00009515 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009516
John McCallacf0ee52010-10-08 02:01:28 +00009517 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009518 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009519 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00009520}
9521
David Blaikie18e9ac72012-05-15 21:57:38 +00009522void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9523 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00009524 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009525
9526 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00009527 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9528 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009529
9530 // If -Wconversion would have warned about either of the candidates
9531 // for a signedness conversion to the context type...
9532 if (!Suspicious) return;
9533
9534 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009535 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00009536 return;
9537
John McCallcc7e5bf2010-05-06 08:58:33 +00009538 // ...then check whether it would have warned about either of the
9539 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00009540 if (E->getType() == T) return;
9541
9542 Suspicious = false;
9543 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9544 E->getType(), CC, &Suspicious);
9545 if (!Suspicious)
9546 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00009547 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009548}
9549
Richard Trieu65724892014-11-15 06:37:39 +00009550/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9551/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009552void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00009553 if (S.getLangOpts().Bool)
9554 return;
9555 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9556}
9557
John McCallcc7e5bf2010-05-06 08:58:33 +00009558/// AnalyzeImplicitConversions - Find and report any interesting
9559/// implicit conversions in the given expression. There are a couple
9560/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009561void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00009562 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00009563 Expr *E = OrigE->IgnoreParenImpCasts();
9564
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00009565 if (E->isTypeDependent() || E->isValueDependent())
9566 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00009567
John McCallcc7e5bf2010-05-06 08:58:33 +00009568 // For conditional operators, we analyze the arguments as if they
9569 // were being fed directly into the output.
9570 if (isa<ConditionalOperator>(E)) {
9571 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00009572 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009573 return;
9574 }
9575
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009576 // Check implicit argument conversions for function calls.
9577 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9578 CheckImplicitArgumentConversions(S, Call, CC);
9579
John McCallcc7e5bf2010-05-06 08:58:33 +00009580 // Go ahead and check any implicit conversions we might have skipped.
9581 // The non-canonical typecheck is just an optimization;
9582 // CheckImplicitConversion will filter out dead implicit conversions.
9583 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009584 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009585
9586 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00009587
9588 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9589 // The bound subexpressions in a PseudoObjectExpr are not reachable
9590 // as transitive children.
9591 // FIXME: Use a more uniform representation for this.
9592 for (auto *SE : POE->semantics())
9593 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9594 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00009595 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00009596
John McCallcc7e5bf2010-05-06 08:58:33 +00009597 // Skip past explicit casts.
9598 if (isa<ExplicitCastExpr>(E)) {
9599 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00009600 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009601 }
9602
John McCalld2a53122010-11-09 23:24:47 +00009603 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9604 // Do a somewhat different check with comparison operators.
9605 if (BO->isComparisonOp())
9606 return AnalyzeComparison(S, BO);
9607
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009608 // And with simple assignments.
9609 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00009610 return AnalyzeAssignment(S, BO);
9611 }
John McCallcc7e5bf2010-05-06 08:58:33 +00009612
9613 // These break the otherwise-useful invariant below. Fortunately,
9614 // we don't really need to recurse into them, because any internal
9615 // expressions should have been analyzed already when they were
9616 // built into statements.
9617 if (isa<StmtExpr>(E)) return;
9618
9619 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00009620 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00009621
9622 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00009623 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00009624 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00009625 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00009626 for (Stmt *SubStmt : E->children()) {
9627 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00009628 if (!ChildExpr)
9629 continue;
9630
Richard Trieu955231d2014-01-25 01:10:35 +00009631 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00009632 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00009633 // Ignore checking string literals that are in logical and operators.
9634 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00009635 continue;
9636 AnalyzeImplicitConversions(S, ChildExpr, CC);
9637 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009638
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009639 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00009640 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9641 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009642 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00009643
9644 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9645 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009646 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009647 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009648
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009649 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9650 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00009651 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009652}
9653
9654} // end anonymous namespace
9655
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009656/// Diagnose integer type and any valid implicit convertion to it.
9657static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9658 // Taking into account implicit conversions,
9659 // allow any integer.
9660 if (!E->getType()->isIntegerType()) {
9661 S.Diag(E->getLocStart(),
9662 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9663 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009664 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009665 // Potentially emit standard warnings for implicit conversions if enabled
9666 // using -Wconversion.
9667 CheckImplicitConversion(S, E, IntT, E->getLocStart());
9668 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009669}
9670
Richard Trieuc1888e02014-06-28 23:25:37 +00009671// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9672// Returns true when emitting a warning about taking the address of a reference.
9673static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00009674 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00009675 E = E->IgnoreParenImpCasts();
9676
9677 const FunctionDecl *FD = nullptr;
9678
9679 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9680 if (!DRE->getDecl()->getType()->isReferenceType())
9681 return false;
9682 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9683 if (!M->getMemberDecl()->getType()->isReferenceType())
9684 return false;
9685 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00009686 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00009687 return false;
9688 FD = Call->getDirectCallee();
9689 } else {
9690 return false;
9691 }
9692
9693 SemaRef.Diag(E->getExprLoc(), PD);
9694
9695 // If possible, point to location of function.
9696 if (FD) {
9697 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9698 }
9699
9700 return true;
9701}
9702
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009703// Returns true if the SourceLocation is expanded from any macro body.
9704// Returns false if the SourceLocation is invalid, is from not in a macro
9705// expansion, or is from expanded from a top-level macro argument.
9706static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9707 if (Loc.isInvalid())
9708 return false;
9709
9710 while (Loc.isMacroID()) {
9711 if (SM.isMacroBodyExpansion(Loc))
9712 return true;
9713 Loc = SM.getImmediateMacroCallerLoc(Loc);
9714 }
9715
9716 return false;
9717}
9718
Richard Trieu3bb8b562014-02-26 02:36:06 +00009719/// \brief Diagnose pointers that are always non-null.
9720/// \param E the expression containing the pointer
9721/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9722/// compared to a null pointer
9723/// \param IsEqual True when the comparison is equal to a null pointer
9724/// \param Range Extra SourceRange to highlight in the diagnostic
9725void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9726 Expr::NullPointerConstantKind NullKind,
9727 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00009728 if (!E)
9729 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009730
9731 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009732 if (E->getExprLoc().isMacroID()) {
9733 const SourceManager &SM = getSourceManager();
9734 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9735 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00009736 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009737 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009738 E = E->IgnoreImpCasts();
9739
9740 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9741
Richard Trieuf7432752014-06-06 21:39:26 +00009742 if (isa<CXXThisExpr>(E)) {
9743 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9744 : diag::warn_this_bool_conversion;
9745 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9746 return;
9747 }
9748
Richard Trieu3bb8b562014-02-26 02:36:06 +00009749 bool IsAddressOf = false;
9750
9751 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9752 if (UO->getOpcode() != UO_AddrOf)
9753 return;
9754 IsAddressOf = true;
9755 E = UO->getSubExpr();
9756 }
9757
Richard Trieuc1888e02014-06-28 23:25:37 +00009758 if (IsAddressOf) {
9759 unsigned DiagID = IsCompare
9760 ? diag::warn_address_of_reference_null_compare
9761 : diag::warn_address_of_reference_bool_conversion;
9762 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9763 << IsEqual;
9764 if (CheckForReference(*this, E, PD)) {
9765 return;
9766 }
9767 }
9768
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009769 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9770 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00009771 std::string Str;
9772 llvm::raw_string_ostream S(Str);
9773 E->printPretty(S, nullptr, getPrintingPolicy());
9774 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9775 : diag::warn_cast_nonnull_to_bool;
9776 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9777 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009778 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00009779 };
9780
9781 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9782 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9783 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009784 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9785 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009786 return;
9787 }
9788 }
9789 }
9790
Richard Trieu3bb8b562014-02-26 02:36:06 +00009791 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00009792 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009793 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9794 D = R->getDecl();
9795 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9796 D = M->getMemberDecl();
9797 }
9798
9799 // Weak Decls can be null.
9800 if (!D || D->isWeak())
9801 return;
George Burgess IV850269a2015-12-08 22:02:00 +00009802
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009803 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00009804 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9805 if (getCurFunction() &&
9806 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009807 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9808 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009809 return;
9810 }
9811
9812 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +00009813 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +00009814 assert(ParamIter != FD->param_end());
9815 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9816
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009817 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9818 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009819 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +00009820 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009821 }
George Burgess IV850269a2015-12-08 22:02:00 +00009822
9823 for (unsigned ArgNo : NonNull->args()) {
9824 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009825 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009826 return;
9827 }
George Burgess IV850269a2015-12-08 22:02:00 +00009828 }
9829 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009830 }
9831 }
George Burgess IV850269a2015-12-08 22:02:00 +00009832 }
9833
Richard Trieu3bb8b562014-02-26 02:36:06 +00009834 QualType T = D->getType();
9835 const bool IsArray = T->isArrayType();
9836 const bool IsFunction = T->isFunctionType();
9837
Richard Trieuc1888e02014-06-28 23:25:37 +00009838 // Address of function is used to silence the function warning.
9839 if (IsAddressOf && IsFunction) {
9840 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009841 }
9842
9843 // Found nothing.
9844 if (!IsAddressOf && !IsFunction && !IsArray)
9845 return;
9846
9847 // Pretty print the expression for the diagnostic.
9848 std::string Str;
9849 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00009850 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00009851
9852 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9853 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00009854 enum {
9855 AddressOf,
9856 FunctionPointer,
9857 ArrayPointer
9858 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009859 if (IsAddressOf)
9860 DiagType = AddressOf;
9861 else if (IsFunction)
9862 DiagType = FunctionPointer;
9863 else if (IsArray)
9864 DiagType = ArrayPointer;
9865 else
9866 llvm_unreachable("Could not determine diagnostic.");
9867 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9868 << Range << IsEqual;
9869
9870 if (!IsFunction)
9871 return;
9872
9873 // Suggest '&' to silence the function warning.
9874 Diag(E->getExprLoc(), diag::note_function_warning_silence)
9875 << FixItHint::CreateInsertion(E->getLocStart(), "&");
9876
9877 // Check to see if '()' fixit should be emitted.
9878 QualType ReturnType;
9879 UnresolvedSet<4> NonTemplateOverloads;
9880 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9881 if (ReturnType.isNull())
9882 return;
9883
9884 if (IsCompare) {
9885 // There are two cases here. If there is null constant, the only suggest
9886 // for a pointer return type. If the null is 0, then suggest if the return
9887 // type is a pointer or an integer type.
9888 if (!ReturnType->isPointerType()) {
9889 if (NullKind == Expr::NPCK_ZeroExpression ||
9890 NullKind == Expr::NPCK_ZeroLiteral) {
9891 if (!ReturnType->isIntegerType())
9892 return;
9893 } else {
9894 return;
9895 }
9896 }
9897 } else { // !IsCompare
9898 // For function to bool, only suggest if the function pointer has bool
9899 // return type.
9900 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9901 return;
9902 }
9903 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00009904 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00009905}
9906
John McCallcc7e5bf2010-05-06 08:58:33 +00009907/// Diagnoses "dangerous" implicit conversions within the given
9908/// expression (which is a full expression). Implements -Wconversion
9909/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009910///
9911/// \param CC the "context" location of the implicit conversion, i.e.
9912/// the most location of the syntactic entity requiring the implicit
9913/// conversion
9914void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009915 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00009916 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00009917 return;
9918
9919 // Don't diagnose for value- or type-dependent expressions.
9920 if (E->isTypeDependent() || E->isValueDependent())
9921 return;
9922
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009923 // Check for array bounds violations in cases where the check isn't triggered
9924 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9925 // ArraySubscriptExpr is on the RHS of a variable initialization.
9926 CheckArrayAccess(E);
9927
John McCallacf0ee52010-10-08 02:01:28 +00009928 // This is not the right CC for (e.g.) a variable initialization.
9929 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009930}
9931
Richard Trieu65724892014-11-15 06:37:39 +00009932/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9933/// Input argument E is a logical expression.
9934void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9935 ::CheckBoolLikeConversion(*this, E, CC);
9936}
9937
Richard Smithc406cb72013-01-17 01:17:56 +00009938namespace {
9939/// \brief Visitor for expressions which looks for unsequenced operations on the
9940/// same object.
9941class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009942 typedef EvaluatedExprVisitor<SequenceChecker> Base;
9943
Richard Smithc406cb72013-01-17 01:17:56 +00009944 /// \brief A tree of sequenced regions within an expression. Two regions are
9945 /// unsequenced if one is an ancestor or a descendent of the other. When we
9946 /// finish processing an expression with sequencing, such as a comma
9947 /// expression, we fold its tree nodes into its parent, since they are
9948 /// unsequenced with respect to nodes we will visit later.
9949 class SequenceTree {
9950 struct Value {
9951 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9952 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +00009953 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +00009954 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009955 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00009956
9957 public:
9958 /// \brief A region within an expression which may be sequenced with respect
9959 /// to some other region.
9960 class Seq {
9961 explicit Seq(unsigned N) : Index(N) {}
9962 unsigned Index;
9963 friend class SequenceTree;
9964 public:
9965 Seq() : Index(0) {}
9966 };
9967
9968 SequenceTree() { Values.push_back(Value(0)); }
9969 Seq root() const { return Seq(0); }
9970
9971 /// \brief Create a new sequence of operations, which is an unsequenced
9972 /// subset of \p Parent. This sequence of operations is sequenced with
9973 /// respect to other children of \p Parent.
9974 Seq allocate(Seq Parent) {
9975 Values.push_back(Value(Parent.Index));
9976 return Seq(Values.size() - 1);
9977 }
9978
9979 /// \brief Merge a sequence of operations into its parent.
9980 void merge(Seq S) {
9981 Values[S.Index].Merged = true;
9982 }
9983
9984 /// \brief Determine whether two operations are unsequenced. This operation
9985 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9986 /// should have been merged into its parent as appropriate.
9987 bool isUnsequenced(Seq Cur, Seq Old) {
9988 unsigned C = representative(Cur.Index);
9989 unsigned Target = representative(Old.Index);
9990 while (C >= Target) {
9991 if (C == Target)
9992 return true;
9993 C = Values[C].Parent;
9994 }
9995 return false;
9996 }
9997
9998 private:
9999 /// \brief Pick a representative for a sequence.
10000 unsigned representative(unsigned K) {
10001 if (Values[K].Merged)
10002 // Perform path compression as we go.
10003 return Values[K].Parent = representative(Values[K].Parent);
10004 return K;
10005 }
10006 };
10007
10008 /// An object for which we can track unsequenced uses.
10009 typedef NamedDecl *Object;
10010
10011 /// Different flavors of object usage which we track. We only track the
10012 /// least-sequenced usage of each kind.
10013 enum UsageKind {
10014 /// A read of an object. Multiple unsequenced reads are OK.
10015 UK_Use,
10016 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000010017 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000010018 UK_ModAsValue,
10019 /// A modification of an object which is not sequenced before the value
10020 /// computation of the expression, such as n++.
10021 UK_ModAsSideEffect,
10022
10023 UK_Count = UK_ModAsSideEffect + 1
10024 };
10025
10026 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +000010027 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +000010028 Expr *Use;
10029 SequenceTree::Seq Seq;
10030 };
10031
10032 struct UsageInfo {
10033 UsageInfo() : Diagnosed(false) {}
10034 Usage Uses[UK_Count];
10035 /// Have we issued a diagnostic for this variable already?
10036 bool Diagnosed;
10037 };
10038 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
10039
10040 Sema &SemaRef;
10041 /// Sequenced regions within the expression.
10042 SequenceTree Tree;
10043 /// Declaration modifications and references which we have seen.
10044 UsageInfoMap UsageMap;
10045 /// The region we are currently within.
10046 SequenceTree::Seq Region;
10047 /// Filled in with declarations which were modified as a side-effect
10048 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010049 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +000010050 /// Expressions to check later. We defer checking these to reduce
10051 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010052 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000010053
10054 /// RAII object wrapping the visitation of a sequenced subexpression of an
10055 /// expression. At the end of this process, the side-effects of the evaluation
10056 /// become sequenced with respect to the value computation of the result, so
10057 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10058 /// UK_ModAsValue.
10059 struct SequencedSubexpression {
10060 SequencedSubexpression(SequenceChecker &Self)
10061 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10062 Self.ModAsSideEffect = &ModAsSideEffect;
10063 }
10064 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000010065 for (auto &M : llvm::reverse(ModAsSideEffect)) {
10066 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000010067 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000010068 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10069 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000010070 }
10071 Self.ModAsSideEffect = OldModAsSideEffect;
10072 }
10073
10074 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010075 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
10076 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000010077 };
10078
Richard Smith40238f02013-06-20 22:21:56 +000010079 /// RAII object wrapping the visitation of a subexpression which we might
10080 /// choose to evaluate as a constant. If any subexpression is evaluated and
10081 /// found to be non-constant, this allows us to suppress the evaluation of
10082 /// the outer expression.
10083 class EvaluationTracker {
10084 public:
10085 EvaluationTracker(SequenceChecker &Self)
10086 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
10087 Self.EvalTracker = this;
10088 }
10089 ~EvaluationTracker() {
10090 Self.EvalTracker = Prev;
10091 if (Prev)
10092 Prev->EvalOK &= EvalOK;
10093 }
10094
10095 bool evaluate(const Expr *E, bool &Result) {
10096 if (!EvalOK || E->isValueDependent())
10097 return false;
10098 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10099 return EvalOK;
10100 }
10101
10102 private:
10103 SequenceChecker &Self;
10104 EvaluationTracker *Prev;
10105 bool EvalOK;
10106 } *EvalTracker;
10107
Richard Smithc406cb72013-01-17 01:17:56 +000010108 /// \brief Find the object which is produced by the specified expression,
10109 /// if any.
10110 Object getObject(Expr *E, bool Mod) const {
10111 E = E->IgnoreParenCasts();
10112 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10113 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10114 return getObject(UO->getSubExpr(), Mod);
10115 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10116 if (BO->getOpcode() == BO_Comma)
10117 return getObject(BO->getRHS(), Mod);
10118 if (Mod && BO->isAssignmentOp())
10119 return getObject(BO->getLHS(), Mod);
10120 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10121 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10122 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10123 return ME->getMemberDecl();
10124 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10125 // FIXME: If this is a reference, map through to its value.
10126 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000010127 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010128 }
10129
10130 /// \brief Note that an object was modified or used by an expression.
10131 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10132 Usage &U = UI.Uses[UK];
10133 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10134 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10135 ModAsSideEffect->push_back(std::make_pair(O, U));
10136 U.Use = Ref;
10137 U.Seq = Region;
10138 }
10139 }
10140 /// \brief Check whether a modification or use conflicts with a prior usage.
10141 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10142 bool IsModMod) {
10143 if (UI.Diagnosed)
10144 return;
10145
10146 const Usage &U = UI.Uses[OtherKind];
10147 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10148 return;
10149
10150 Expr *Mod = U.Use;
10151 Expr *ModOrUse = Ref;
10152 if (OtherKind == UK_Use)
10153 std::swap(Mod, ModOrUse);
10154
10155 SemaRef.Diag(Mod->getExprLoc(),
10156 IsModMod ? diag::warn_unsequenced_mod_mod
10157 : diag::warn_unsequenced_mod_use)
10158 << O << SourceRange(ModOrUse->getExprLoc());
10159 UI.Diagnosed = true;
10160 }
10161
10162 void notePreUse(Object O, Expr *Use) {
10163 UsageInfo &U = UsageMap[O];
10164 // Uses conflict with other modifications.
10165 checkUsage(O, U, Use, UK_ModAsValue, false);
10166 }
10167 void notePostUse(Object O, Expr *Use) {
10168 UsageInfo &U = UsageMap[O];
10169 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10170 addUsage(U, O, Use, UK_Use);
10171 }
10172
10173 void notePreMod(Object O, Expr *Mod) {
10174 UsageInfo &U = UsageMap[O];
10175 // Modifications conflict with other modifications and with uses.
10176 checkUsage(O, U, Mod, UK_ModAsValue, true);
10177 checkUsage(O, U, Mod, UK_Use, false);
10178 }
10179 void notePostMod(Object O, Expr *Use, UsageKind UK) {
10180 UsageInfo &U = UsageMap[O];
10181 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10182 addUsage(U, O, Use, UK);
10183 }
10184
10185public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010186 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +000010187 : Base(S.Context), SemaRef(S), Region(Tree.root()),
10188 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010189 Visit(E);
10190 }
10191
10192 void VisitStmt(Stmt *S) {
10193 // Skip all statements which aren't expressions for now.
10194 }
10195
10196 void VisitExpr(Expr *E) {
10197 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000010198 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000010199 }
10200
10201 void VisitCastExpr(CastExpr *E) {
10202 Object O = Object();
10203 if (E->getCastKind() == CK_LValueToRValue)
10204 O = getObject(E->getSubExpr(), false);
10205
10206 if (O)
10207 notePreUse(O, E);
10208 VisitExpr(E);
10209 if (O)
10210 notePostUse(O, E);
10211 }
10212
10213 void VisitBinComma(BinaryOperator *BO) {
10214 // C++11 [expr.comma]p1:
10215 // Every value computation and side effect associated with the left
10216 // expression is sequenced before every value computation and side
10217 // effect associated with the right expression.
10218 SequenceTree::Seq LHS = Tree.allocate(Region);
10219 SequenceTree::Seq RHS = Tree.allocate(Region);
10220 SequenceTree::Seq OldRegion = Region;
10221
10222 {
10223 SequencedSubexpression SeqLHS(*this);
10224 Region = LHS;
10225 Visit(BO->getLHS());
10226 }
10227
10228 Region = RHS;
10229 Visit(BO->getRHS());
10230
10231 Region = OldRegion;
10232
10233 // Forget that LHS and RHS are sequenced. They are both unsequenced
10234 // with respect to other stuff.
10235 Tree.merge(LHS);
10236 Tree.merge(RHS);
10237 }
10238
10239 void VisitBinAssign(BinaryOperator *BO) {
10240 // The modification is sequenced after the value computation of the LHS
10241 // and RHS, so check it before inspecting the operands and update the
10242 // map afterwards.
10243 Object O = getObject(BO->getLHS(), true);
10244 if (!O)
10245 return VisitExpr(BO);
10246
10247 notePreMod(O, BO);
10248
10249 // C++11 [expr.ass]p7:
10250 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10251 // only once.
10252 //
10253 // Therefore, for a compound assignment operator, O is considered used
10254 // everywhere except within the evaluation of E1 itself.
10255 if (isa<CompoundAssignOperator>(BO))
10256 notePreUse(O, BO);
10257
10258 Visit(BO->getLHS());
10259
10260 if (isa<CompoundAssignOperator>(BO))
10261 notePostUse(O, BO);
10262
10263 Visit(BO->getRHS());
10264
Richard Smith83e37bee2013-06-26 23:16:51 +000010265 // C++11 [expr.ass]p1:
10266 // the assignment is sequenced [...] before the value computation of the
10267 // assignment expression.
10268 // C11 6.5.16/3 has no such rule.
10269 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10270 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010271 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010272
Richard Smithc406cb72013-01-17 01:17:56 +000010273 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10274 VisitBinAssign(CAO);
10275 }
10276
10277 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10278 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10279 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10280 Object O = getObject(UO->getSubExpr(), true);
10281 if (!O)
10282 return VisitExpr(UO);
10283
10284 notePreMod(O, UO);
10285 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000010286 // C++11 [expr.pre.incr]p1:
10287 // the expression ++x is equivalent to x+=1
10288 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10289 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010290 }
10291
10292 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10293 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10294 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10295 Object O = getObject(UO->getSubExpr(), true);
10296 if (!O)
10297 return VisitExpr(UO);
10298
10299 notePreMod(O, UO);
10300 Visit(UO->getSubExpr());
10301 notePostMod(O, UO, UK_ModAsSideEffect);
10302 }
10303
10304 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10305 void VisitBinLOr(BinaryOperator *BO) {
10306 // The side-effects of the LHS of an '&&' are sequenced before the
10307 // value computation of the RHS, and hence before the value computation
10308 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10309 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000010310 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010311 {
10312 SequencedSubexpression Sequenced(*this);
10313 Visit(BO->getLHS());
10314 }
10315
10316 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010317 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010318 if (!Result)
10319 Visit(BO->getRHS());
10320 } else {
10321 // Check for unsequenced operations in the RHS, treating it as an
10322 // entirely separate evaluation.
10323 //
10324 // FIXME: If there are operations in the RHS which are unsequenced
10325 // with respect to operations outside the RHS, and those operations
10326 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000010327 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010328 }
Richard Smithc406cb72013-01-17 01:17:56 +000010329 }
10330 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000010331 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010332 {
10333 SequencedSubexpression Sequenced(*this);
10334 Visit(BO->getLHS());
10335 }
10336
10337 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010338 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010339 if (Result)
10340 Visit(BO->getRHS());
10341 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000010342 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010343 }
Richard Smithc406cb72013-01-17 01:17:56 +000010344 }
10345
10346 // Only visit the condition, unless we can be sure which subexpression will
10347 // be chosen.
10348 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000010349 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000010350 {
10351 SequencedSubexpression Sequenced(*this);
10352 Visit(CO->getCond());
10353 }
Richard Smithc406cb72013-01-17 01:17:56 +000010354
10355 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010356 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000010357 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010358 else {
Richard Smithd33f5202013-01-17 23:18:09 +000010359 WorkList.push_back(CO->getTrueExpr());
10360 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010361 }
Richard Smithc406cb72013-01-17 01:17:56 +000010362 }
10363
Richard Smithe3dbfe02013-06-30 10:40:20 +000010364 void VisitCallExpr(CallExpr *CE) {
10365 // C++11 [intro.execution]p15:
10366 // When calling a function [...], every value computation and side effect
10367 // associated with any argument expression, or with the postfix expression
10368 // designating the called function, is sequenced before execution of every
10369 // expression or statement in the body of the function [and thus before
10370 // the value computation of its result].
10371 SequencedSubexpression Sequenced(*this);
10372 Base::VisitCallExpr(CE);
10373
10374 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10375 }
10376
Richard Smithc406cb72013-01-17 01:17:56 +000010377 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010378 // This is a call, so all subexpressions are sequenced before the result.
10379 SequencedSubexpression Sequenced(*this);
10380
Richard Smithc406cb72013-01-17 01:17:56 +000010381 if (!CCE->isListInitialization())
10382 return VisitExpr(CCE);
10383
10384 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010385 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010386 SequenceTree::Seq Parent = Region;
10387 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10388 E = CCE->arg_end();
10389 I != E; ++I) {
10390 Region = Tree.allocate(Parent);
10391 Elts.push_back(Region);
10392 Visit(*I);
10393 }
10394
10395 // Forget that the initializers are sequenced.
10396 Region = Parent;
10397 for (unsigned I = 0; I < Elts.size(); ++I)
10398 Tree.merge(Elts[I]);
10399 }
10400
10401 void VisitInitListExpr(InitListExpr *ILE) {
10402 if (!SemaRef.getLangOpts().CPlusPlus11)
10403 return VisitExpr(ILE);
10404
10405 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010406 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010407 SequenceTree::Seq Parent = Region;
10408 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10409 Expr *E = ILE->getInit(I);
10410 if (!E) continue;
10411 Region = Tree.allocate(Parent);
10412 Elts.push_back(Region);
10413 Visit(E);
10414 }
10415
10416 // Forget that the initializers are sequenced.
10417 Region = Parent;
10418 for (unsigned I = 0; I < Elts.size(); ++I)
10419 Tree.merge(Elts[I]);
10420 }
10421};
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010422} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +000010423
10424void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010425 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000010426 WorkList.push_back(E);
10427 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000010428 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000010429 SequenceChecker(*this, Item, WorkList);
10430 }
Richard Smithc406cb72013-01-17 01:17:56 +000010431}
10432
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010433void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10434 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010435 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000010436 if (!E->isInstantiationDependent())
10437 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010438 if (!IsConstexpr && !E->isValueDependent())
Nick Lewyckye7d6fbd2017-04-29 09:33:46 +000010439 E->EvaluateForOverflow(Context);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010440 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000010441}
10442
John McCall1f425642010-11-11 03:21:53 +000010443void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10444 FieldDecl *BitField,
10445 Expr *Init) {
10446 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10447}
10448
David Majnemer61a5bbf2015-04-07 22:08:51 +000010449static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10450 SourceLocation Loc) {
10451 if (!PType->isVariablyModifiedType())
10452 return;
10453 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10454 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10455 return;
10456 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000010457 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10458 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10459 return;
10460 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000010461 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10462 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10463 return;
10464 }
10465
10466 const ArrayType *AT = S.Context.getAsArrayType(PType);
10467 if (!AT)
10468 return;
10469
10470 if (AT->getSizeModifier() != ArrayType::Star) {
10471 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10472 return;
10473 }
10474
10475 S.Diag(Loc, diag::err_array_star_in_function_definition);
10476}
10477
Mike Stump0c2ec772010-01-21 03:59:47 +000010478/// CheckParmsForFunctionDef - Check that the parameters of the given
10479/// function are appropriate for the definition of a function. This
10480/// takes care of any checks that cannot be performed on the
10481/// declaration itself, e.g., that the types of each of the function
10482/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000010483bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000010484 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010485 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000010486 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010487 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10488 // function declarator that is part of a function definition of
10489 // that function shall not have incomplete type.
10490 //
10491 // This is also C++ [dcl.fct]p6.
10492 if (!Param->isInvalidDecl() &&
10493 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010494 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010495 Param->setInvalidDecl();
10496 HasInvalidParm = true;
10497 }
10498
10499 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10500 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000010501 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000010502 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000010503 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000010504 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000010505 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000010506
10507 // C99 6.7.5.3p12:
10508 // If the function declarator is not part of a definition of that
10509 // function, parameters may have incomplete type and may use the [*]
10510 // notation in their sequences of declarator specifiers to specify
10511 // variable length array types.
10512 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000010513 // FIXME: This diagnostic should point the '[*]' if source-location
10514 // information is added for it.
10515 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010516
10517 // MSVC destroys objects passed by value in the callee. Therefore a
10518 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010519 // object's destructor. However, we don't perform any direct access check
10520 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +000010521 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10522 .getCXXABI()
10523 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +000010524 if (!Param->isInvalidDecl()) {
10525 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10526 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10527 if (!ClassDecl->isInvalidDecl() &&
10528 !ClassDecl->hasIrrelevantDestructor() &&
10529 !ClassDecl->isDependentContext()) {
10530 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10531 MarkFunctionReferenced(Param->getLocation(), Destructor);
10532 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10533 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010534 }
10535 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010536 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010537
10538 // Parameters with the pass_object_size attribute only need to be marked
10539 // constant at function definitions. Because we lack information about
10540 // whether we're on a declaration or definition when we're instantiating the
10541 // attribute, we need to check for constness here.
10542 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10543 if (!Param->getType().isConstQualified())
10544 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10545 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000010546 }
10547
10548 return HasInvalidParm;
10549}
John McCall2b5c1b22010-08-12 21:44:57 +000010550
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010551/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10552/// or MemberExpr.
10553static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10554 ASTContext &Context) {
10555 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10556 return Context.getDeclAlign(DRE->getDecl());
10557
10558 if (const auto *ME = dyn_cast<MemberExpr>(E))
10559 return Context.getDeclAlign(ME->getMemberDecl());
10560
10561 return TypeAlign;
10562}
10563
John McCall2b5c1b22010-08-12 21:44:57 +000010564/// CheckCastAlign - Implements -Wcast-align, which warns when a
10565/// pointer cast increases the alignment requirements.
10566void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10567 // This is actually a lot of work to potentially be doing on every
10568 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010569 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000010570 return;
10571
10572 // Ignore dependent types.
10573 if (T->isDependentType() || Op->getType()->isDependentType())
10574 return;
10575
10576 // Require that the destination be a pointer type.
10577 const PointerType *DestPtr = T->getAs<PointerType>();
10578 if (!DestPtr) return;
10579
10580 // If the destination has alignment 1, we're done.
10581 QualType DestPointee = DestPtr->getPointeeType();
10582 if (DestPointee->isIncompleteType()) return;
10583 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10584 if (DestAlign.isOne()) return;
10585
10586 // Require that the source be a pointer type.
10587 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10588 if (!SrcPtr) return;
10589 QualType SrcPointee = SrcPtr->getPointeeType();
10590
10591 // Whitelist casts from cv void*. We already implicitly
10592 // whitelisted casts to cv void*, since they have alignment 1.
10593 // Also whitelist casts involving incomplete types, which implicitly
10594 // includes 'void'.
10595 if (SrcPointee->isIncompleteType()) return;
10596
10597 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010598
10599 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10600 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10601 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10602 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10603 if (UO->getOpcode() == UO_AddrOf)
10604 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10605 }
10606
John McCall2b5c1b22010-08-12 21:44:57 +000010607 if (SrcAlign >= DestAlign) return;
10608
10609 Diag(TRange.getBegin(), diag::warn_cast_align)
10610 << Op->getType() << T
10611 << static_cast<unsigned>(SrcAlign.getQuantity())
10612 << static_cast<unsigned>(DestAlign.getQuantity())
10613 << TRange << Op->getSourceRange();
10614}
10615
Chandler Carruth28389f02011-08-05 09:10:50 +000010616/// \brief Check whether this array fits the idiom of a size-one tail padded
10617/// array member of a struct.
10618///
10619/// We avoid emitting out-of-bounds access warnings for such arrays as they are
10620/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000010621static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000010622 const NamedDecl *ND) {
10623 if (Size != 1 || !ND) return false;
10624
10625 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10626 if (!FD) return false;
10627
10628 // Don't consider sizes resulting from macro expansions or template argument
10629 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000010630
10631 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010632 while (TInfo) {
10633 TypeLoc TL = TInfo->getTypeLoc();
10634 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000010635 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10636 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010637 TInfo = TDL->getTypeSourceInfo();
10638 continue;
10639 }
David Blaikie6adc78e2013-02-18 22:06:02 +000010640 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10641 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000010642 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10643 return false;
10644 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010645 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000010646 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010647
10648 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000010649 if (!RD) return false;
10650 if (RD->isUnion()) return false;
10651 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10652 if (!CRD->isStandardLayout()) return false;
10653 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010654
Benjamin Kramer8c543672011-08-06 03:04:42 +000010655 // See if this is the last field decl in the record.
10656 const Decl *D = FD;
10657 while ((D = D->getNextDeclInContext()))
10658 if (isa<FieldDecl>(D))
10659 return false;
10660 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000010661}
10662
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010663void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010664 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000010665 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010666 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010667 if (IndexExpr->isValueDependent())
10668 return;
10669
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010670 const Type *EffectiveType =
10671 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010672 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010673 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010674 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010675 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000010676 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000010677
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010678 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000010679 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000010680 return;
Richard Smith13f67182011-12-16 19:31:14 +000010681 if (IndexNegated)
10682 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000010683
Craig Topperc3ec1492014-05-26 06:22:03 +000010684 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000010685 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10686 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +000010687 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +000010688 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +000010689
Ted Kremeneke4b316c2011-02-23 23:06:04 +000010690 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010691 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000010692 if (!size.isStrictlyPositive())
10693 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010694
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010695 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000010696 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010697 // Make sure we're comparing apples to apples when comparing index to size
10698 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10699 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000010700 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000010701 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010702 if (ptrarith_typesize != array_typesize) {
10703 // There's a cast to a different size type involved
10704 uint64_t ratio = array_typesize / ptrarith_typesize;
10705 // TODO: Be smarter about handling cases where array_typesize is not a
10706 // multiple of ptrarith_typesize
10707 if (ptrarith_typesize * ratio == array_typesize)
10708 size *= llvm::APInt(size.getBitWidth(), ratio);
10709 }
10710 }
10711
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010712 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010713 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010714 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010715 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010716
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010717 // For array subscripting the index must be less than size, but for pointer
10718 // arithmetic also allow the index (offset) to be equal to size since
10719 // computing the next address after the end of the array is legal and
10720 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010721 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000010722 return;
10723
10724 // Also don't warn for arrays of size 1 which are members of some
10725 // structure. These are often used to approximate flexible arrays in C89
10726 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010727 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000010728 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010729
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010730 // Suppress the warning if the subscript expression (as identified by the
10731 // ']' location) and the index expression are both from macro expansions
10732 // within a system header.
10733 if (ASE) {
10734 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10735 ASE->getRBracketLoc());
10736 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10737 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10738 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000010739 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010740 return;
10741 }
10742 }
10743
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010744 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010745 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010746 DiagID = diag::warn_array_index_exceeds_bounds;
10747
10748 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10749 PDiag(DiagID) << index.toString(10, true)
10750 << size.toString(10, true)
10751 << (unsigned)size.getLimitedValue(~0U)
10752 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010753 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010754 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010755 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010756 DiagID = diag::warn_ptr_arith_precedes_bounds;
10757 if (index.isNegative()) index = -index;
10758 }
10759
10760 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10761 PDiag(DiagID) << index.toString(10, true)
10762 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000010763 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000010764
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000010765 if (!ND) {
10766 // Try harder to find a NamedDecl to point at in the note.
10767 while (const ArraySubscriptExpr *ASE =
10768 dyn_cast<ArraySubscriptExpr>(BaseExpr))
10769 BaseExpr = ASE->getBase()->IgnoreParenCasts();
10770 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10771 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10772 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10773 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10774 }
10775
Chandler Carruth1af88f12011-02-17 21:10:52 +000010776 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010777 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10778 PDiag(diag::note_array_index_out_of_bounds)
10779 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000010780}
10781
Ted Kremenekdf26df72011-03-01 18:41:00 +000010782void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010783 int AllowOnePastEnd = 0;
10784 while (expr) {
10785 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000010786 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010787 case Stmt::ArraySubscriptExprClass: {
10788 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010789 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010790 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +000010791 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010792 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010793 case Stmt::OMPArraySectionExprClass: {
10794 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10795 if (ASE->getLowerBound())
10796 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10797 /*ASE=*/nullptr, AllowOnePastEnd > 0);
10798 return;
10799 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010800 case Stmt::UnaryOperatorClass: {
10801 // Only unwrap the * and & unary operators
10802 const UnaryOperator *UO = cast<UnaryOperator>(expr);
10803 expr = UO->getSubExpr();
10804 switch (UO->getOpcode()) {
10805 case UO_AddrOf:
10806 AllowOnePastEnd++;
10807 break;
10808 case UO_Deref:
10809 AllowOnePastEnd--;
10810 break;
10811 default:
10812 return;
10813 }
10814 break;
10815 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010816 case Stmt::ConditionalOperatorClass: {
10817 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10818 if (const Expr *lhs = cond->getLHS())
10819 CheckArrayAccess(lhs);
10820 if (const Expr *rhs = cond->getRHS())
10821 CheckArrayAccess(rhs);
10822 return;
10823 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000010824 case Stmt::CXXOperatorCallExprClass: {
10825 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
10826 for (const auto *Arg : OCE->arguments())
10827 CheckArrayAccess(Arg);
10828 return;
10829 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010830 default:
10831 return;
10832 }
Peter Collingbourne91147592011-04-15 00:35:48 +000010833 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010834}
John McCall31168b02011-06-15 23:02:42 +000010835
10836//===--- CHECK: Objective-C retain cycles ----------------------------------//
10837
10838namespace {
10839 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +000010840 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +000010841 VarDecl *Variable;
10842 SourceRange Range;
10843 SourceLocation Loc;
10844 bool Indirect;
10845
10846 void setLocsFrom(Expr *e) {
10847 Loc = e->getExprLoc();
10848 Range = e->getSourceRange();
10849 }
10850 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010851} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010852
10853/// Consider whether capturing the given variable can possibly lead to
10854/// a retain cycle.
10855static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010856 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000010857 // lifetime. In MRR, it's captured strongly if the variable is
10858 // __block and has an appropriate type.
10859 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10860 return false;
10861
10862 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010863 if (ref)
10864 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000010865 return true;
10866}
10867
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010868static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000010869 while (true) {
10870 e = e->IgnoreParens();
10871 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10872 switch (cast->getCastKind()) {
10873 case CK_BitCast:
10874 case CK_LValueBitCast:
10875 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000010876 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000010877 e = cast->getSubExpr();
10878 continue;
10879
John McCall31168b02011-06-15 23:02:42 +000010880 default:
10881 return false;
10882 }
10883 }
10884
10885 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10886 ObjCIvarDecl *ivar = ref->getDecl();
10887 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10888 return false;
10889
10890 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010891 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000010892 return false;
10893
10894 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10895 owner.Indirect = true;
10896 return true;
10897 }
10898
10899 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10900 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10901 if (!var) return false;
10902 return considerVariable(var, ref, owner);
10903 }
10904
John McCall31168b02011-06-15 23:02:42 +000010905 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10906 if (member->isArrow()) return false;
10907
10908 // Don't count this as an indirect ownership.
10909 e = member->getBase();
10910 continue;
10911 }
10912
John McCallfe96e0b2011-11-06 09:01:30 +000010913 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10914 // Only pay attention to pseudo-objects on property references.
10915 ObjCPropertyRefExpr *pre
10916 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10917 ->IgnoreParens());
10918 if (!pre) return false;
10919 if (pre->isImplicitProperty()) return false;
10920 ObjCPropertyDecl *property = pre->getExplicitProperty();
10921 if (!property->isRetaining() &&
10922 !(property->getPropertyIvarDecl() &&
10923 property->getPropertyIvarDecl()->getType()
10924 .getObjCLifetime() == Qualifiers::OCL_Strong))
10925 return false;
10926
10927 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010928 if (pre->isSuperReceiver()) {
10929 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10930 if (!owner.Variable)
10931 return false;
10932 owner.Loc = pre->getLocation();
10933 owner.Range = pre->getSourceRange();
10934 return true;
10935 }
John McCallfe96e0b2011-11-06 09:01:30 +000010936 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10937 ->getSourceExpr());
10938 continue;
10939 }
10940
John McCall31168b02011-06-15 23:02:42 +000010941 // Array ivars?
10942
10943 return false;
10944 }
10945}
10946
10947namespace {
10948 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10949 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10950 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010951 Context(Context), Variable(variable), Capturer(nullptr),
10952 VarWillBeReased(false) {}
10953 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000010954 VarDecl *Variable;
10955 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010956 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +000010957
10958 void VisitDeclRefExpr(DeclRefExpr *ref) {
10959 if (ref->getDecl() == Variable && !Capturer)
10960 Capturer = ref;
10961 }
10962
John McCall31168b02011-06-15 23:02:42 +000010963 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10964 if (Capturer) return;
10965 Visit(ref->getBase());
10966 if (Capturer && ref->isFreeIvar())
10967 Capturer = ref;
10968 }
10969
10970 void VisitBlockExpr(BlockExpr *block) {
10971 // Look inside nested blocks
10972 if (block->getBlockDecl()->capturesVariable(Variable))
10973 Visit(block->getBlockDecl()->getBody());
10974 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000010975
10976 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
10977 if (Capturer) return;
10978 if (OVE->getSourceExpr())
10979 Visit(OVE->getSourceExpr());
10980 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010981 void VisitBinaryOperator(BinaryOperator *BinOp) {
10982 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
10983 return;
10984 Expr *LHS = BinOp->getLHS();
10985 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
10986 if (DRE->getDecl() != Variable)
10987 return;
10988 if (Expr *RHS = BinOp->getRHS()) {
10989 RHS = RHS->IgnoreParenCasts();
10990 llvm::APSInt Value;
10991 VarWillBeReased =
10992 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
10993 }
10994 }
10995 }
John McCall31168b02011-06-15 23:02:42 +000010996 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010997} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010998
10999/// Check whether the given argument is a block which captures a
11000/// variable.
11001static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11002 assert(owner.Variable && owner.Loc.isValid());
11003
11004 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000011005
11006 // Look through [^{...} copy] and Block_copy(^{...}).
11007 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11008 Selector Cmd = ME->getSelector();
11009 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11010 e = ME->getInstanceReceiver();
11011 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000011012 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000011013 e = e->IgnoreParenCasts();
11014 }
11015 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11016 if (CE->getNumArgs() == 1) {
11017 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000011018 if (Fn) {
11019 const IdentifierInfo *FnI = Fn->getIdentifier();
11020 if (FnI && FnI->isStr("_Block_copy")) {
11021 e = CE->getArg(0)->IgnoreParenCasts();
11022 }
11023 }
Jordan Rose67e887c2012-09-17 17:54:30 +000011024 }
11025 }
11026
John McCall31168b02011-06-15 23:02:42 +000011027 BlockExpr *block = dyn_cast<BlockExpr>(e);
11028 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000011029 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011030
11031 FindCaptureVisitor visitor(S.Context, owner.Variable);
11032 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011033 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000011034}
11035
11036static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11037 RetainCycleOwner &owner) {
11038 assert(capturer);
11039 assert(owner.Variable && owner.Loc.isValid());
11040
11041 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11042 << owner.Variable << capturer->getSourceRange();
11043 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11044 << owner.Indirect << owner.Range;
11045}
11046
11047/// Check for a keyword selector that starts with the word 'add' or
11048/// 'set'.
11049static bool isSetterLikeSelector(Selector sel) {
11050 if (sel.isUnarySelector()) return false;
11051
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011052 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000011053 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011054 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000011055 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011056 else if (str.startswith("add")) {
11057 // Specially whitelist 'addOperationWithBlock:'.
11058 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11059 return false;
11060 str = str.substr(3);
11061 }
John McCall31168b02011-06-15 23:02:42 +000011062 else
11063 return false;
11064
11065 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000011066 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000011067}
11068
Benjamin Kramer3a743452015-03-09 15:03:32 +000011069static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11070 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011071 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11072 Message->getReceiverInterface(),
11073 NSAPI::ClassId_NSMutableArray);
11074 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011075 return None;
11076 }
11077
11078 Selector Sel = Message->getSelector();
11079
11080 Optional<NSAPI::NSArrayMethodKind> MKOpt =
11081 S.NSAPIObj->getNSArrayMethodKind(Sel);
11082 if (!MKOpt) {
11083 return None;
11084 }
11085
11086 NSAPI::NSArrayMethodKind MK = *MKOpt;
11087
11088 switch (MK) {
11089 case NSAPI::NSMutableArr_addObject:
11090 case NSAPI::NSMutableArr_insertObjectAtIndex:
11091 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11092 return 0;
11093 case NSAPI::NSMutableArr_replaceObjectAtIndex:
11094 return 1;
11095
11096 default:
11097 return None;
11098 }
11099
11100 return None;
11101}
11102
11103static
11104Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11105 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011106 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11107 Message->getReceiverInterface(),
11108 NSAPI::ClassId_NSMutableDictionary);
11109 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011110 return None;
11111 }
11112
11113 Selector Sel = Message->getSelector();
11114
11115 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11116 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11117 if (!MKOpt) {
11118 return None;
11119 }
11120
11121 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11122
11123 switch (MK) {
11124 case NSAPI::NSMutableDict_setObjectForKey:
11125 case NSAPI::NSMutableDict_setValueForKey:
11126 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11127 return 0;
11128
11129 default:
11130 return None;
11131 }
11132
11133 return None;
11134}
11135
11136static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011137 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11138 Message->getReceiverInterface(),
11139 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000011140
Alex Denisov5dfac812015-08-06 04:51:14 +000011141 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11142 Message->getReceiverInterface(),
11143 NSAPI::ClassId_NSMutableOrderedSet);
11144 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011145 return None;
11146 }
11147
11148 Selector Sel = Message->getSelector();
11149
11150 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11151 if (!MKOpt) {
11152 return None;
11153 }
11154
11155 NSAPI::NSSetMethodKind MK = *MKOpt;
11156
11157 switch (MK) {
11158 case NSAPI::NSMutableSet_addObject:
11159 case NSAPI::NSOrderedSet_setObjectAtIndex:
11160 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11161 case NSAPI::NSOrderedSet_insertObjectAtIndex:
11162 return 0;
11163 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11164 return 1;
11165 }
11166
11167 return None;
11168}
11169
11170void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11171 if (!Message->isInstanceMessage()) {
11172 return;
11173 }
11174
11175 Optional<int> ArgOpt;
11176
11177 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11178 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11179 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11180 return;
11181 }
11182
11183 int ArgIndex = *ArgOpt;
11184
Alex Denisove1d882c2015-03-04 17:55:52 +000011185 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11186 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11187 Arg = OE->getSourceExpr()->IgnoreImpCasts();
11188 }
11189
Alex Denisov5dfac812015-08-06 04:51:14 +000011190 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011191 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011192 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011193 Diag(Message->getSourceRange().getBegin(),
11194 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000011195 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000011196 }
11197 }
Alex Denisov5dfac812015-08-06 04:51:14 +000011198 } else {
11199 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11200
11201 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11202 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11203 }
11204
11205 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11206 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11207 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11208 ValueDecl *Decl = ReceiverRE->getDecl();
11209 Diag(Message->getSourceRange().getBegin(),
11210 diag::warn_objc_circular_container)
11211 << Decl->getName() << Decl->getName();
11212 if (!ArgRE->isObjCSelfExpr()) {
11213 Diag(Decl->getLocation(),
11214 diag::note_objc_circular_container_declared_here)
11215 << Decl->getName();
11216 }
11217 }
11218 }
11219 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11220 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11221 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11222 ObjCIvarDecl *Decl = IvarRE->getDecl();
11223 Diag(Message->getSourceRange().getBegin(),
11224 diag::warn_objc_circular_container)
11225 << Decl->getName() << Decl->getName();
11226 Diag(Decl->getLocation(),
11227 diag::note_objc_circular_container_declared_here)
11228 << Decl->getName();
11229 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011230 }
11231 }
11232 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011233}
11234
John McCall31168b02011-06-15 23:02:42 +000011235/// Check a message send to see if it's likely to cause a retain cycle.
11236void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11237 // Only check instance methods whose selector looks like a setter.
11238 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11239 return;
11240
11241 // Try to find a variable that the receiver is strongly owned by.
11242 RetainCycleOwner owner;
11243 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011244 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000011245 return;
11246 } else {
11247 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11248 owner.Variable = getCurMethodDecl()->getSelfDecl();
11249 owner.Loc = msg->getSuperLoc();
11250 owner.Range = msg->getSuperLoc();
11251 }
11252
11253 // Check whether the receiver is captured by any of the arguments.
11254 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
11255 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
11256 return diagnoseRetainCycle(*this, capturer, owner);
11257}
11258
11259/// Check a property assign to see if it's likely to cause a retain cycle.
11260void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11261 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011262 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000011263 return;
11264
11265 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11266 diagnoseRetainCycle(*this, capturer, owner);
11267}
11268
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011269void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11270 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000011271 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011272 return;
11273
11274 // Because we don't have an expression for the variable, we have to set the
11275 // location explicitly here.
11276 Owner.Loc = Var->getLocation();
11277 Owner.Range = Var->getSourceRange();
11278
11279 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11280 diagnoseRetainCycle(*this, Capturer, Owner);
11281}
11282
Ted Kremenek9304da92012-12-21 08:04:28 +000011283static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11284 Expr *RHS, bool isProperty) {
11285 // Check if RHS is an Objective-C object literal, which also can get
11286 // immediately zapped in a weak reference. Note that we explicitly
11287 // allow ObjCStringLiterals, since those are designed to never really die.
11288 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011289
Ted Kremenek64873352012-12-21 22:46:35 +000011290 // This enum needs to match with the 'select' in
11291 // warn_objc_arc_literal_assign (off-by-1).
11292 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11293 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11294 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011295
11296 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000011297 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000011298 << (isProperty ? 0 : 1)
11299 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011300
11301 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000011302}
11303
Ted Kremenekc1f014a2012-12-21 19:45:30 +000011304static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11305 Qualifiers::ObjCLifetime LT,
11306 Expr *RHS, bool isProperty) {
11307 // Strip off any implicit cast added to get to the one ARC-specific.
11308 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11309 if (cast->getCastKind() == CK_ARCConsumeObject) {
11310 S.Diag(Loc, diag::warn_arc_retained_assign)
11311 << (LT == Qualifiers::OCL_ExplicitNone)
11312 << (isProperty ? 0 : 1)
11313 << RHS->getSourceRange();
11314 return true;
11315 }
11316 RHS = cast->getSubExpr();
11317 }
11318
11319 if (LT == Qualifiers::OCL_Weak &&
11320 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11321 return true;
11322
11323 return false;
11324}
11325
Ted Kremenekb36234d2012-12-21 08:04:20 +000011326bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11327 QualType LHS, Expr *RHS) {
11328 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11329
11330 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11331 return false;
11332
11333 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11334 return true;
11335
11336 return false;
11337}
11338
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011339void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11340 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011341 QualType LHSType;
11342 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011343 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011344 ObjCPropertyRefExpr *PRE
11345 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11346 if (PRE && !PRE->isImplicitProperty()) {
11347 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11348 if (PD)
11349 LHSType = PD->getType();
11350 }
11351
11352 if (LHSType.isNull())
11353 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000011354
11355 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11356
11357 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011358 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000011359 getCurFunction()->markSafeWeakUse(LHS);
11360 }
11361
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011362 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11363 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000011364
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011365 // FIXME. Check for other life times.
11366 if (LT != Qualifiers::OCL_None)
11367 return;
11368
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011369 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011370 if (PRE->isImplicitProperty())
11371 return;
11372 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11373 if (!PD)
11374 return;
11375
Bill Wendling44426052012-12-20 19:22:21 +000011376 unsigned Attributes = PD->getPropertyAttributes();
11377 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011378 // when 'assign' attribute was not explicitly specified
11379 // by user, ignore it and rely on property type itself
11380 // for lifetime info.
11381 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11382 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11383 LHSType->isObjCRetainableType())
11384 return;
11385
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011386 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000011387 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011388 Diag(Loc, diag::warn_arc_retained_property_assign)
11389 << RHS->getSourceRange();
11390 return;
11391 }
11392 RHS = cast->getSubExpr();
11393 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011394 }
Bill Wendling44426052012-12-20 19:22:21 +000011395 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000011396 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11397 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000011398 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011399 }
11400}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011401
11402//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11403
11404namespace {
11405bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11406 SourceLocation StmtLoc,
11407 const NullStmt *Body) {
11408 // Do not warn if the body is a macro that expands to nothing, e.g:
11409 //
11410 // #define CALL(x)
11411 // if (condition)
11412 // CALL(0);
11413 //
11414 if (Body->hasLeadingEmptyMacro())
11415 return false;
11416
11417 // Get line numbers of statement and body.
11418 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000011419 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011420 &StmtLineInvalid);
11421 if (StmtLineInvalid)
11422 return false;
11423
11424 bool BodyLineInvalid;
11425 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11426 &BodyLineInvalid);
11427 if (BodyLineInvalid)
11428 return false;
11429
11430 // Warn if null statement and body are on the same line.
11431 if (StmtLine != BodyLine)
11432 return false;
11433
11434 return true;
11435}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011436} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011437
11438void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11439 const Stmt *Body,
11440 unsigned DiagID) {
11441 // Since this is a syntactic check, don't emit diagnostic for template
11442 // instantiations, this just adds noise.
11443 if (CurrentInstantiationScope)
11444 return;
11445
11446 // The body should be a null statement.
11447 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11448 if (!NBody)
11449 return;
11450
11451 // Do the usual checks.
11452 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11453 return;
11454
11455 Diag(NBody->getSemiLoc(), DiagID);
11456 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11457}
11458
11459void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11460 const Stmt *PossibleBody) {
11461 assert(!CurrentInstantiationScope); // Ensured by caller
11462
11463 SourceLocation StmtLoc;
11464 const Stmt *Body;
11465 unsigned DiagID;
11466 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11467 StmtLoc = FS->getRParenLoc();
11468 Body = FS->getBody();
11469 DiagID = diag::warn_empty_for_body;
11470 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11471 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11472 Body = WS->getBody();
11473 DiagID = diag::warn_empty_while_body;
11474 } else
11475 return; // Neither `for' nor `while'.
11476
11477 // The body should be a null statement.
11478 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11479 if (!NBody)
11480 return;
11481
11482 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011483 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011484 return;
11485
11486 // Do the usual checks.
11487 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11488 return;
11489
11490 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11491 // noise level low, emit diagnostics only if for/while is followed by a
11492 // CompoundStmt, e.g.:
11493 // for (int i = 0; i < n; i++);
11494 // {
11495 // a(i);
11496 // }
11497 // or if for/while is followed by a statement with more indentation
11498 // than for/while itself:
11499 // for (int i = 0; i < n; i++);
11500 // a(i);
11501 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11502 if (!ProbableTypo) {
11503 bool BodyColInvalid;
11504 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11505 PossibleBody->getLocStart(),
11506 &BodyColInvalid);
11507 if (BodyColInvalid)
11508 return;
11509
11510 bool StmtColInvalid;
11511 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11512 S->getLocStart(),
11513 &StmtColInvalid);
11514 if (StmtColInvalid)
11515 return;
11516
11517 if (BodyCol > StmtCol)
11518 ProbableTypo = true;
11519 }
11520
11521 if (ProbableTypo) {
11522 Diag(NBody->getSemiLoc(), DiagID);
11523 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11524 }
11525}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011526
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011527//===--- CHECK: Warn on self move with std::move. -------------------------===//
11528
11529/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11530void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11531 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011532 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11533 return;
11534
Richard Smith51ec0cf2017-02-21 01:17:38 +000011535 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011536 return;
11537
11538 // Strip parens and casts away.
11539 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11540 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11541
11542 // Check for a call expression
11543 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11544 if (!CE || CE->getNumArgs() != 1)
11545 return;
11546
11547 // Check for a call to std::move
11548 const FunctionDecl *FD = CE->getDirectCallee();
11549 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11550 !FD->getIdentifier()->isStr("move"))
11551 return;
11552
11553 // Get argument from std::move
11554 RHSExpr = CE->getArg(0);
11555
11556 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11557 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11558
11559 // Two DeclRefExpr's, check that the decls are the same.
11560 if (LHSDeclRef && RHSDeclRef) {
11561 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11562 return;
11563 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11564 RHSDeclRef->getDecl()->getCanonicalDecl())
11565 return;
11566
11567 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11568 << LHSExpr->getSourceRange()
11569 << RHSExpr->getSourceRange();
11570 return;
11571 }
11572
11573 // Member variables require a different approach to check for self moves.
11574 // MemberExpr's are the same if every nested MemberExpr refers to the same
11575 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11576 // the base Expr's are CXXThisExpr's.
11577 const Expr *LHSBase = LHSExpr;
11578 const Expr *RHSBase = RHSExpr;
11579 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11580 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11581 if (!LHSME || !RHSME)
11582 return;
11583
11584 while (LHSME && RHSME) {
11585 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11586 RHSME->getMemberDecl()->getCanonicalDecl())
11587 return;
11588
11589 LHSBase = LHSME->getBase();
11590 RHSBase = RHSME->getBase();
11591 LHSME = dyn_cast<MemberExpr>(LHSBase);
11592 RHSME = dyn_cast<MemberExpr>(RHSBase);
11593 }
11594
11595 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11596 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11597 if (LHSDeclRef && RHSDeclRef) {
11598 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11599 return;
11600 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11601 RHSDeclRef->getDecl()->getCanonicalDecl())
11602 return;
11603
11604 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11605 << LHSExpr->getSourceRange()
11606 << RHSExpr->getSourceRange();
11607 return;
11608 }
11609
11610 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11611 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11612 << LHSExpr->getSourceRange()
11613 << RHSExpr->getSourceRange();
11614}
11615
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011616//===--- Layout compatibility ----------------------------------------------//
11617
11618namespace {
11619
11620bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11621
11622/// \brief Check if two enumeration types are layout-compatible.
11623bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11624 // C++11 [dcl.enum] p8:
11625 // Two enumeration types are layout-compatible if they have the same
11626 // underlying type.
11627 return ED1->isComplete() && ED2->isComplete() &&
11628 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11629}
11630
11631/// \brief Check if two fields are layout-compatible.
11632bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11633 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11634 return false;
11635
11636 if (Field1->isBitField() != Field2->isBitField())
11637 return false;
11638
11639 if (Field1->isBitField()) {
11640 // Make sure that the bit-fields are the same length.
11641 unsigned Bits1 = Field1->getBitWidthValue(C);
11642 unsigned Bits2 = Field2->getBitWidthValue(C);
11643
11644 if (Bits1 != Bits2)
11645 return false;
11646 }
11647
11648 return true;
11649}
11650
11651/// \brief Check if two standard-layout structs are layout-compatible.
11652/// (C++11 [class.mem] p17)
11653bool isLayoutCompatibleStruct(ASTContext &C,
11654 RecordDecl *RD1,
11655 RecordDecl *RD2) {
11656 // If both records are C++ classes, check that base classes match.
11657 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11658 // If one of records is a CXXRecordDecl we are in C++ mode,
11659 // thus the other one is a CXXRecordDecl, too.
11660 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11661 // Check number of base classes.
11662 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11663 return false;
11664
11665 // Check the base classes.
11666 for (CXXRecordDecl::base_class_const_iterator
11667 Base1 = D1CXX->bases_begin(),
11668 BaseEnd1 = D1CXX->bases_end(),
11669 Base2 = D2CXX->bases_begin();
11670 Base1 != BaseEnd1;
11671 ++Base1, ++Base2) {
11672 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11673 return false;
11674 }
11675 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11676 // If only RD2 is a C++ class, it should have zero base classes.
11677 if (D2CXX->getNumBases() > 0)
11678 return false;
11679 }
11680
11681 // Check the fields.
11682 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11683 Field2End = RD2->field_end(),
11684 Field1 = RD1->field_begin(),
11685 Field1End = RD1->field_end();
11686 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11687 if (!isLayoutCompatible(C, *Field1, *Field2))
11688 return false;
11689 }
11690 if (Field1 != Field1End || Field2 != Field2End)
11691 return false;
11692
11693 return true;
11694}
11695
11696/// \brief Check if two standard-layout unions are layout-compatible.
11697/// (C++11 [class.mem] p18)
11698bool isLayoutCompatibleUnion(ASTContext &C,
11699 RecordDecl *RD1,
11700 RecordDecl *RD2) {
11701 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011702 for (auto *Field2 : RD2->fields())
11703 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011704
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011705 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011706 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11707 I = UnmatchedFields.begin(),
11708 E = UnmatchedFields.end();
11709
11710 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011711 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011712 bool Result = UnmatchedFields.erase(*I);
11713 (void) Result;
11714 assert(Result);
11715 break;
11716 }
11717 }
11718 if (I == E)
11719 return false;
11720 }
11721
11722 return UnmatchedFields.empty();
11723}
11724
11725bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11726 if (RD1->isUnion() != RD2->isUnion())
11727 return false;
11728
11729 if (RD1->isUnion())
11730 return isLayoutCompatibleUnion(C, RD1, RD2);
11731 else
11732 return isLayoutCompatibleStruct(C, RD1, RD2);
11733}
11734
11735/// \brief Check if two types are layout-compatible in C++11 sense.
11736bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11737 if (T1.isNull() || T2.isNull())
11738 return false;
11739
11740 // C++11 [basic.types] p11:
11741 // If two types T1 and T2 are the same type, then T1 and T2 are
11742 // layout-compatible types.
11743 if (C.hasSameType(T1, T2))
11744 return true;
11745
11746 T1 = T1.getCanonicalType().getUnqualifiedType();
11747 T2 = T2.getCanonicalType().getUnqualifiedType();
11748
11749 const Type::TypeClass TC1 = T1->getTypeClass();
11750 const Type::TypeClass TC2 = T2->getTypeClass();
11751
11752 if (TC1 != TC2)
11753 return false;
11754
11755 if (TC1 == Type::Enum) {
11756 return isLayoutCompatible(C,
11757 cast<EnumType>(T1)->getDecl(),
11758 cast<EnumType>(T2)->getDecl());
11759 } else if (TC1 == Type::Record) {
11760 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11761 return false;
11762
11763 return isLayoutCompatible(C,
11764 cast<RecordType>(T1)->getDecl(),
11765 cast<RecordType>(T2)->getDecl());
11766 }
11767
11768 return false;
11769}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011770} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011771
11772//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11773
11774namespace {
11775/// \brief Given a type tag expression find the type tag itself.
11776///
11777/// \param TypeExpr Type tag expression, as it appears in user's code.
11778///
11779/// \param VD Declaration of an identifier that appears in a type tag.
11780///
11781/// \param MagicValue Type tag magic value.
11782bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11783 const ValueDecl **VD, uint64_t *MagicValue) {
11784 while(true) {
11785 if (!TypeExpr)
11786 return false;
11787
11788 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11789
11790 switch (TypeExpr->getStmtClass()) {
11791 case Stmt::UnaryOperatorClass: {
11792 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11793 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11794 TypeExpr = UO->getSubExpr();
11795 continue;
11796 }
11797 return false;
11798 }
11799
11800 case Stmt::DeclRefExprClass: {
11801 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11802 *VD = DRE->getDecl();
11803 return true;
11804 }
11805
11806 case Stmt::IntegerLiteralClass: {
11807 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11808 llvm::APInt MagicValueAPInt = IL->getValue();
11809 if (MagicValueAPInt.getActiveBits() <= 64) {
11810 *MagicValue = MagicValueAPInt.getZExtValue();
11811 return true;
11812 } else
11813 return false;
11814 }
11815
11816 case Stmt::BinaryConditionalOperatorClass:
11817 case Stmt::ConditionalOperatorClass: {
11818 const AbstractConditionalOperator *ACO =
11819 cast<AbstractConditionalOperator>(TypeExpr);
11820 bool Result;
11821 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11822 if (Result)
11823 TypeExpr = ACO->getTrueExpr();
11824 else
11825 TypeExpr = ACO->getFalseExpr();
11826 continue;
11827 }
11828 return false;
11829 }
11830
11831 case Stmt::BinaryOperatorClass: {
11832 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11833 if (BO->getOpcode() == BO_Comma) {
11834 TypeExpr = BO->getRHS();
11835 continue;
11836 }
11837 return false;
11838 }
11839
11840 default:
11841 return false;
11842 }
11843 }
11844}
11845
11846/// \brief Retrieve the C type corresponding to type tag TypeExpr.
11847///
11848/// \param TypeExpr Expression that specifies a type tag.
11849///
11850/// \param MagicValues Registered magic values.
11851///
11852/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11853/// kind.
11854///
11855/// \param TypeInfo Information about the corresponding C type.
11856///
11857/// \returns true if the corresponding C type was found.
11858bool GetMatchingCType(
11859 const IdentifierInfo *ArgumentKind,
11860 const Expr *TypeExpr, const ASTContext &Ctx,
11861 const llvm::DenseMap<Sema::TypeTagMagicValue,
11862 Sema::TypeTagData> *MagicValues,
11863 bool &FoundWrongKind,
11864 Sema::TypeTagData &TypeInfo) {
11865 FoundWrongKind = false;
11866
11867 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000011868 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011869
11870 uint64_t MagicValue;
11871
11872 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11873 return false;
11874
11875 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000011876 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011877 if (I->getArgumentKind() != ArgumentKind) {
11878 FoundWrongKind = true;
11879 return false;
11880 }
11881 TypeInfo.Type = I->getMatchingCType();
11882 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11883 TypeInfo.MustBeNull = I->getMustBeNull();
11884 return true;
11885 }
11886 return false;
11887 }
11888
11889 if (!MagicValues)
11890 return false;
11891
11892 llvm::DenseMap<Sema::TypeTagMagicValue,
11893 Sema::TypeTagData>::const_iterator I =
11894 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11895 if (I == MagicValues->end())
11896 return false;
11897
11898 TypeInfo = I->second;
11899 return true;
11900}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011901} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011902
11903void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11904 uint64_t MagicValue, QualType Type,
11905 bool LayoutCompatible,
11906 bool MustBeNull) {
11907 if (!TypeTagForDatatypeMagicValues)
11908 TypeTagForDatatypeMagicValues.reset(
11909 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11910
11911 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11912 (*TypeTagForDatatypeMagicValues)[Magic] =
11913 TypeTagData(Type, LayoutCompatible, MustBeNull);
11914}
11915
11916namespace {
11917bool IsSameCharType(QualType T1, QualType T2) {
11918 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11919 if (!BT1)
11920 return false;
11921
11922 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11923 if (!BT2)
11924 return false;
11925
11926 BuiltinType::Kind T1Kind = BT1->getKind();
11927 BuiltinType::Kind T2Kind = BT2->getKind();
11928
11929 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
11930 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
11931 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11932 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11933}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011934} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011935
11936void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11937 const Expr * const *ExprArgs) {
11938 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11939 bool IsPointerAttr = Attr->getIsPointer();
11940
11941 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11942 bool FoundWrongKind;
11943 TypeTagData TypeInfo;
11944 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11945 TypeTagForDatatypeMagicValues.get(),
11946 FoundWrongKind, TypeInfo)) {
11947 if (FoundWrongKind)
11948 Diag(TypeTagExpr->getExprLoc(),
11949 diag::warn_type_tag_for_datatype_wrong_kind)
11950 << TypeTagExpr->getSourceRange();
11951 return;
11952 }
11953
11954 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11955 if (IsPointerAttr) {
11956 // Skip implicit cast of pointer to `void *' (as a function argument).
11957 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000011958 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000011959 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011960 ArgumentExpr = ICE->getSubExpr();
11961 }
11962 QualType ArgumentType = ArgumentExpr->getType();
11963
11964 // Passing a `void*' pointer shouldn't trigger a warning.
11965 if (IsPointerAttr && ArgumentType->isVoidPointerType())
11966 return;
11967
11968 if (TypeInfo.MustBeNull) {
11969 // Type tag with matching void type requires a null pointer.
11970 if (!ArgumentExpr->isNullPointerConstant(Context,
11971 Expr::NPC_ValueDependentIsNotNull)) {
11972 Diag(ArgumentExpr->getExprLoc(),
11973 diag::warn_type_safety_null_pointer_required)
11974 << ArgumentKind->getName()
11975 << ArgumentExpr->getSourceRange()
11976 << TypeTagExpr->getSourceRange();
11977 }
11978 return;
11979 }
11980
11981 QualType RequiredType = TypeInfo.Type;
11982 if (IsPointerAttr)
11983 RequiredType = Context.getPointerType(RequiredType);
11984
11985 bool mismatch = false;
11986 if (!TypeInfo.LayoutCompatible) {
11987 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
11988
11989 // C++11 [basic.fundamental] p1:
11990 // Plain char, signed char, and unsigned char are three distinct types.
11991 //
11992 // But we treat plain `char' as equivalent to `signed char' or `unsigned
11993 // char' depending on the current char signedness mode.
11994 if (mismatch)
11995 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
11996 RequiredType->getPointeeType())) ||
11997 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
11998 mismatch = false;
11999 } else
12000 if (IsPointerAttr)
12001 mismatch = !isLayoutCompatible(Context,
12002 ArgumentType->getPointeeType(),
12003 RequiredType->getPointeeType());
12004 else
12005 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12006
12007 if (mismatch)
12008 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000012009 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012010 << TypeInfo.LayoutCompatible << RequiredType
12011 << ArgumentExpr->getSourceRange()
12012 << TypeTagExpr->getSourceRange();
12013}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012014
12015void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12016 CharUnits Alignment) {
12017 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12018}
12019
12020void Sema::DiagnoseMisalignedMembers() {
12021 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000012022 const NamedDecl *ND = m.RD;
12023 if (ND->getName().empty()) {
12024 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12025 ND = TD;
12026 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012027 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000012028 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012029 }
12030 MisalignedMembers.clear();
12031}
12032
12033void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012034 E = E->IgnoreParens();
12035 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012036 return;
12037 if (isa<UnaryOperator>(E) &&
12038 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12039 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12040 if (isa<MemberExpr>(Op)) {
12041 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12042 MisalignedMember(Op));
12043 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012044 (T->isIntegerType() ||
12045 (T->isPointerType() &&
12046 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012047 MisalignedMembers.erase(MA);
12048 }
12049 }
12050}
12051
12052void Sema::RefersToMemberWithReducedAlignment(
12053 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000012054 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12055 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012056 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012057 if (!ME)
12058 return;
12059
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000012060 // No need to check expressions with an __unaligned-qualified type.
12061 if (E->getType().getQualifiers().hasUnaligned())
12062 return;
12063
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012064 // For a chain of MemberExpr like "a.b.c.d" this list
12065 // will keep FieldDecl's like [d, c, b].
12066 SmallVector<FieldDecl *, 4> ReverseMemberChain;
12067 const MemberExpr *TopME = nullptr;
12068 bool AnyIsPacked = false;
12069 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012070 QualType BaseType = ME->getBase()->getType();
12071 if (ME->isArrow())
12072 BaseType = BaseType->getPointeeType();
12073 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
12074
12075 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012076 auto *FD = dyn_cast<FieldDecl>(MD);
12077 // We do not care about non-data members.
12078 if (!FD || FD->isInvalidDecl())
12079 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012080
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012081 AnyIsPacked =
12082 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12083 ReverseMemberChain.push_back(FD);
12084
12085 TopME = ME;
12086 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12087 } while (ME);
12088 assert(TopME && "We did not compute a topmost MemberExpr!");
12089
12090 // Not the scope of this diagnostic.
12091 if (!AnyIsPacked)
12092 return;
12093
12094 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12095 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12096 // TODO: The innermost base of the member expression may be too complicated.
12097 // For now, just disregard these cases. This is left for future
12098 // improvement.
12099 if (!DRE && !isa<CXXThisExpr>(TopBase))
12100 return;
12101
12102 // Alignment expected by the whole expression.
12103 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12104
12105 // No need to do anything else with this case.
12106 if (ExpectedAlignment.isOne())
12107 return;
12108
12109 // Synthesize offset of the whole access.
12110 CharUnits Offset;
12111 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12112 I++) {
12113 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12114 }
12115
12116 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12117 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12118 ReverseMemberChain.back()->getParent()->getTypeForDecl());
12119
12120 // The base expression of the innermost MemberExpr may give
12121 // stronger guarantees than the class containing the member.
12122 if (DRE && !TopME->isArrow()) {
12123 const ValueDecl *VD = DRE->getDecl();
12124 if (!VD->getType()->isReferenceType())
12125 CompleteObjectAlignment =
12126 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12127 }
12128
12129 // Check if the synthesized offset fulfills the alignment.
12130 if (Offset % ExpectedAlignment != 0 ||
12131 // It may fulfill the offset it but the effective alignment may still be
12132 // lower than the expected expression alignment.
12133 CompleteObjectAlignment < ExpectedAlignment) {
12134 // If this happens, we want to determine a sensible culprit of this.
12135 // Intuitively, watching the chain of member expressions from right to
12136 // left, we start with the required alignment (as required by the field
12137 // type) but some packed attribute in that chain has reduced the alignment.
12138 // It may happen that another packed structure increases it again. But if
12139 // we are here such increase has not been enough. So pointing the first
12140 // FieldDecl that either is packed or else its RecordDecl is,
12141 // seems reasonable.
12142 FieldDecl *FD = nullptr;
12143 CharUnits Alignment;
12144 for (FieldDecl *FDI : ReverseMemberChain) {
12145 if (FDI->hasAttr<PackedAttr>() ||
12146 FDI->getParent()->hasAttr<PackedAttr>()) {
12147 FD = FDI;
12148 Alignment = std::min(
12149 Context.getTypeAlignInChars(FD->getType()),
12150 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12151 break;
12152 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012153 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012154 assert(FD && "We did not find a packed FieldDecl!");
12155 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012156 }
12157}
12158
12159void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12160 using namespace std::placeholders;
12161 RefersToMemberWithReducedAlignment(
12162 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12163 _2, _3, _4));
12164}
12165