blob: 845c4bf61b7aad37bb678186f16bf4022bd1c48d [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)
Alexander Shaposhnikov62351372017-06-26 23:02:27 +00006003 .Case("CFIndex", Context.LongTy)
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006004 .Case("NSInteger", Context.LongTy)
6005 .Case("NSUInteger", Context.UnsignedLongTy)
6006 .Case("SInt32", Context.IntTy)
6007 .Case("UInt32", Context.UnsignedIntTy)
6008 .Default(QualType());
6009
6010 if (!CastTy.isNull())
6011 return std::make_pair(CastTy, Name);
6012
6013 TyTy = UserTy->desugar();
6014 }
6015
6016 // Strip parens if necessary.
6017 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6018 return shouldNotPrintDirectly(Context,
6019 PE->getSubExpr()->getType(),
6020 PE->getSubExpr());
6021
6022 // If this is a conditional expression, then its result type is constructed
6023 // via usual arithmetic conversions and thus there might be no necessary
6024 // typedef sugar there. Recurse to operands to check for NSInteger &
6025 // Co. usage condition.
6026 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6027 QualType TrueTy, FalseTy;
6028 StringRef TrueName, FalseName;
6029
6030 std::tie(TrueTy, TrueName) =
6031 shouldNotPrintDirectly(Context,
6032 CO->getTrueExpr()->getType(),
6033 CO->getTrueExpr());
6034 std::tie(FalseTy, FalseName) =
6035 shouldNotPrintDirectly(Context,
6036 CO->getFalseExpr()->getType(),
6037 CO->getFalseExpr());
6038
6039 if (TrueTy == FalseTy)
6040 return std::make_pair(TrueTy, TrueName);
6041 else if (TrueTy.isNull())
6042 return std::make_pair(FalseTy, FalseName);
6043 else if (FalseTy.isNull())
6044 return std::make_pair(TrueTy, TrueName);
6045 }
6046
6047 return std::make_pair(QualType(), StringRef());
6048}
6049
Richard Smith55ce3522012-06-25 20:30:08 +00006050bool
6051CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6052 const char *StartSpecifier,
6053 unsigned SpecifierLen,
6054 const Expr *E) {
6055 using namespace analyze_format_string;
6056 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006057 // Now type check the data expression that matches the
6058 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006059 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00006060 if (!AT.isValid())
6061 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00006062
Jordan Rose598ec092012-12-05 18:44:40 +00006063 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00006064 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6065 ExprTy = TET->getUnderlyingExpr()->getType();
6066 }
6067
Seth Cantrellb4802962015-03-04 03:12:10 +00006068 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6069
6070 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00006071 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006072 }
Jordan Rose98709982012-06-04 22:48:57 +00006073
Jordan Rose22b74712012-09-05 22:56:19 +00006074 // Look through argument promotions for our error message's reported type.
6075 // This includes the integral and floating promotions, but excludes array
6076 // and function pointer decay; seeing that an argument intended to be a
6077 // string has type 'char [6]' is probably more confusing than 'char *'.
6078 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6079 if (ICE->getCastKind() == CK_IntegralCast ||
6080 ICE->getCastKind() == CK_FloatingCast) {
6081 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006082 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006083
6084 // Check if we didn't match because of an implicit cast from a 'char'
6085 // or 'short' to an 'int'. This is done because printf is a varargs
6086 // function.
6087 if (ICE->getType() == S.Context.IntTy ||
6088 ICE->getType() == S.Context.UnsignedIntTy) {
6089 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006090 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006091 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006092 }
Jordan Rose98709982012-06-04 22:48:57 +00006093 }
Jordan Rose598ec092012-12-05 18:44:40 +00006094 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6095 // Special case for 'a', which has type 'int' in C.
6096 // Note, however, that we do /not/ want to treat multibyte constants like
6097 // 'MooV' as characters! This form is deprecated but still exists.
6098 if (ExprTy == S.Context.IntTy)
6099 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6100 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006101 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006102
Jordan Rosebc53ed12014-05-31 04:12:14 +00006103 // Look through enums to their underlying type.
6104 bool IsEnum = false;
6105 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6106 ExprTy = EnumTy->getDecl()->getIntegerType();
6107 IsEnum = true;
6108 }
6109
Jordan Rose0e5badd2012-12-05 18:44:49 +00006110 // %C in an Objective-C context prints a unichar, not a wchar_t.
6111 // If the argument is an integer of some kind, believe the %C and suggest
6112 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006113 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006114 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006115 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6116 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6117 !ExprTy->isCharType()) {
6118 // 'unichar' is defined as a typedef of unsigned short, but we should
6119 // prefer using the typedef if it is visible.
6120 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006121
6122 // While we are here, check if the value is an IntegerLiteral that happens
6123 // to be within the valid range.
6124 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6125 const llvm::APInt &V = IL->getValue();
6126 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6127 return true;
6128 }
6129
Jordan Rose0e5badd2012-12-05 18:44:49 +00006130 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6131 Sema::LookupOrdinaryName);
6132 if (S.LookupName(Result, S.getCurScope())) {
6133 NamedDecl *ND = Result.getFoundDecl();
6134 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6135 if (TD->getUnderlyingType() == IntendedTy)
6136 IntendedTy = S.Context.getTypedefType(TD);
6137 }
6138 }
6139 }
6140
6141 // Special-case some of Darwin's platform-independence types by suggesting
6142 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006143 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006144 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006145 QualType CastTy;
6146 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6147 if (!CastTy.isNull()) {
6148 IntendedTy = CastTy;
6149 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006150 }
6151 }
6152
Jordan Rose22b74712012-09-05 22:56:19 +00006153 // We may be able to offer a FixItHint if it is a supported type.
6154 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006155 bool success =
6156 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006157
Jordan Rose22b74712012-09-05 22:56:19 +00006158 if (success) {
6159 // Get the fix string from the fixed format specifier
6160 SmallString<16> buf;
6161 llvm::raw_svector_ostream os(buf);
6162 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006163
Jordan Roseaee34382012-09-05 22:56:26 +00006164 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6165
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006166 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00006167 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6168 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6169 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6170 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00006171 // In this case, the specifier is wrong and should be changed to match
6172 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006173 EmitFormatDiagnostic(S.PDiag(diag)
6174 << AT.getRepresentativeTypeName(S.Context)
6175 << IntendedTy << IsEnum << E->getSourceRange(),
6176 E->getLocStart(),
6177 /*IsStringLocation*/ false, SpecRange,
6178 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006179 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006180 // The canonical type for formatting this value is different from the
6181 // actual type of the expression. (This occurs, for example, with Darwin's
6182 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6183 // should be printed as 'long' for 64-bit compatibility.)
6184 // Rather than emitting a normal format/argument mismatch, we want to
6185 // add a cast to the recommended type (and correct the format string
6186 // if necessary).
6187 SmallString<16> CastBuf;
6188 llvm::raw_svector_ostream CastFix(CastBuf);
6189 CastFix << "(";
6190 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6191 CastFix << ")";
6192
6193 SmallVector<FixItHint,4> Hints;
6194 if (!AT.matchesType(S.Context, IntendedTy))
6195 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6196
6197 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6198 // If there's already a cast present, just replace it.
6199 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6200 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6201
6202 } else if (!requiresParensToAddCast(E)) {
6203 // If the expression has high enough precedence,
6204 // just write the C-style cast.
6205 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6206 CastFix.str()));
6207 } else {
6208 // Otherwise, add parens around the expression as well as the cast.
6209 CastFix << "(";
6210 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6211 CastFix.str()));
6212
Alp Tokerb6cc5922014-05-03 03:45:55 +00006213 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006214 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6215 }
6216
Jordan Rose0e5badd2012-12-05 18:44:49 +00006217 if (ShouldNotPrintDirectly) {
6218 // The expression has a type that should not be printed directly.
6219 // We extract the name from the typedef because we don't want to show
6220 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006221 StringRef Name;
6222 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6223 Name = TypedefTy->getDecl()->getName();
6224 else
6225 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006226 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006227 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006228 << E->getSourceRange(),
6229 E->getLocStart(), /*IsStringLocation=*/false,
6230 SpecRange, Hints);
6231 } else {
6232 // In this case, the expression could be printed using a different
6233 // specifier, but we've decided that the specifier is probably correct
6234 // and we should cast instead. Just use the normal warning message.
6235 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006236 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6237 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006238 << E->getSourceRange(),
6239 E->getLocStart(), /*IsStringLocation*/false,
6240 SpecRange, Hints);
6241 }
Jordan Roseaee34382012-09-05 22:56:26 +00006242 }
Jordan Rose22b74712012-09-05 22:56:19 +00006243 } else {
6244 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6245 SpecifierLen);
6246 // Since the warning for passing non-POD types to variadic functions
6247 // was deferred until now, we emit a warning for non-POD
6248 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006249 switch (S.isValidVarArgType(ExprTy)) {
6250 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006251 case Sema::VAK_ValidInCXX11: {
6252 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6253 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6254 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6255 }
Richard Smithd7293d72013-08-05 18:49:43 +00006256
Seth Cantrellb4802962015-03-04 03:12:10 +00006257 EmitFormatDiagnostic(
6258 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6259 << IsEnum << CSR << E->getSourceRange(),
6260 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6261 break;
6262 }
Richard Smithd7293d72013-08-05 18:49:43 +00006263 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006264 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006265 EmitFormatDiagnostic(
6266 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006267 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006268 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006269 << CallType
6270 << AT.getRepresentativeTypeName(S.Context)
6271 << CSR
6272 << E->getSourceRange(),
6273 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006274 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006275 break;
6276
6277 case Sema::VAK_Invalid:
6278 if (ExprTy->isObjCObjectType())
6279 EmitFormatDiagnostic(
6280 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6281 << S.getLangOpts().CPlusPlus11
6282 << ExprTy
6283 << CallType
6284 << AT.getRepresentativeTypeName(S.Context)
6285 << CSR
6286 << E->getSourceRange(),
6287 E->getLocStart(), /*IsStringLocation*/false, CSR);
6288 else
6289 // FIXME: If this is an initializer list, suggest removing the braces
6290 // or inserting a cast to the target type.
6291 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6292 << isa<InitListExpr>(E) << ExprTy << CallType
6293 << AT.getRepresentativeTypeName(S.Context)
6294 << E->getSourceRange();
6295 break;
6296 }
6297
6298 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6299 "format string specifier index out of range");
6300 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006301 }
6302
Ted Kremenekab278de2010-01-28 23:39:18 +00006303 return true;
6304}
6305
Ted Kremenek02087932010-07-16 02:11:22 +00006306//===--- CHECK: Scanf format string checking ------------------------------===//
6307
6308namespace {
6309class CheckScanfHandler : public CheckFormatHandler {
6310public:
Stephen Hines648c3692016-09-16 01:07:04 +00006311 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006312 const Expr *origFormatExpr, Sema::FormatStringType type,
6313 unsigned firstDataArg, unsigned numDataArgs,
6314 const char *beg, bool hasVAListArg,
6315 ArrayRef<const Expr *> Args, unsigned formatIdx,
6316 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006317 llvm::SmallBitVector &CheckedVarArgs,
6318 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006319 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6320 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6321 inFunctionCall, CallType, CheckedVarArgs,
6322 UncoveredArg) {}
6323
Ted Kremenek02087932010-07-16 02:11:22 +00006324 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6325 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006326 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006327
6328 bool HandleInvalidScanfConversionSpecifier(
6329 const analyze_scanf::ScanfSpecifier &FS,
6330 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006331 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006332
Craig Toppere14c0f82014-03-12 04:55:44 +00006333 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006334};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006335} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006336
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006337void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6338 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006339 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6340 getLocationOfByte(end), /*IsStringLocation*/true,
6341 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006342}
6343
Ted Kremenekce815422010-07-19 21:25:57 +00006344bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6345 const analyze_scanf::ScanfSpecifier &FS,
6346 const char *startSpecifier,
6347 unsigned specifierLen) {
6348
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006349 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006350 FS.getConversionSpecifier();
6351
6352 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6353 getLocationOfByte(CS.getStart()),
6354 startSpecifier, specifierLen,
6355 CS.getStart(), CS.getLength());
6356}
6357
Ted Kremenek02087932010-07-16 02:11:22 +00006358bool CheckScanfHandler::HandleScanfSpecifier(
6359 const analyze_scanf::ScanfSpecifier &FS,
6360 const char *startSpecifier,
6361 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006362 using namespace analyze_scanf;
6363 using namespace analyze_format_string;
6364
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006365 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006366
Ted Kremenek6cd69422010-07-19 22:01:06 +00006367 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6368 // be used to decide if we are using positional arguments consistently.
6369 if (FS.consumesDataArgument()) {
6370 if (atFirstArg) {
6371 atFirstArg = false;
6372 usesPositionalArgs = FS.usesPositionalArg();
6373 }
6374 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006375 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6376 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006377 return false;
6378 }
Ted Kremenek02087932010-07-16 02:11:22 +00006379 }
6380
6381 // Check if the field with is non-zero.
6382 const OptionalAmount &Amt = FS.getFieldWidth();
6383 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6384 if (Amt.getConstantAmount() == 0) {
6385 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6386 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006387 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6388 getLocationOfByte(Amt.getStart()),
6389 /*IsStringLocation*/true, R,
6390 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006391 }
6392 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006393
Ted Kremenek02087932010-07-16 02:11:22 +00006394 if (!FS.consumesDataArgument()) {
6395 // FIXME: Technically specifying a precision or field width here
6396 // makes no sense. Worth issuing a warning at some point.
6397 return true;
6398 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006399
Ted Kremenek02087932010-07-16 02:11:22 +00006400 // Consume the argument.
6401 unsigned argIndex = FS.getArgIndex();
6402 if (argIndex < NumDataArgs) {
6403 // The check to see if the argIndex is valid will come later.
6404 // We set the bit here because we may exit early from this
6405 // function if we encounter some other error.
6406 CoveredArgs.set(argIndex);
6407 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006408
Ted Kremenek4407ea42010-07-20 20:04:47 +00006409 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006410 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006411 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6412 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006413 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006414 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006415 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006416 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6417 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006418
Jordan Rose92303592012-09-08 04:00:03 +00006419 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6420 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6421
Ted Kremenek02087932010-07-16 02:11:22 +00006422 // The remaining checks depend on the data arguments.
6423 if (HasVAListArg)
6424 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006425
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006426 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006427 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006428
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006429 // Check that the argument type matches the format specifier.
6430 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006431 if (!Ex)
6432 return true;
6433
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006434 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006435
6436 if (!AT.isValid()) {
6437 return true;
6438 }
6439
Seth Cantrellb4802962015-03-04 03:12:10 +00006440 analyze_format_string::ArgType::MatchKind match =
6441 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006442 if (match == analyze_format_string::ArgType::Match) {
6443 return true;
6444 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006445
Seth Cantrell79340072015-03-04 05:58:08 +00006446 ScanfSpecifier fixedFS = FS;
6447 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6448 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006449
Seth Cantrell79340072015-03-04 05:58:08 +00006450 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6451 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6452 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6453 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006454
Seth Cantrell79340072015-03-04 05:58:08 +00006455 if (success) {
6456 // Get the fix string from the fixed format specifier.
6457 SmallString<128> buf;
6458 llvm::raw_svector_ostream os(buf);
6459 fixedFS.toString(os);
6460
6461 EmitFormatDiagnostic(
6462 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6463 << Ex->getType() << false << Ex->getSourceRange(),
6464 Ex->getLocStart(),
6465 /*IsStringLocation*/ false,
6466 getSpecifierRange(startSpecifier, specifierLen),
6467 FixItHint::CreateReplacement(
6468 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6469 } else {
6470 EmitFormatDiagnostic(S.PDiag(diag)
6471 << AT.getRepresentativeTypeName(S.Context)
6472 << Ex->getType() << false << Ex->getSourceRange(),
6473 Ex->getLocStart(),
6474 /*IsStringLocation*/ false,
6475 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006476 }
6477
Ted Kremenek02087932010-07-16 02:11:22 +00006478 return true;
6479}
6480
Stephen Hines648c3692016-09-16 01:07:04 +00006481static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006482 const Expr *OrigFormatExpr,
6483 ArrayRef<const Expr *> Args,
6484 bool HasVAListArg, unsigned format_idx,
6485 unsigned firstDataArg,
6486 Sema::FormatStringType Type,
6487 bool inFunctionCall,
6488 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006489 llvm::SmallBitVector &CheckedVarArgs,
6490 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00006491 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00006492 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006493 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006494 S, inFunctionCall, Args[format_idx],
6495 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006496 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006497 return;
6498 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006499
Ted Kremenekab278de2010-01-28 23:39:18 +00006500 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006501 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00006502 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006503 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006504 const ConstantArrayType *T =
6505 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006506 assert(T && "String literal not of constant array type!");
6507 size_t TypeSize = T->getSize().getZExtValue();
6508 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006509 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006510
6511 // Emit a warning if the string literal is truncated and does not contain an
6512 // embedded null character.
6513 if (TypeSize <= StrRef.size() &&
6514 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6515 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006516 S, inFunctionCall, Args[format_idx],
6517 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006518 FExpr->getLocStart(),
6519 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6520 return;
6521 }
6522
Ted Kremenekab278de2010-01-28 23:39:18 +00006523 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006524 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006525 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006526 S, inFunctionCall, Args[format_idx],
6527 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006528 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006529 return;
6530 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006531
6532 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00006533 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6534 Type == Sema::FST_OSTrace) {
6535 CheckPrintfHandler H(
6536 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6537 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6538 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6539 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006540
Hans Wennborg23926bd2011-12-15 10:25:47 +00006541 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006542 S.getLangOpts(),
6543 S.Context.getTargetInfo(),
6544 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006545 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006546 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00006547 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6548 numDataArgs, Str, HasVAListArg, Args, format_idx,
6549 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006550
Hans Wennborg23926bd2011-12-15 10:25:47 +00006551 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006552 S.getLangOpts(),
6553 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006554 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006555 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006556}
6557
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006558bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6559 // Str - The format string. NOTE: this is NOT null-terminated!
6560 StringRef StrRef = FExpr->getString();
6561 const char *Str = StrRef.data();
6562 // Account for cases where the string literal is truncated in a declaration.
6563 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6564 assert(T && "String literal not of constant array type!");
6565 size_t TypeSize = T->getSize().getZExtValue();
6566 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6567 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6568 getLangOpts(),
6569 Context.getTargetInfo());
6570}
6571
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006572//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6573
6574// Returns the related absolute value function that is larger, of 0 if one
6575// does not exist.
6576static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6577 switch (AbsFunction) {
6578 default:
6579 return 0;
6580
6581 case Builtin::BI__builtin_abs:
6582 return Builtin::BI__builtin_labs;
6583 case Builtin::BI__builtin_labs:
6584 return Builtin::BI__builtin_llabs;
6585 case Builtin::BI__builtin_llabs:
6586 return 0;
6587
6588 case Builtin::BI__builtin_fabsf:
6589 return Builtin::BI__builtin_fabs;
6590 case Builtin::BI__builtin_fabs:
6591 return Builtin::BI__builtin_fabsl;
6592 case Builtin::BI__builtin_fabsl:
6593 return 0;
6594
6595 case Builtin::BI__builtin_cabsf:
6596 return Builtin::BI__builtin_cabs;
6597 case Builtin::BI__builtin_cabs:
6598 return Builtin::BI__builtin_cabsl;
6599 case Builtin::BI__builtin_cabsl:
6600 return 0;
6601
6602 case Builtin::BIabs:
6603 return Builtin::BIlabs;
6604 case Builtin::BIlabs:
6605 return Builtin::BIllabs;
6606 case Builtin::BIllabs:
6607 return 0;
6608
6609 case Builtin::BIfabsf:
6610 return Builtin::BIfabs;
6611 case Builtin::BIfabs:
6612 return Builtin::BIfabsl;
6613 case Builtin::BIfabsl:
6614 return 0;
6615
6616 case Builtin::BIcabsf:
6617 return Builtin::BIcabs;
6618 case Builtin::BIcabs:
6619 return Builtin::BIcabsl;
6620 case Builtin::BIcabsl:
6621 return 0;
6622 }
6623}
6624
6625// Returns the argument type of the absolute value function.
6626static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6627 unsigned AbsType) {
6628 if (AbsType == 0)
6629 return QualType();
6630
6631 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6632 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6633 if (Error != ASTContext::GE_None)
6634 return QualType();
6635
6636 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6637 if (!FT)
6638 return QualType();
6639
6640 if (FT->getNumParams() != 1)
6641 return QualType();
6642
6643 return FT->getParamType(0);
6644}
6645
6646// Returns the best absolute value function, or zero, based on type and
6647// current absolute value function.
6648static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6649 unsigned AbsFunctionKind) {
6650 unsigned BestKind = 0;
6651 uint64_t ArgSize = Context.getTypeSize(ArgType);
6652 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6653 Kind = getLargerAbsoluteValueFunction(Kind)) {
6654 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6655 if (Context.getTypeSize(ParamType) >= ArgSize) {
6656 if (BestKind == 0)
6657 BestKind = Kind;
6658 else if (Context.hasSameType(ParamType, ArgType)) {
6659 BestKind = Kind;
6660 break;
6661 }
6662 }
6663 }
6664 return BestKind;
6665}
6666
6667enum AbsoluteValueKind {
6668 AVK_Integer,
6669 AVK_Floating,
6670 AVK_Complex
6671};
6672
6673static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6674 if (T->isIntegralOrEnumerationType())
6675 return AVK_Integer;
6676 if (T->isRealFloatingType())
6677 return AVK_Floating;
6678 if (T->isAnyComplexType())
6679 return AVK_Complex;
6680
6681 llvm_unreachable("Type not integer, floating, or complex");
6682}
6683
6684// Changes the absolute value function to a different type. Preserves whether
6685// the function is a builtin.
6686static unsigned changeAbsFunction(unsigned AbsKind,
6687 AbsoluteValueKind ValueKind) {
6688 switch (ValueKind) {
6689 case AVK_Integer:
6690 switch (AbsKind) {
6691 default:
6692 return 0;
6693 case Builtin::BI__builtin_fabsf:
6694 case Builtin::BI__builtin_fabs:
6695 case Builtin::BI__builtin_fabsl:
6696 case Builtin::BI__builtin_cabsf:
6697 case Builtin::BI__builtin_cabs:
6698 case Builtin::BI__builtin_cabsl:
6699 return Builtin::BI__builtin_abs;
6700 case Builtin::BIfabsf:
6701 case Builtin::BIfabs:
6702 case Builtin::BIfabsl:
6703 case Builtin::BIcabsf:
6704 case Builtin::BIcabs:
6705 case Builtin::BIcabsl:
6706 return Builtin::BIabs;
6707 }
6708 case AVK_Floating:
6709 switch (AbsKind) {
6710 default:
6711 return 0;
6712 case Builtin::BI__builtin_abs:
6713 case Builtin::BI__builtin_labs:
6714 case Builtin::BI__builtin_llabs:
6715 case Builtin::BI__builtin_cabsf:
6716 case Builtin::BI__builtin_cabs:
6717 case Builtin::BI__builtin_cabsl:
6718 return Builtin::BI__builtin_fabsf;
6719 case Builtin::BIabs:
6720 case Builtin::BIlabs:
6721 case Builtin::BIllabs:
6722 case Builtin::BIcabsf:
6723 case Builtin::BIcabs:
6724 case Builtin::BIcabsl:
6725 return Builtin::BIfabsf;
6726 }
6727 case AVK_Complex:
6728 switch (AbsKind) {
6729 default:
6730 return 0;
6731 case Builtin::BI__builtin_abs:
6732 case Builtin::BI__builtin_labs:
6733 case Builtin::BI__builtin_llabs:
6734 case Builtin::BI__builtin_fabsf:
6735 case Builtin::BI__builtin_fabs:
6736 case Builtin::BI__builtin_fabsl:
6737 return Builtin::BI__builtin_cabsf;
6738 case Builtin::BIabs:
6739 case Builtin::BIlabs:
6740 case Builtin::BIllabs:
6741 case Builtin::BIfabsf:
6742 case Builtin::BIfabs:
6743 case Builtin::BIfabsl:
6744 return Builtin::BIcabsf;
6745 }
6746 }
6747 llvm_unreachable("Unable to convert function");
6748}
6749
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006750static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006751 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6752 if (!FnInfo)
6753 return 0;
6754
6755 switch (FDecl->getBuiltinID()) {
6756 default:
6757 return 0;
6758 case Builtin::BI__builtin_abs:
6759 case Builtin::BI__builtin_fabs:
6760 case Builtin::BI__builtin_fabsf:
6761 case Builtin::BI__builtin_fabsl:
6762 case Builtin::BI__builtin_labs:
6763 case Builtin::BI__builtin_llabs:
6764 case Builtin::BI__builtin_cabs:
6765 case Builtin::BI__builtin_cabsf:
6766 case Builtin::BI__builtin_cabsl:
6767 case Builtin::BIabs:
6768 case Builtin::BIlabs:
6769 case Builtin::BIllabs:
6770 case Builtin::BIfabs:
6771 case Builtin::BIfabsf:
6772 case Builtin::BIfabsl:
6773 case Builtin::BIcabs:
6774 case Builtin::BIcabsf:
6775 case Builtin::BIcabsl:
6776 return FDecl->getBuiltinID();
6777 }
6778 llvm_unreachable("Unknown Builtin type");
6779}
6780
6781// If the replacement is valid, emit a note with replacement function.
6782// Additionally, suggest including the proper header if not already included.
6783static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00006784 unsigned AbsKind, QualType ArgType) {
6785 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006786 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00006787 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006788 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6789 FunctionName = "std::abs";
6790 if (ArgType->isIntegralOrEnumerationType()) {
6791 HeaderName = "cstdlib";
6792 } else if (ArgType->isRealFloatingType()) {
6793 HeaderName = "cmath";
6794 } else {
6795 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006796 }
Richard Trieubeffb832014-04-15 23:47:53 +00006797
6798 // Lookup all std::abs
6799 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00006800 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00006801 R.suppressDiagnostics();
6802 S.LookupQualifiedName(R, Std);
6803
6804 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006805 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006806 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6807 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6808 } else {
6809 FDecl = dyn_cast<FunctionDecl>(I);
6810 }
6811 if (!FDecl)
6812 continue;
6813
6814 // Found std::abs(), check that they are the right ones.
6815 if (FDecl->getNumParams() != 1)
6816 continue;
6817
6818 // Check that the parameter type can handle the argument.
6819 QualType ParamType = FDecl->getParamDecl(0)->getType();
6820 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6821 S.Context.getTypeSize(ArgType) <=
6822 S.Context.getTypeSize(ParamType)) {
6823 // Found a function, don't need the header hint.
6824 EmitHeaderHint = false;
6825 break;
6826 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006827 }
Richard Trieubeffb832014-04-15 23:47:53 +00006828 }
6829 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00006830 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00006831 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6832
6833 if (HeaderName) {
6834 DeclarationName DN(&S.Context.Idents.get(FunctionName));
6835 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6836 R.suppressDiagnostics();
6837 S.LookupName(R, S.getCurScope());
6838
6839 if (R.isSingleResult()) {
6840 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6841 if (FD && FD->getBuiltinID() == AbsKind) {
6842 EmitHeaderHint = false;
6843 } else {
6844 return;
6845 }
6846 } else if (!R.empty()) {
6847 return;
6848 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006849 }
6850 }
6851
6852 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00006853 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006854
Richard Trieubeffb832014-04-15 23:47:53 +00006855 if (!HeaderName)
6856 return;
6857
6858 if (!EmitHeaderHint)
6859 return;
6860
Alp Toker5d96e0a2014-07-11 20:53:51 +00006861 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6862 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00006863}
6864
Richard Trieua7f30b12016-12-06 01:42:28 +00006865template <std::size_t StrLen>
6866static bool IsStdFunction(const FunctionDecl *FDecl,
6867 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00006868 if (!FDecl)
6869 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00006870 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00006871 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00006872 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00006873 return false;
6874
6875 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006876}
6877
6878// Warn when using the wrong abs() function.
6879void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00006880 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006881 if (Call->getNumArgs() != 1)
6882 return;
6883
6884 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00006885 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00006886 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006887 return;
6888
6889 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6890 QualType ParamType = Call->getArg(0)->getType();
6891
Alp Toker5d96e0a2014-07-11 20:53:51 +00006892 // Unsigned types cannot be negative. Suggest removing the absolute value
6893 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006894 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00006895 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00006896 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006897 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6898 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00006899 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006900 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6901 return;
6902 }
6903
David Majnemer7f77eb92015-11-15 03:04:34 +00006904 // Taking the absolute value of a pointer is very suspicious, they probably
6905 // wanted to index into an array, dereference a pointer, call a function, etc.
6906 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6907 unsigned DiagType = 0;
6908 if (ArgType->isFunctionType())
6909 DiagType = 1;
6910 else if (ArgType->isArrayType())
6911 DiagType = 2;
6912
6913 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6914 return;
6915 }
6916
Richard Trieubeffb832014-04-15 23:47:53 +00006917 // std::abs has overloads which prevent most of the absolute value problems
6918 // from occurring.
6919 if (IsStdAbs)
6920 return;
6921
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006922 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6923 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6924
6925 // The argument and parameter are the same kind. Check if they are the right
6926 // size.
6927 if (ArgValueKind == ParamValueKind) {
6928 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6929 return;
6930
6931 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6932 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6933 << FDecl << ArgType << ParamType;
6934
6935 if (NewAbsKind == 0)
6936 return;
6937
6938 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006939 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006940 return;
6941 }
6942
6943 // ArgValueKind != ParamValueKind
6944 // The wrong type of absolute value function was used. Attempt to find the
6945 // proper one.
6946 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6947 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6948 if (NewAbsKind == 0)
6949 return;
6950
6951 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6952 << FDecl << ParamValueKind << ArgValueKind;
6953
6954 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006955 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006956}
6957
Richard Trieu67c00712016-12-05 23:41:46 +00006958//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00006959void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
6960 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00006961 if (!Call || !FDecl) return;
6962
6963 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00006964 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00006965 if (Call->getExprLoc().isMacroID()) return;
6966
6967 // Only care about the one template argument, two function parameter std::max
6968 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00006969 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00006970 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
6971 if (!ArgList) return;
6972 if (ArgList->size() != 1) return;
6973
6974 // Check that template type argument is unsigned integer.
6975 const auto& TA = ArgList->get(0);
6976 if (TA.getKind() != TemplateArgument::Type) return;
6977 QualType ArgType = TA.getAsType();
6978 if (!ArgType->isUnsignedIntegerType()) return;
6979
6980 // See if either argument is a literal zero.
6981 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
6982 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
6983 if (!MTE) return false;
6984 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
6985 if (!Num) return false;
6986 if (Num->getValue() != 0) return false;
6987 return true;
6988 };
6989
6990 const Expr *FirstArg = Call->getArg(0);
6991 const Expr *SecondArg = Call->getArg(1);
6992 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
6993 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
6994
6995 // Only warn when exactly one argument is zero.
6996 if (IsFirstArgZero == IsSecondArgZero) return;
6997
6998 SourceRange FirstRange = FirstArg->getSourceRange();
6999 SourceRange SecondRange = SecondArg->getSourceRange();
7000
7001 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7002
7003 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7004 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7005
7006 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7007 SourceRange RemovalRange;
7008 if (IsFirstArgZero) {
7009 RemovalRange = SourceRange(FirstRange.getBegin(),
7010 SecondRange.getBegin().getLocWithOffset(-1));
7011 } else {
7012 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7013 SecondRange.getEnd());
7014 }
7015
7016 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7017 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7018 << FixItHint::CreateRemoval(RemovalRange);
7019}
7020
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007021//===--- CHECK: Standard memory functions ---------------------------------===//
7022
Nico Weber0e6daef2013-12-26 23:38:39 +00007023/// \brief Takes the expression passed to the size_t parameter of functions
7024/// such as memcmp, strncat, etc and warns if it's a comparison.
7025///
7026/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7027static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7028 IdentifierInfo *FnName,
7029 SourceLocation FnLoc,
7030 SourceLocation RParenLoc) {
7031 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7032 if (!Size)
7033 return false;
7034
7035 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
7036 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
7037 return false;
7038
Nico Weber0e6daef2013-12-26 23:38:39 +00007039 SourceRange SizeRange = Size->getSourceRange();
7040 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7041 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00007042 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007043 << FnName << FixItHint::CreateInsertion(
7044 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00007045 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00007046 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00007047 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00007048 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7049 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00007050
7051 return true;
7052}
7053
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007054/// \brief Determine whether the given type is or contains a dynamic class type
7055/// (e.g., whether it has a vtable).
7056static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7057 bool &IsContained) {
7058 // Look through array types while ignoring qualifiers.
7059 const Type *Ty = T->getBaseElementTypeUnsafe();
7060 IsContained = false;
7061
7062 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7063 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00007064 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007065 return nullptr;
7066
7067 if (RD->isDynamicClass())
7068 return RD;
7069
7070 // Check all the fields. If any bases were dynamic, the class is dynamic.
7071 // It's impossible for a class to transitively contain itself by value, so
7072 // infinite recursion is impossible.
7073 for (auto *FD : RD->fields()) {
7074 bool SubContained;
7075 if (const CXXRecordDecl *ContainedRD =
7076 getContainedDynamicClass(FD->getType(), SubContained)) {
7077 IsContained = true;
7078 return ContainedRD;
7079 }
7080 }
7081
7082 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007083}
7084
Chandler Carruth889ed862011-06-21 23:04:20 +00007085/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007086/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007087static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007088 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007089 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7090 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
7091 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007092
Craig Topperc3ec1492014-05-26 06:22:03 +00007093 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007094}
7095
Chandler Carruth889ed862011-06-21 23:04:20 +00007096/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007097static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007098 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7099 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7100 if (SizeOf->getKind() == clang::UETT_SizeOf)
7101 return SizeOf->getTypeOfArgument();
7102
7103 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007104}
7105
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007106/// \brief Check for dangerous or invalid arguments to memset().
7107///
Chandler Carruthac687262011-06-03 06:23:57 +00007108/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007109/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7110/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007111///
7112/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007113void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007114 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007115 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007116 assert(BId != 0);
7117
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007118 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007119 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007120 unsigned ExpectedNumArgs =
7121 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007122 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007123 return;
7124
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007125 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007126 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007127 unsigned LenArg =
7128 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007129 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007130
Nico Weber0e6daef2013-12-26 23:38:39 +00007131 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7132 Call->getLocStart(), Call->getRParenLoc()))
7133 return;
7134
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007135 // We have special checking when the length is a sizeof expression.
7136 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7137 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7138 llvm::FoldingSetNodeID SizeOfArgID;
7139
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007140 // Although widely used, 'bzero' is not a standard function. Be more strict
7141 // with the argument types before allowing diagnostics and only allow the
7142 // form bzero(ptr, sizeof(...)).
7143 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7144 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7145 return;
7146
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007147 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7148 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007149 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007150
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007151 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007152 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007153 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007154 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007155
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007156 // Never warn about void type pointers. This can be used to suppress
7157 // false positives.
7158 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007159 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007160
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007161 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7162 // actually comparing the expressions for equality. Because computing the
7163 // expression IDs can be expensive, we only do this if the diagnostic is
7164 // enabled.
7165 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007166 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7167 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007168 // We only compute IDs for expressions if the warning is enabled, and
7169 // cache the sizeof arg's ID.
7170 if (SizeOfArgID == llvm::FoldingSetNodeID())
7171 SizeOfArg->Profile(SizeOfArgID, Context, true);
7172 llvm::FoldingSetNodeID DestID;
7173 Dest->Profile(DestID, Context, true);
7174 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007175 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7176 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007177 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007178 StringRef ReadableName = FnName->getName();
7179
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007180 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007181 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007182 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007183 if (!PointeeTy->isIncompleteType() &&
7184 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007185 ActionIdx = 2; // If the pointee's size is sizeof(char),
7186 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007187
7188 // If the function is defined as a builtin macro, do not show macro
7189 // expansion.
7190 SourceLocation SL = SizeOfArg->getExprLoc();
7191 SourceRange DSR = Dest->getSourceRange();
7192 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007193 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007194
7195 if (SM.isMacroArgExpansion(SL)) {
7196 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7197 SL = SM.getSpellingLoc(SL);
7198 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7199 SM.getSpellingLoc(DSR.getEnd()));
7200 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7201 SM.getSpellingLoc(SSR.getEnd()));
7202 }
7203
Anna Zaksd08d9152012-05-30 23:14:52 +00007204 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007205 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007206 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007207 << PointeeTy
7208 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007209 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007210 << SSR);
7211 DiagRuntimeBehavior(SL, SizeOfArg,
7212 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7213 << ActionIdx
7214 << SSR);
7215
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007216 break;
7217 }
7218 }
7219
7220 // Also check for cases where the sizeof argument is the exact same
7221 // type as the memory argument, and where it points to a user-defined
7222 // record type.
7223 if (SizeOfArgTy != QualType()) {
7224 if (PointeeTy->isRecordType() &&
7225 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7226 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7227 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7228 << FnName << SizeOfArgTy << ArgIdx
7229 << PointeeTy << Dest->getSourceRange()
7230 << LenExpr->getSourceRange());
7231 break;
7232 }
Nico Weberc5e73862011-06-14 16:14:58 +00007233 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00007234 } else if (DestTy->isArrayType()) {
7235 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00007236 }
Nico Weberc5e73862011-06-14 16:14:58 +00007237
Nico Weberc44b35e2015-03-21 17:37:46 +00007238 if (PointeeTy == QualType())
7239 continue;
Anna Zaks22122702012-01-17 00:37:07 +00007240
Nico Weberc44b35e2015-03-21 17:37:46 +00007241 // Always complain about dynamic classes.
7242 bool IsContained;
7243 if (const CXXRecordDecl *ContainedRD =
7244 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00007245
Nico Weberc44b35e2015-03-21 17:37:46 +00007246 unsigned OperationType = 0;
7247 // "overwritten" if we're warning about the destination for any call
7248 // but memcmp; otherwise a verb appropriate to the call.
7249 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7250 if (BId == Builtin::BImemcpy)
7251 OperationType = 1;
7252 else if(BId == Builtin::BImemmove)
7253 OperationType = 2;
7254 else if (BId == Builtin::BImemcmp)
7255 OperationType = 3;
7256 }
7257
John McCall31168b02011-06-15 23:02:42 +00007258 DiagRuntimeBehavior(
7259 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007260 PDiag(diag::warn_dyn_class_memaccess)
7261 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7262 << FnName << IsContained << ContainedRD << OperationType
7263 << Call->getCallee()->getSourceRange());
7264 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7265 BId != Builtin::BImemset)
7266 DiagRuntimeBehavior(
7267 Dest->getExprLoc(), Dest,
7268 PDiag(diag::warn_arc_object_memaccess)
7269 << ArgIdx << FnName << PointeeTy
7270 << Call->getCallee()->getSourceRange());
7271 else
7272 continue;
7273
7274 DiagRuntimeBehavior(
7275 Dest->getExprLoc(), Dest,
7276 PDiag(diag::note_bad_memaccess_silence)
7277 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7278 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007279 }
7280}
7281
Ted Kremenek6865f772011-08-18 20:55:45 +00007282// A little helper routine: ignore addition and subtraction of integer literals.
7283// This intentionally does not ignore all integer constant expressions because
7284// we don't want to remove sizeof().
7285static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7286 Ex = Ex->IgnoreParenCasts();
7287
7288 for (;;) {
7289 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7290 if (!BO || !BO->isAdditiveOp())
7291 break;
7292
7293 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7294 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7295
7296 if (isa<IntegerLiteral>(RHS))
7297 Ex = LHS;
7298 else if (isa<IntegerLiteral>(LHS))
7299 Ex = RHS;
7300 else
7301 break;
7302 }
7303
7304 return Ex;
7305}
7306
Anna Zaks13b08572012-08-08 21:42:23 +00007307static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7308 ASTContext &Context) {
7309 // Only handle constant-sized or VLAs, but not flexible members.
7310 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7311 // Only issue the FIXIT for arrays of size > 1.
7312 if (CAT->getSize().getSExtValue() <= 1)
7313 return false;
7314 } else if (!Ty->isVariableArrayType()) {
7315 return false;
7316 }
7317 return true;
7318}
7319
Ted Kremenek6865f772011-08-18 20:55:45 +00007320// Warn if the user has made the 'size' argument to strlcpy or strlcat
7321// be the size of the source, instead of the destination.
7322void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7323 IdentifierInfo *FnName) {
7324
7325 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007326 unsigned NumArgs = Call->getNumArgs();
7327 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007328 return;
7329
7330 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7331 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007332 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007333
7334 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7335 Call->getLocStart(), Call->getRParenLoc()))
7336 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00007337
7338 // Look for 'strlcpy(dst, x, sizeof(x))'
7339 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7340 CompareWithSrc = Ex;
7341 else {
7342 // Look for 'strlcpy(dst, x, strlen(x))'
7343 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00007344 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7345 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00007346 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7347 }
7348 }
7349
7350 if (!CompareWithSrc)
7351 return;
7352
7353 // Determine if the argument to sizeof/strlen is equal to the source
7354 // argument. In principle there's all kinds of things you could do
7355 // here, for instance creating an == expression and evaluating it with
7356 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7357 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7358 if (!SrcArgDRE)
7359 return;
7360
7361 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7362 if (!CompareWithSrcDRE ||
7363 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7364 return;
7365
7366 const Expr *OriginalSizeArg = Call->getArg(2);
7367 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7368 << OriginalSizeArg->getSourceRange() << FnName;
7369
7370 // Output a FIXIT hint if the destination is an array (rather than a
7371 // pointer to an array). This could be enhanced to handle some
7372 // pointers if we know the actual size, like if DstArg is 'array+2'
7373 // we could say 'sizeof(array)-2'.
7374 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00007375 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00007376 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007377
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007378 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007379 llvm::raw_svector_ostream OS(sizeString);
7380 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007381 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00007382 OS << ")";
7383
7384 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7385 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7386 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00007387}
7388
Anna Zaks314cd092012-02-01 19:08:57 +00007389/// Check if two expressions refer to the same declaration.
7390static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7391 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7392 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7393 return D1->getDecl() == D2->getDecl();
7394 return false;
7395}
7396
7397static const Expr *getStrlenExprArg(const Expr *E) {
7398 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7399 const FunctionDecl *FD = CE->getDirectCallee();
7400 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00007401 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007402 return CE->getArg(0)->IgnoreParenCasts();
7403 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007404 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007405}
7406
7407// Warn on anti-patterns as the 'size' argument to strncat.
7408// The correct size argument should look like following:
7409// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7410void Sema::CheckStrncatArguments(const CallExpr *CE,
7411 IdentifierInfo *FnName) {
7412 // Don't crash if the user has the wrong number of arguments.
7413 if (CE->getNumArgs() < 3)
7414 return;
7415 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7416 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7417 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7418
Nico Weber0e6daef2013-12-26 23:38:39 +00007419 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7420 CE->getRParenLoc()))
7421 return;
7422
Anna Zaks314cd092012-02-01 19:08:57 +00007423 // Identify common expressions, which are wrongly used as the size argument
7424 // to strncat and may lead to buffer overflows.
7425 unsigned PatternType = 0;
7426 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7427 // - sizeof(dst)
7428 if (referToTheSameDecl(SizeOfArg, DstArg))
7429 PatternType = 1;
7430 // - sizeof(src)
7431 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7432 PatternType = 2;
7433 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7434 if (BE->getOpcode() == BO_Sub) {
7435 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7436 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7437 // - sizeof(dst) - strlen(dst)
7438 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7439 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7440 PatternType = 1;
7441 // - sizeof(src) - (anything)
7442 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7443 PatternType = 2;
7444 }
7445 }
7446
7447 if (PatternType == 0)
7448 return;
7449
Anna Zaks5069aa32012-02-03 01:27:37 +00007450 // Generate the diagnostic.
7451 SourceLocation SL = LenArg->getLocStart();
7452 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007453 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00007454
7455 // If the function is defined as a builtin macro, do not show macro expansion.
7456 if (SM.isMacroArgExpansion(SL)) {
7457 SL = SM.getSpellingLoc(SL);
7458 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7459 SM.getSpellingLoc(SR.getEnd()));
7460 }
7461
Anna Zaks13b08572012-08-08 21:42:23 +00007462 // Check if the destination is an array (rather than a pointer to an array).
7463 QualType DstTy = DstArg->getType();
7464 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7465 Context);
7466 if (!isKnownSizeArray) {
7467 if (PatternType == 1)
7468 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7469 else
7470 Diag(SL, diag::warn_strncat_src_size) << SR;
7471 return;
7472 }
7473
Anna Zaks314cd092012-02-01 19:08:57 +00007474 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00007475 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007476 else
Anna Zaks5069aa32012-02-03 01:27:37 +00007477 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007478
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007479 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00007480 llvm::raw_svector_ostream OS(sizeString);
7481 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007482 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007483 OS << ") - ";
7484 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007485 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007486 OS << ") - 1";
7487
Anna Zaks5069aa32012-02-03 01:27:37 +00007488 Diag(SL, diag::note_strncat_wrong_size)
7489 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00007490}
7491
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007492//===--- CHECK: Return Address of Stack Variable --------------------------===//
7493
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007494static const Expr *EvalVal(const Expr *E,
7495 SmallVectorImpl<const DeclRefExpr *> &refVars,
7496 const Decl *ParentDecl);
7497static const Expr *EvalAddr(const Expr *E,
7498 SmallVectorImpl<const DeclRefExpr *> &refVars,
7499 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007500
7501/// CheckReturnStackAddr - Check if a return statement returns the address
7502/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007503static void
7504CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7505 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00007506
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007507 const Expr *stackE = nullptr;
7508 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007509
7510 // Perform checking for returned stack addresses, local blocks,
7511 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00007512 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007513 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007514 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00007515 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007516 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007517 }
7518
Craig Topperc3ec1492014-05-26 06:22:03 +00007519 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007520 return; // Nothing suspicious was found.
7521
Simon Pilgrim750bde62017-03-31 11:00:53 +00007522 // Parameters are initialized in the calling scope, so taking the address
Richard Trieu81b6c562016-08-05 23:24:47 +00007523 // of a parameter reference doesn't need a warning.
7524 for (auto *DRE : refVars)
7525 if (isa<ParmVarDecl>(DRE->getDecl()))
7526 return;
7527
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007528 SourceLocation diagLoc;
7529 SourceRange diagRange;
7530 if (refVars.empty()) {
7531 diagLoc = stackE->getLocStart();
7532 diagRange = stackE->getSourceRange();
7533 } else {
7534 // We followed through a reference variable. 'stackE' contains the
7535 // problematic expression but we will warn at the return statement pointing
7536 // at the reference variable. We will later display the "trail" of
7537 // reference variables using notes.
7538 diagLoc = refVars[0]->getLocStart();
7539 diagRange = refVars[0]->getSourceRange();
7540 }
7541
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007542 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7543 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00007544 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007545 << DR->getDecl()->getDeclName() << diagRange;
7546 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007547 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007548 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007549 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007550 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00007551 // If there is an LValue->RValue conversion, then the value of the
7552 // reference type is used, not the reference.
7553 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7554 if (ICE->getCastKind() == CK_LValueToRValue) {
7555 return;
7556 }
7557 }
Craig Topperda7b27f2015-11-17 05:40:09 +00007558 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7559 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007560 }
7561
7562 // Display the "trail" of reference variables that we followed until we
7563 // found the problematic expression using notes.
7564 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007565 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007566 // If this var binds to another reference var, show the range of the next
7567 // var, otherwise the var binds to the problematic expression, in which case
7568 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007569 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7570 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007571 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7572 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007573 }
7574}
7575
7576/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7577/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007578/// to a location on the stack, a local block, an address of a label, or a
7579/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007580/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007581/// encounter a subexpression that (1) clearly does not lead to one of the
7582/// above problematic expressions (2) is something we cannot determine leads to
7583/// a problematic expression based on such local checking.
7584///
7585/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7586/// the expression that they point to. Such variables are added to the
7587/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007588///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007589/// EvalAddr processes expressions that are pointers that are used as
7590/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007591/// At the base case of the recursion is a check for the above problematic
7592/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007593///
7594/// This implementation handles:
7595///
7596/// * pointer-to-pointer casts
7597/// * implicit conversions from array references to pointers
7598/// * taking the address of fields
7599/// * arbitrary interplay between "&" and "*" operators
7600/// * pointer arithmetic from an address of a stack variable
7601/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007602static const Expr *EvalAddr(const Expr *E,
7603 SmallVectorImpl<const DeclRefExpr *> &refVars,
7604 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007605 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00007606 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007607
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007608 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00007609 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00007610 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007611 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00007612 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00007613
Peter Collingbourne91147592011-04-15 00:35:48 +00007614 E = E->IgnoreParens();
7615
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007616 // Our "symbolic interpreter" is just a dispatch off the currently
7617 // viewed AST node. We then recursively traverse the AST by calling
7618 // EvalAddr and EvalVal appropriately.
7619 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007620 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007621 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007622
Richard Smith40f08eb2014-01-30 22:05:38 +00007623 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00007624 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00007625 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00007626
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007627 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007628 // If this is a reference variable, follow through to the expression that
7629 // it points to.
7630 if (V->hasLocalStorage() &&
7631 V->getType()->isReferenceType() && V->hasInit()) {
7632 // Add the reference variable to the "trail".
7633 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007634 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007635 }
7636
Craig Topperc3ec1492014-05-26 06:22:03 +00007637 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007638 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007639
Chris Lattner934edb22007-12-28 05:31:15 +00007640 case Stmt::UnaryOperatorClass: {
7641 // The only unary operator that make sense to handle here
7642 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007643 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007644
John McCalle3027922010-08-25 11:45:40 +00007645 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007646 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007647 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007648 }
Mike Stump11289f42009-09-09 15:08:12 +00007649
Chris Lattner934edb22007-12-28 05:31:15 +00007650 case Stmt::BinaryOperatorClass: {
7651 // Handle pointer arithmetic. All other binary operators are not valid
7652 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007653 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00007654 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00007655
John McCalle3027922010-08-25 11:45:40 +00007656 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00007657 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007658
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007659 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00007660
7661 // Determine which argument is the real pointer base. It could be
7662 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007663 if (!Base->getType()->isPointerType())
7664 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00007665
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007666 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007667 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007668 }
Steve Naroff2752a172008-09-10 19:17:48 +00007669
Chris Lattner934edb22007-12-28 05:31:15 +00007670 // For conditional operators we need to see if either the LHS or RHS are
7671 // valid DeclRefExpr*s. If one of them is valid, we return it.
7672 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007673 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007674
Chris Lattner934edb22007-12-28 05:31:15 +00007675 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007676 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007677 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007678 // In C++, we can have a throw-expression, which has 'void' type.
7679 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007680 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007681 return LHS;
7682 }
Chris Lattner934edb22007-12-28 05:31:15 +00007683
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007684 // In C++, we can have a throw-expression, which has 'void' type.
7685 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00007686 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007687
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007688 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007689 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007690
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007691 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00007692 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007693 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00007694 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007695
7696 case Stmt::AddrLabelExprClass:
7697 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00007698
John McCall28fc7092011-11-10 05:35:25 +00007699 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007700 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7701 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00007702
Ted Kremenekc3b4c522008-08-07 00:49:01 +00007703 // For casts, we need to handle conversions from arrays to
7704 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00007705 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00007706 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007707 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00007708 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00007709 case Stmt::CXXStaticCastExprClass:
7710 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00007711 case Stmt::CXXConstCastExprClass:
7712 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007713 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00007714 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00007715 case CK_LValueToRValue:
7716 case CK_NoOp:
7717 case CK_BaseToDerived:
7718 case CK_DerivedToBase:
7719 case CK_UncheckedDerivedToBase:
7720 case CK_Dynamic:
7721 case CK_CPointerToObjCPointerCast:
7722 case CK_BlockPointerToObjCPointerCast:
7723 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007724 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007725
7726 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007727 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007728
Richard Trieudadefde2014-07-02 04:39:38 +00007729 case CK_BitCast:
7730 if (SubExpr->getType()->isAnyPointerType() ||
7731 SubExpr->getType()->isBlockPointerType() ||
7732 SubExpr->getType()->isObjCQualifiedIdType())
7733 return EvalAddr(SubExpr, refVars, ParentDecl);
7734 else
7735 return nullptr;
7736
Eli Friedman8195ad72012-02-23 23:04:32 +00007737 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007738 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00007739 }
Chris Lattner934edb22007-12-28 05:31:15 +00007740 }
Mike Stump11289f42009-09-09 15:08:12 +00007741
Douglas Gregorfe314812011-06-21 17:03:29 +00007742 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007743 if (const Expr *Result =
7744 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7745 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00007746 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00007747 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007748
Chris Lattner934edb22007-12-28 05:31:15 +00007749 // Everything else: we simply don't reason about them.
7750 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007751 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00007752 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007753}
Mike Stump11289f42009-09-09 15:08:12 +00007754
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007755/// EvalVal - This function is complements EvalAddr in the mutual recursion.
7756/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007757static const Expr *EvalVal(const Expr *E,
7758 SmallVectorImpl<const DeclRefExpr *> &refVars,
7759 const Decl *ParentDecl) {
7760 do {
7761 // We should only be called for evaluating non-pointer expressions, or
7762 // expressions with a pointer type that are not used as references but
7763 // instead
7764 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00007765
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007766 // Our "symbolic interpreter" is just a dispatch off the currently
7767 // viewed AST node. We then recursively traverse the AST by calling
7768 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00007769
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007770 E = E->IgnoreParens();
7771 switch (E->getStmtClass()) {
7772 case Stmt::ImplicitCastExprClass: {
7773 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7774 if (IE->getValueKind() == VK_LValue) {
7775 E = IE->getSubExpr();
7776 continue;
7777 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007778 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007779 }
Richard Smith40f08eb2014-01-30 22:05:38 +00007780
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007781 case Stmt::ExprWithCleanupsClass:
7782 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7783 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007784
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007785 case Stmt::DeclRefExprClass: {
7786 // When we hit a DeclRefExpr we are looking at code that refers to a
7787 // variable's name. If it's not a reference variable we check if it has
7788 // local storage within the function, and if so, return the expression.
7789 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7790
7791 // If we leave the immediate function, the lifetime isn't about to end.
7792 if (DR->refersToEnclosingVariableOrCapture())
7793 return nullptr;
7794
7795 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7796 // Check if it refers to itself, e.g. "int& i = i;".
7797 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007798 return DR;
7799
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007800 if (V->hasLocalStorage()) {
7801 if (!V->getType()->isReferenceType())
7802 return DR;
7803
7804 // Reference variable, follow through to the expression that
7805 // it points to.
7806 if (V->hasInit()) {
7807 // Add the reference variable to the "trail".
7808 refVars.push_back(DR);
7809 return EvalVal(V->getInit(), refVars, V);
7810 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007811 }
7812 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007813
7814 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007815 }
Mike Stump11289f42009-09-09 15:08:12 +00007816
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007817 case Stmt::UnaryOperatorClass: {
7818 // The only unary operator that make sense to handle here
7819 // is Deref. All others don't resolve to a "name." This includes
7820 // handling all sorts of rvalues passed to a unary operator.
7821 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007822
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007823 if (U->getOpcode() == UO_Deref)
7824 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007825
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007826 return nullptr;
7827 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007828
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007829 case Stmt::ArraySubscriptExprClass: {
7830 // Array subscripts are potential references to data on the stack. We
7831 // retrieve the DeclRefExpr* for the array variable if it indeed
7832 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00007833 const auto *ASE = cast<ArraySubscriptExpr>(E);
7834 if (ASE->isTypeDependent())
7835 return nullptr;
7836 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007837 }
Mike Stump11289f42009-09-09 15:08:12 +00007838
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007839 case Stmt::OMPArraySectionExprClass: {
7840 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7841 ParentDecl);
7842 }
Mike Stump11289f42009-09-09 15:08:12 +00007843
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007844 case Stmt::ConditionalOperatorClass: {
7845 // For conditional operators we need to see if either the LHS or RHS are
7846 // non-NULL Expr's. If one is non-NULL, we return it.
7847 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007848
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007849 // Handle the GNU extension for missing LHS.
7850 if (const Expr *LHSExpr = C->getLHS()) {
7851 // In C++, we can have a throw-expression, which has 'void' type.
7852 if (!LHSExpr->getType()->isVoidType())
7853 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7854 return LHS;
7855 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007856
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007857 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007858 if (C->getRHS()->getType()->isVoidType())
7859 return nullptr;
7860
7861 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007862 }
7863
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007864 // Accesses to members are potential references to data on the stack.
7865 case Stmt::MemberExprClass: {
7866 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00007867
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007868 // Check for indirect access. We only want direct field accesses.
7869 if (M->isArrow())
7870 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007871
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007872 // Check whether the member type is itself a reference, in which case
7873 // we're not going to refer to the member, but to what the member refers
7874 // to.
7875 if (M->getMemberDecl()->getType()->isReferenceType())
7876 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007877
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007878 return EvalVal(M->getBase(), refVars, ParentDecl);
7879 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00007880
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007881 case Stmt::MaterializeTemporaryExprClass:
7882 if (const Expr *Result =
7883 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7884 refVars, ParentDecl))
7885 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007886 return E;
7887
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007888 default:
7889 // Check that we don't return or take the address of a reference to a
7890 // temporary. This is only useful in C++.
7891 if (!E->isTypeDependent() && E->isRValue())
7892 return E;
7893
7894 // Everything else: we simply don't reason about them.
7895 return nullptr;
7896 }
7897 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007898}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007899
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007900void
7901Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7902 SourceLocation ReturnLoc,
7903 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00007904 const AttrVec *Attrs,
7905 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007906 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7907
7908 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00007909 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7910 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00007911 CheckNonNullExpr(*this, RetValExp))
7912 Diag(ReturnLoc, diag::warn_null_ret)
7913 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00007914
7915 // C++11 [basic.stc.dynamic.allocation]p4:
7916 // If an allocation function declared with a non-throwing
7917 // exception-specification fails to allocate storage, it shall return
7918 // a null pointer. Any other allocation function that fails to allocate
7919 // storage shall indicate failure only by throwing an exception [...]
7920 if (FD) {
7921 OverloadedOperatorKind Op = FD->getOverloadedOperator();
7922 if (Op == OO_New || Op == OO_Array_New) {
7923 const FunctionProtoType *Proto
7924 = FD->getType()->castAs<FunctionProtoType>();
7925 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7926 CheckNonNullExpr(*this, RetValExp))
7927 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7928 << FD << getLangOpts().CPlusPlus11;
7929 }
7930 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007931}
7932
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007933//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7934
7935/// Check for comparisons of floating point operands using != and ==.
7936/// Issue a warning if these are no self-comparisons, as they are not likely
7937/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00007938void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00007939 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7940 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007941
7942 // Special case: check for x == x (which is OK).
7943 // Do not emit warnings for such cases.
7944 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7945 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7946 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00007947 return;
Mike Stump11289f42009-09-09 15:08:12 +00007948
Ted Kremenekeda40e22007-11-29 00:59:04 +00007949 // Special case: check for comparisons against literals that can be exactly
7950 // represented by APFloat. In such cases, do not emit a warning. This
7951 // is a heuristic: often comparison against such literals are used to
7952 // detect if a value in a variable has not changed. This clearly can
7953 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00007954 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7955 if (FLL->isExact())
7956 return;
7957 } else
7958 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7959 if (FLR->isExact())
7960 return;
Mike Stump11289f42009-09-09 15:08:12 +00007961
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007962 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00007963 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007964 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007965 return;
Mike Stump11289f42009-09-09 15:08:12 +00007966
David Blaikie1f4ff152012-07-16 20:47:22 +00007967 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007968 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007969 return;
Mike Stump11289f42009-09-09 15:08:12 +00007970
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007971 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00007972 Diag(Loc, diag::warn_floatingpoint_eq)
7973 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007974}
John McCallca01b222010-01-04 23:21:16 +00007975
John McCall70aa5392010-01-06 05:24:50 +00007976//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7977//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00007978
John McCall70aa5392010-01-06 05:24:50 +00007979namespace {
John McCallca01b222010-01-04 23:21:16 +00007980
John McCall70aa5392010-01-06 05:24:50 +00007981/// Structure recording the 'active' range of an integer-valued
7982/// expression.
7983struct IntRange {
7984 /// The number of bits active in the int.
7985 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00007986
John McCall70aa5392010-01-06 05:24:50 +00007987 /// True if the int is known not to have negative values.
7988 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00007989
John McCall70aa5392010-01-06 05:24:50 +00007990 IntRange(unsigned Width, bool NonNegative)
7991 : Width(Width), NonNegative(NonNegative)
7992 {}
John McCallca01b222010-01-04 23:21:16 +00007993
John McCall817d4af2010-11-10 23:38:19 +00007994 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00007995 static IntRange forBoolType() {
7996 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00007997 }
7998
John McCall817d4af2010-11-10 23:38:19 +00007999 /// Returns the range of an opaque value of the given integral type.
8000 static IntRange forValueOfType(ASTContext &C, QualType T) {
8001 return forValueOfCanonicalType(C,
8002 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00008003 }
8004
John McCall817d4af2010-11-10 23:38:19 +00008005 /// Returns the range of an opaque value of a canonical integral type.
8006 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00008007 assert(T->isCanonicalUnqualified());
8008
8009 if (const VectorType *VT = dyn_cast<VectorType>(T))
8010 T = VT->getElementType().getTypePtr();
8011 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8012 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008013 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8014 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00008015
David Majnemer6a426652013-06-07 22:07:20 +00008016 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00008017 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00008018 EnumDecl *Enum = ET->getDecl();
8019 if (!Enum->isCompleteDefinition())
8020 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00008021
David Majnemer6a426652013-06-07 22:07:20 +00008022 unsigned NumPositive = Enum->getNumPositiveBits();
8023 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00008024
David Majnemer6a426652013-06-07 22:07:20 +00008025 if (NumNegative == 0)
8026 return IntRange(NumPositive, true/*NonNegative*/);
8027 else
8028 return IntRange(std::max(NumPositive + 1, NumNegative),
8029 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00008030 }
John McCall70aa5392010-01-06 05:24:50 +00008031
8032 const BuiltinType *BT = cast<BuiltinType>(T);
8033 assert(BT->isInteger());
8034
8035 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8036 }
8037
John McCall817d4af2010-11-10 23:38:19 +00008038 /// Returns the "target" range of a canonical integral type, i.e.
8039 /// the range of values expressible in the type.
8040 ///
8041 /// This matches forValueOfCanonicalType except that enums have the
8042 /// full range of their type, not the range of their enumerators.
8043 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8044 assert(T->isCanonicalUnqualified());
8045
8046 if (const VectorType *VT = dyn_cast<VectorType>(T))
8047 T = VT->getElementType().getTypePtr();
8048 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8049 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008050 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8051 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008052 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00008053 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008054
8055 const BuiltinType *BT = cast<BuiltinType>(T);
8056 assert(BT->isInteger());
8057
8058 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8059 }
8060
8061 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00008062 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00008063 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00008064 L.NonNegative && R.NonNegative);
8065 }
8066
John McCall817d4af2010-11-10 23:38:19 +00008067 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008068 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008069 return IntRange(std::min(L.Width, R.Width),
8070 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008071 }
8072};
8073
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008074IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008075 if (value.isSigned() && value.isNegative())
8076 return IntRange(value.getMinSignedBits(), false);
8077
8078 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008079 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008080
8081 // isNonNegative() just checks the sign bit without considering
8082 // signedness.
8083 return IntRange(value.getActiveBits(), true);
8084}
8085
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008086IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8087 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008088 if (result.isInt())
8089 return GetValueRange(C, result.getInt(), MaxWidth);
8090
8091 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008092 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8093 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8094 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8095 R = IntRange::join(R, El);
8096 }
John McCall70aa5392010-01-06 05:24:50 +00008097 return R;
8098 }
8099
8100 if (result.isComplexInt()) {
8101 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8102 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8103 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008104 }
8105
8106 // This can happen with lossless casts to intptr_t of "based" lvalues.
8107 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008108 // FIXME: The only reason we need to pass the type in here is to get
8109 // the sign right on this one case. It would be nice if APValue
8110 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008111 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008112 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008113}
John McCall70aa5392010-01-06 05:24:50 +00008114
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008115QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008116 QualType Ty = E->getType();
8117 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8118 Ty = AtomicRHS->getValueType();
8119 return Ty;
8120}
8121
John McCall70aa5392010-01-06 05:24:50 +00008122/// Pseudo-evaluate the given integer expression, estimating the
8123/// range of values it might take.
8124///
8125/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008126IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008127 E = E->IgnoreParens();
8128
8129 // Try a full evaluation first.
8130 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008131 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008132 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008133
8134 // I think we only want to look through implicit casts here; if the
8135 // user has an explicit widening cast, we should treat the value as
8136 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008137 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00008138 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00008139 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8140
Eli Friedmane6d33952013-07-08 20:20:06 +00008141 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00008142
George Burgess IVdf1ed002016-01-13 01:52:39 +00008143 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8144 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00008145
John McCall70aa5392010-01-06 05:24:50 +00008146 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00008147 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00008148 return OutputTypeRange;
8149
8150 IntRange SubRange
8151 = GetExprRange(C, CE->getSubExpr(),
8152 std::min(MaxWidth, OutputTypeRange.Width));
8153
8154 // Bail out if the subexpr's range is as wide as the cast type.
8155 if (SubRange.Width >= OutputTypeRange.Width)
8156 return OutputTypeRange;
8157
8158 // Otherwise, we take the smaller width, and we're non-negative if
8159 // either the output type or the subexpr is.
8160 return IntRange(SubRange.Width,
8161 SubRange.NonNegative || OutputTypeRange.NonNegative);
8162 }
8163
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008164 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008165 // If we can fold the condition, just take that operand.
8166 bool CondResult;
8167 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8168 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8169 : CO->getFalseExpr(),
8170 MaxWidth);
8171
8172 // Otherwise, conservatively merge.
8173 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8174 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8175 return IntRange::join(L, R);
8176 }
8177
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008178 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008179 switch (BO->getOpcode()) {
8180
8181 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00008182 case BO_LAnd:
8183 case BO_LOr:
8184 case BO_LT:
8185 case BO_GT:
8186 case BO_LE:
8187 case BO_GE:
8188 case BO_EQ:
8189 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00008190 return IntRange::forBoolType();
8191
John McCallc3688382011-07-13 06:35:24 +00008192 // The type of the assignments is the type of the LHS, so the RHS
8193 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00008194 case BO_MulAssign:
8195 case BO_DivAssign:
8196 case BO_RemAssign:
8197 case BO_AddAssign:
8198 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00008199 case BO_XorAssign:
8200 case BO_OrAssign:
8201 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00008202 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00008203
John McCallc3688382011-07-13 06:35:24 +00008204 // Simple assignments just pass through the RHS, which will have
8205 // been coerced to the LHS type.
8206 case BO_Assign:
8207 // TODO: bitfields?
8208 return GetExprRange(C, BO->getRHS(), MaxWidth);
8209
John McCall70aa5392010-01-06 05:24:50 +00008210 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008211 case BO_PtrMemD:
8212 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00008213 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008214
John McCall2ce81ad2010-01-06 22:07:33 +00008215 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00008216 case BO_And:
8217 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00008218 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8219 GetExprRange(C, BO->getRHS(), MaxWidth));
8220
John McCall70aa5392010-01-06 05:24:50 +00008221 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00008222 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00008223 // ...except that we want to treat '1 << (blah)' as logically
8224 // positive. It's an important idiom.
8225 if (IntegerLiteral *I
8226 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8227 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008228 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00008229 return IntRange(R.Width, /*NonNegative*/ true);
8230 }
8231 }
8232 // fallthrough
8233
John McCalle3027922010-08-25 11:45:40 +00008234 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00008235 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008236
John McCall2ce81ad2010-01-06 22:07:33 +00008237 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00008238 case BO_Shr:
8239 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00008240 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8241
8242 // If the shift amount is a positive constant, drop the width by
8243 // that much.
8244 llvm::APSInt shift;
8245 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8246 shift.isNonNegative()) {
8247 unsigned zext = shift.getZExtValue();
8248 if (zext >= L.Width)
8249 L.Width = (L.NonNegative ? 0 : 1);
8250 else
8251 L.Width -= zext;
8252 }
8253
8254 return L;
8255 }
8256
8257 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008258 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008259 return GetExprRange(C, BO->getRHS(), MaxWidth);
8260
John McCall2ce81ad2010-01-06 22:07:33 +00008261 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008262 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008263 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008264 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008265 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008266
John McCall51431812011-07-14 22:39:48 +00008267 // The width of a division result is mostly determined by the size
8268 // of the LHS.
8269 case BO_Div: {
8270 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008271 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008272 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8273
8274 // If the divisor is constant, use that.
8275 llvm::APSInt divisor;
8276 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8277 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8278 if (log2 >= L.Width)
8279 L.Width = (L.NonNegative ? 0 : 1);
8280 else
8281 L.Width = std::min(L.Width - log2, MaxWidth);
8282 return L;
8283 }
8284
8285 // Otherwise, just use the LHS's width.
8286 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8287 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8288 }
8289
8290 // The result of a remainder can't be larger than the result of
8291 // either side.
8292 case BO_Rem: {
8293 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008294 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008295 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8296 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8297
8298 IntRange meet = IntRange::meet(L, R);
8299 meet.Width = std::min(meet.Width, MaxWidth);
8300 return meet;
8301 }
8302
8303 // The default behavior is okay for these.
8304 case BO_Mul:
8305 case BO_Add:
8306 case BO_Xor:
8307 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008308 break;
8309 }
8310
John McCall51431812011-07-14 22:39:48 +00008311 // The default case is to treat the operation as if it were closed
8312 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008313 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8314 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8315 return IntRange::join(L, R);
8316 }
8317
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008318 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008319 switch (UO->getOpcode()) {
8320 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008321 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008322 return IntRange::forBoolType();
8323
8324 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008325 case UO_Deref:
8326 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00008327 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008328
8329 default:
8330 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8331 }
8332 }
8333
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008334 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00008335 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8336
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008337 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00008338 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00008339 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00008340
Eli Friedmane6d33952013-07-08 20:20:06 +00008341 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008342}
John McCall263a48b2010-01-04 23:31:57 +00008343
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008344IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008345 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00008346}
8347
John McCall263a48b2010-01-04 23:31:57 +00008348/// Checks whether the given value, which currently has the given
8349/// source semantics, has the same value when coerced through the
8350/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008351bool IsSameFloatAfterCast(const llvm::APFloat &value,
8352 const llvm::fltSemantics &Src,
8353 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008354 llvm::APFloat truncated = value;
8355
8356 bool ignored;
8357 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8358 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8359
8360 return truncated.bitwiseIsEqual(value);
8361}
8362
8363/// Checks whether the given value, which currently has the given
8364/// source semantics, has the same value when coerced through the
8365/// target semantics.
8366///
8367/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008368bool IsSameFloatAfterCast(const APValue &value,
8369 const llvm::fltSemantics &Src,
8370 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008371 if (value.isFloat())
8372 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8373
8374 if (value.isVector()) {
8375 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8376 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8377 return false;
8378 return true;
8379 }
8380
8381 assert(value.isComplexFloat());
8382 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8383 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8384}
8385
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008386void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008387
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008388bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00008389 // Suppress cases where we are comparing against an enum constant.
8390 if (const DeclRefExpr *DR =
8391 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8392 if (isa<EnumConstantDecl>(DR->getDecl()))
8393 return false;
8394
8395 // Suppress cases where the '0' value is expanded from a macro.
8396 if (E->getLocStart().isMacroID())
8397 return false;
8398
John McCallcc7e5bf2010-05-06 08:58:33 +00008399 llvm::APSInt Value;
8400 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8401}
8402
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008403bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00008404 // Strip off implicit integral promotions.
8405 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008406 if (ICE->getCastKind() != CK_IntegralCast &&
8407 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00008408 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008409 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00008410 }
8411
8412 return E->getType()->isEnumeralType();
8413}
8414
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008415void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00008416 // Disable warning in template instantiations.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008417 if (S.inTemplateInstantiation())
Richard Trieu36594562013-11-01 21:47:19 +00008418 return;
8419
John McCalle3027922010-08-25 11:45:40 +00008420 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00008421 if (E->isValueDependent())
8422 return;
8423
John McCalle3027922010-08-25 11:45:40 +00008424 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008425 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008426 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008427 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008428 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008429 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008430 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008431 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008432 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008433 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008434 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008435 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008436 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008437 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008438 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008439 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8440 }
8441}
8442
Benjamin Kramer7320b992016-06-15 14:20:56 +00008443void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8444 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008445 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00008446 // Disable warning in template instantiations.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008447 if (S.inTemplateInstantiation())
Richard Trieudd51d742013-11-01 21:19:43 +00008448 return;
8449
Richard Trieu0f097742014-04-04 04:13:47 +00008450 // TODO: Investigate using GetExprRange() to get tighter bounds
8451 // on the bit ranges.
8452 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00008453 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00008454 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00008455 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8456 unsigned OtherWidth = OtherRange.Width;
8457
8458 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8459
Richard Trieu560910c2012-11-14 22:50:24 +00008460 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00008461 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00008462 return;
8463
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008464 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00008465 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008466
Richard Trieu0f097742014-04-04 04:13:47 +00008467 // Used for diagnostic printout.
8468 enum {
8469 LiteralConstant = 0,
8470 CXXBoolLiteralTrue,
8471 CXXBoolLiteralFalse
8472 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008473
Richard Trieu0f097742014-04-04 04:13:47 +00008474 if (!OtherIsBooleanType) {
8475 QualType ConstantT = Constant->getType();
8476 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00008477
Richard Trieu0f097742014-04-04 04:13:47 +00008478 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8479 return;
8480 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8481 "comparison with non-integer type");
8482
8483 bool ConstantSigned = ConstantT->isSignedIntegerType();
8484 bool CommonSigned = CommonT->isSignedIntegerType();
8485
8486 bool EqualityOnly = false;
8487
8488 if (CommonSigned) {
8489 // The common type is signed, therefore no signed to unsigned conversion.
8490 if (!OtherRange.NonNegative) {
8491 // Check that the constant is representable in type OtherT.
8492 if (ConstantSigned) {
8493 if (OtherWidth >= Value.getMinSignedBits())
8494 return;
8495 } else { // !ConstantSigned
8496 if (OtherWidth >= Value.getActiveBits() + 1)
8497 return;
8498 }
8499 } else { // !OtherSigned
8500 // Check that the constant is representable in type OtherT.
8501 // Negative values are out of range.
8502 if (ConstantSigned) {
8503 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8504 return;
8505 } else { // !ConstantSigned
8506 if (OtherWidth >= Value.getActiveBits())
8507 return;
8508 }
Richard Trieu560910c2012-11-14 22:50:24 +00008509 }
Richard Trieu0f097742014-04-04 04:13:47 +00008510 } else { // !CommonSigned
8511 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00008512 if (OtherWidth >= Value.getActiveBits())
8513 return;
Craig Toppercf360162014-06-18 05:13:11 +00008514 } else { // OtherSigned
8515 assert(!ConstantSigned &&
8516 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00008517 // Check to see if the constant is representable in OtherT.
8518 if (OtherWidth > Value.getActiveBits())
8519 return;
8520 // Check to see if the constant is equivalent to a negative value
8521 // cast to CommonT.
8522 if (S.Context.getIntWidth(ConstantT) ==
8523 S.Context.getIntWidth(CommonT) &&
8524 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8525 return;
8526 // The constant value rests between values that OtherT can represent
8527 // after conversion. Relational comparison still works, but equality
8528 // comparisons will be tautological.
8529 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008530 }
8531 }
Richard Trieu0f097742014-04-04 04:13:47 +00008532
8533 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8534
8535 if (op == BO_EQ || op == BO_NE) {
8536 IsTrue = op == BO_NE;
8537 } else if (EqualityOnly) {
8538 return;
8539 } else if (RhsConstant) {
8540 if (op == BO_GT || op == BO_GE)
8541 IsTrue = !PositiveConstant;
8542 else // op == BO_LT || op == BO_LE
8543 IsTrue = PositiveConstant;
8544 } else {
8545 if (op == BO_LT || op == BO_LE)
8546 IsTrue = !PositiveConstant;
8547 else // op == BO_GT || op == BO_GE
8548 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008549 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008550 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00008551 // Other isKnownToHaveBooleanValue
8552 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8553 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8554 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8555
8556 static const struct LinkedConditions {
8557 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8558 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8559 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8560 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8561 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8562 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8563
8564 } TruthTable = {
8565 // Constant on LHS. | Constant on RHS. |
8566 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
8567 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8568 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8569 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8570 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8571 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8572 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8573 };
8574
8575 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8576
8577 enum ConstantValue ConstVal = Zero;
8578 if (Value.isUnsigned() || Value.isNonNegative()) {
8579 if (Value == 0) {
8580 LiteralOrBoolConstant =
8581 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8582 ConstVal = Zero;
8583 } else if (Value == 1) {
8584 LiteralOrBoolConstant =
8585 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8586 ConstVal = One;
8587 } else {
8588 LiteralOrBoolConstant = LiteralConstant;
8589 ConstVal = GT_One;
8590 }
8591 } else {
8592 ConstVal = LT_Zero;
8593 }
8594
8595 CompareBoolWithConstantResult CmpRes;
8596
8597 switch (op) {
8598 case BO_LT:
8599 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8600 break;
8601 case BO_GT:
8602 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8603 break;
8604 case BO_LE:
8605 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8606 break;
8607 case BO_GE:
8608 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8609 break;
8610 case BO_EQ:
8611 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8612 break;
8613 case BO_NE:
8614 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8615 break;
8616 default:
8617 CmpRes = Unkwn;
8618 break;
8619 }
8620
8621 if (CmpRes == AFals) {
8622 IsTrue = false;
8623 } else if (CmpRes == ATrue) {
8624 IsTrue = true;
8625 } else {
8626 return;
8627 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008628 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008629
8630 // If this is a comparison to an enum constant, include that
8631 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00008632 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008633 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8634 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8635
8636 SmallString<64> PrettySourceValue;
8637 llvm::raw_svector_ostream OS(PrettySourceValue);
8638 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00008639 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008640 else
8641 OS << Value;
8642
Richard Trieu0f097742014-04-04 04:13:47 +00008643 S.DiagRuntimeBehavior(
8644 E->getOperatorLoc(), E,
8645 S.PDiag(diag::warn_out_of_range_compare)
8646 << OS.str() << LiteralOrBoolConstant
8647 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8648 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008649}
8650
John McCallcc7e5bf2010-05-06 08:58:33 +00008651/// Analyze the operands of the given comparison. Implements the
8652/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008653void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00008654 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8655 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008656}
John McCall263a48b2010-01-04 23:31:57 +00008657
John McCallca01b222010-01-04 23:21:16 +00008658/// \brief Implements -Wsign-compare.
8659///
Richard Trieu82402a02011-09-15 21:56:47 +00008660/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008661void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008662 // The type the comparison is being performed in.
8663 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00008664
8665 // Only analyze comparison operators where both sides have been converted to
8666 // the same type.
8667 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8668 return AnalyzeImpConvsInComparison(S, E);
8669
8670 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00008671 if (E->isValueDependent())
8672 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008673
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008674 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8675 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008676
8677 bool IsComparisonConstant = false;
8678
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008679 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008680 // of 'true' or 'false'.
8681 if (T->isIntegralType(S.Context)) {
8682 llvm::APSInt RHSValue;
8683 bool IsRHSIntegralLiteral =
8684 RHS->isIntegerConstantExpr(RHSValue, S.Context);
8685 llvm::APSInt LHSValue;
8686 bool IsLHSIntegralLiteral =
8687 LHS->isIntegerConstantExpr(LHSValue, S.Context);
8688 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8689 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8690 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8691 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8692 else
8693 IsComparisonConstant =
8694 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008695 } else if (!T->hasUnsignedIntegerRepresentation())
8696 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008697
John McCallcc7e5bf2010-05-06 08:58:33 +00008698 // We don't do anything special if this isn't an unsigned integral
8699 // comparison: we're only interested in integral comparisons, and
8700 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00008701 //
8702 // We also don't care about value-dependent expressions or expressions
8703 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008704 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00008705 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008706
John McCallcc7e5bf2010-05-06 08:58:33 +00008707 // Check to see if one of the (unmodified) operands is of different
8708 // signedness.
8709 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00008710 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8711 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00008712 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00008713 signedOperand = LHS;
8714 unsignedOperand = RHS;
8715 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8716 signedOperand = RHS;
8717 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00008718 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00008719 CheckTrivialUnsignedComparison(S, E);
8720 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008721 }
8722
John McCallcc7e5bf2010-05-06 08:58:33 +00008723 // Otherwise, calculate the effective range of the signed operand.
8724 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00008725
John McCallcc7e5bf2010-05-06 08:58:33 +00008726 // Go ahead and analyze implicit conversions in the operands. Note
8727 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00008728 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8729 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00008730
John McCallcc7e5bf2010-05-06 08:58:33 +00008731 // If the signed range is non-negative, -Wsign-compare won't fire,
8732 // but we should still check for comparisons which are always true
8733 // or false.
8734 if (signedRange.NonNegative)
8735 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008736
8737 // For (in)equality comparisons, if the unsigned operand is a
8738 // constant which cannot collide with a overflowed signed operand,
8739 // then reinterpreting the signed operand as unsigned will not
8740 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00008741 if (E->isEqualityOp()) {
8742 unsigned comparisonWidth = S.Context.getIntWidth(T);
8743 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00008744
John McCallcc7e5bf2010-05-06 08:58:33 +00008745 // We should never be unable to prove that the unsigned operand is
8746 // non-negative.
8747 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8748
8749 if (unsignedRange.Width < comparisonWidth)
8750 return;
8751 }
8752
Douglas Gregorbfb4a212012-05-01 01:53:49 +00008753 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8754 S.PDiag(diag::warn_mixed_sign_comparison)
8755 << LHS->getType() << RHS->getType()
8756 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00008757}
8758
John McCall1f425642010-11-11 03:21:53 +00008759/// Analyzes an attempt to assign the given value to a bitfield.
8760///
8761/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008762bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8763 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00008764 assert(Bitfield->isBitField());
8765 if (Bitfield->isInvalidDecl())
8766 return false;
8767
John McCalldeebbcf2010-11-11 05:33:51 +00008768 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00008769 QualType BitfieldType = Bitfield->getType();
8770 if (BitfieldType->isBooleanType())
8771 return false;
8772
8773 if (BitfieldType->isEnumeralType()) {
8774 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
8775 // If the underlying enum type was not explicitly specified as an unsigned
8776 // type and the enum contain only positive values, MSVC++ will cause an
8777 // inconsistency by storing this as a signed type.
8778 if (S.getLangOpts().CPlusPlus11 &&
8779 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
8780 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
8781 BitfieldEnumDecl->getNumNegativeBits() == 0) {
8782 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
8783 << BitfieldEnumDecl->getNameAsString();
8784 }
8785 }
8786
John McCalldeebbcf2010-11-11 05:33:51 +00008787 if (Bitfield->getType()->isBooleanType())
8788 return false;
8789
Douglas Gregor789adec2011-02-04 13:09:01 +00008790 // Ignore value- or type-dependent expressions.
8791 if (Bitfield->getBitWidth()->isValueDependent() ||
8792 Bitfield->getBitWidth()->isTypeDependent() ||
8793 Init->isValueDependent() ||
8794 Init->isTypeDependent())
8795 return false;
8796
John McCall1f425642010-11-11 03:21:53 +00008797 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00008798 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00008799
Richard Smith5fab0c92011-12-28 19:48:30 +00008800 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00008801 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
8802 Expr::SE_AllowSideEffects)) {
8803 // The RHS is not constant. If the RHS has an enum type, make sure the
8804 // bitfield is wide enough to hold all the values of the enum without
8805 // truncation.
8806 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
8807 EnumDecl *ED = EnumTy->getDecl();
8808 bool SignedBitfield = BitfieldType->isSignedIntegerType();
8809
8810 // Enum types are implicitly signed on Windows, so check if there are any
8811 // negative enumerators to see if the enum was intended to be signed or
8812 // not.
8813 bool SignedEnum = ED->getNumNegativeBits() > 0;
8814
8815 // Check for surprising sign changes when assigning enum values to a
8816 // bitfield of different signedness. If the bitfield is signed and we
8817 // have exactly the right number of bits to store this unsigned enum,
8818 // suggest changing the enum to an unsigned type. This typically happens
8819 // on Windows where unfixed enums always use an underlying type of 'int'.
8820 unsigned DiagID = 0;
8821 if (SignedEnum && !SignedBitfield) {
8822 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
8823 } else if (SignedBitfield && !SignedEnum &&
8824 ED->getNumPositiveBits() == FieldWidth) {
8825 DiagID = diag::warn_signed_bitfield_enum_conversion;
8826 }
8827
8828 if (DiagID) {
8829 S.Diag(InitLoc, DiagID) << Bitfield << ED;
8830 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
8831 SourceRange TypeRange =
8832 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
8833 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
8834 << SignedEnum << TypeRange;
8835 }
8836
8837 // Compute the required bitwidth. If the enum has negative values, we need
8838 // one more bit than the normal number of positive bits to represent the
8839 // sign bit.
8840 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
8841 ED->getNumNegativeBits())
8842 : ED->getNumPositiveBits();
8843
8844 // Check the bitwidth.
8845 if (BitsNeeded > FieldWidth) {
8846 Expr *WidthExpr = Bitfield->getBitWidth();
8847 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
8848 << Bitfield << ED;
8849 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
8850 << BitsNeeded << ED << WidthExpr->getSourceRange();
8851 }
8852 }
8853
John McCall1f425642010-11-11 03:21:53 +00008854 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00008855 }
John McCall1f425642010-11-11 03:21:53 +00008856
John McCall1f425642010-11-11 03:21:53 +00008857 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00008858
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008859 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00008860 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008861 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8862 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00008863
John McCall1f425642010-11-11 03:21:53 +00008864 if (OriginalWidth <= FieldWidth)
8865 return false;
8866
Eli Friedmanc267a322012-01-26 23:11:39 +00008867 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00008868 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00008869 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00008870
Eli Friedmanc267a322012-01-26 23:11:39 +00008871 // Check whether the stored value is equal to the original value.
8872 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00008873 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00008874 return false;
8875
Eli Friedmanc267a322012-01-26 23:11:39 +00008876 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00008877 // therefore don't strictly fit into a signed bitfield of width 1.
8878 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00008879 return false;
8880
John McCall1f425642010-11-11 03:21:53 +00008881 std::string PrettyValue = Value.toString(10);
8882 std::string PrettyTrunc = TruncatedValue.toString(10);
8883
8884 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8885 << PrettyValue << PrettyTrunc << OriginalInit->getType()
8886 << Init->getSourceRange();
8887
8888 return true;
8889}
8890
John McCalld2a53122010-11-09 23:24:47 +00008891/// Analyze the given simple or compound assignment for warning-worthy
8892/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008893void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00008894 // Just recurse on the LHS.
8895 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8896
8897 // We want to recurse on the RHS as normal unless we're assigning to
8898 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00008899 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008900 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00008901 E->getOperatorLoc())) {
8902 // Recurse, ignoring any implicit conversions on the RHS.
8903 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8904 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00008905 }
8906 }
8907
8908 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8909}
8910
John McCall263a48b2010-01-04 23:31:57 +00008911/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008912void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8913 SourceLocation CContext, unsigned diag,
8914 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008915 if (pruneControlFlow) {
8916 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8917 S.PDiag(diag)
8918 << SourceType << T << E->getSourceRange()
8919 << SourceRange(CContext));
8920 return;
8921 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00008922 S.Diag(E->getExprLoc(), diag)
8923 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8924}
8925
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008926/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008927void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8928 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008929 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008930}
8931
Richard Trieube234c32016-04-21 21:04:55 +00008932
8933/// Diagnose an implicit cast from a floating point value to an integer value.
8934void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8935
8936 SourceLocation CContext) {
8937 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00008938 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00008939
8940 Expr *InnerE = E->IgnoreParenImpCasts();
8941 // We also want to warn on, e.g., "int i = -1.234"
8942 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8943 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8944 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8945
8946 const bool IsLiteral =
8947 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8948
8949 llvm::APFloat Value(0.0);
8950 bool IsConstant =
8951 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8952 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00008953 return DiagnoseImpCast(S, E, T, CContext,
8954 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00008955 }
8956
Chandler Carruth016ef402011-04-10 08:36:24 +00008957 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00008958
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00008959 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8960 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00008961 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8962 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00008963 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00008964 if (IsLiteral) return;
8965 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8966 PruneWarnings);
8967 }
8968
8969 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00008970 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00008971 // Warn on floating point literal to integer.
8972 DiagID = diag::warn_impcast_literal_float_to_integer;
8973 } else if (IntegerValue == 0) {
8974 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
8975 return DiagnoseImpCast(S, E, T, CContext,
8976 diag::warn_impcast_float_integer, PruneWarnings);
8977 }
8978 // Warn on non-zero to zero conversion.
8979 DiagID = diag::warn_impcast_float_to_integer_zero;
8980 } else {
8981 if (IntegerValue.isUnsigned()) {
8982 if (!IntegerValue.isMaxValue()) {
8983 return DiagnoseImpCast(S, E, T, CContext,
8984 diag::warn_impcast_float_integer, PruneWarnings);
8985 }
8986 } else { // IntegerValue.isSigned()
8987 if (!IntegerValue.isMaxSignedValue() &&
8988 !IntegerValue.isMinSignedValue()) {
8989 return DiagnoseImpCast(S, E, T, CContext,
8990 diag::warn_impcast_float_integer, PruneWarnings);
8991 }
8992 }
8993 // Warn on evaluatable floating point expression to integer conversion.
8994 DiagID = diag::warn_impcast_float_to_integer;
8995 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008996
Eli Friedman07185912013-08-29 23:44:43 +00008997 // FIXME: Force the precision of the source value down so we don't print
8998 // digits which are usually useless (we don't really care here if we
8999 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9000 // would automatically print the shortest representation, but it's a bit
9001 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00009002 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00009003 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9004 precision = (precision * 59 + 195) / 196;
9005 Value.toString(PrettySourceValue, precision);
9006
David Blaikie9b88cc02012-05-15 17:18:27 +00009007 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00009008 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00009009 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00009010 else
David Blaikie9b88cc02012-05-15 17:18:27 +00009011 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00009012
Richard Trieube234c32016-04-21 21:04:55 +00009013 if (PruneWarnings) {
9014 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9015 S.PDiag(DiagID)
9016 << E->getType() << T.getUnqualifiedType()
9017 << PrettySourceValue << PrettyTargetValue
9018 << E->getSourceRange() << SourceRange(CContext));
9019 } else {
9020 S.Diag(E->getExprLoc(), DiagID)
9021 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9022 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9023 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009024}
9025
John McCall18a2c2c2010-11-09 22:22:12 +00009026std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
9027 if (!Range.Width) return "0";
9028
9029 llvm::APSInt ValueInRange = Value;
9030 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00009031 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00009032 return ValueInRange.toString(10);
9033}
9034
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009035bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009036 if (!isa<ImplicitCastExpr>(Ex))
9037 return false;
9038
9039 Expr *InnerE = Ex->IgnoreParenImpCasts();
9040 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9041 const Type *Source =
9042 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9043 if (Target->isDependentType())
9044 return false;
9045
9046 const BuiltinType *FloatCandidateBT =
9047 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9048 const Type *BoolCandidateType = ToBool ? Target : Source;
9049
9050 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9051 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9052}
9053
9054void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9055 SourceLocation CC) {
9056 unsigned NumArgs = TheCall->getNumArgs();
9057 for (unsigned i = 0; i < NumArgs; ++i) {
9058 Expr *CurrA = TheCall->getArg(i);
9059 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9060 continue;
9061
9062 bool IsSwapped = ((i > 0) &&
9063 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9064 IsSwapped |= ((i < (NumArgs - 1)) &&
9065 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9066 if (IsSwapped) {
9067 // Warn on this floating-point to bool conversion.
9068 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9069 CurrA->getType(), CC,
9070 diag::warn_impcast_floating_point_to_bool);
9071 }
9072 }
9073}
9074
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009075void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009076 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9077 E->getExprLoc()))
9078 return;
9079
Richard Trieu09d6b802016-01-08 23:35:06 +00009080 // Don't warn on functions which have return type nullptr_t.
9081 if (isa<CallExpr>(E))
9082 return;
9083
Richard Trieu5b993502014-10-15 03:42:06 +00009084 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9085 const Expr::NullPointerConstantKind NullKind =
9086 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9087 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9088 return;
9089
9090 // Return if target type is a safe conversion.
9091 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9092 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9093 return;
9094
9095 SourceLocation Loc = E->getSourceRange().getBegin();
9096
Richard Trieu0a5e1662016-02-13 00:58:53 +00009097 // Venture through the macro stacks to get to the source of macro arguments.
9098 // The new location is a better location than the complete location that was
9099 // passed in.
9100 while (S.SourceMgr.isMacroArgExpansion(Loc))
9101 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
9102
9103 while (S.SourceMgr.isMacroArgExpansion(CC))
9104 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
9105
Richard Trieu5b993502014-10-15 03:42:06 +00009106 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00009107 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9108 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9109 Loc, S.SourceMgr, S.getLangOpts());
9110 if (MacroName == "NULL")
9111 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00009112 }
9113
9114 // Only warn if the null and context location are in the same macro expansion.
9115 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9116 return;
9117
9118 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9119 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
9120 << FixItHint::CreateReplacement(Loc,
9121 S.getFixItZeroLiteralForType(T, Loc));
9122}
9123
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009124void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9125 ObjCArrayLiteral *ArrayLiteral);
9126void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9127 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00009128
9129/// Check a single element within a collection literal against the
9130/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009131void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
9132 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009133 // Skip a bitcast to 'id' or qualified 'id'.
9134 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9135 if (ICE->getCastKind() == CK_BitCast &&
9136 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9137 Element = ICE->getSubExpr();
9138 }
9139
9140 QualType ElementType = Element->getType();
9141 ExprResult ElementResult(Element);
9142 if (ElementType->getAs<ObjCObjectPointerType>() &&
9143 S.CheckSingleAssignmentConstraints(TargetElementType,
9144 ElementResult,
9145 false, false)
9146 != Sema::Compatible) {
9147 S.Diag(Element->getLocStart(),
9148 diag::warn_objc_collection_literal_element)
9149 << ElementType << ElementKind << TargetElementType
9150 << Element->getSourceRange();
9151 }
9152
9153 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9154 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9155 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9156 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9157}
9158
9159/// Check an Objective-C array literal being converted to the given
9160/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009161void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9162 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009163 if (!S.NSArrayDecl)
9164 return;
9165
9166 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9167 if (!TargetObjCPtr)
9168 return;
9169
9170 if (TargetObjCPtr->isUnspecialized() ||
9171 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9172 != S.NSArrayDecl->getCanonicalDecl())
9173 return;
9174
9175 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9176 if (TypeArgs.size() != 1)
9177 return;
9178
9179 QualType TargetElementType = TypeArgs[0];
9180 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9181 checkObjCCollectionLiteralElement(S, TargetElementType,
9182 ArrayLiteral->getElement(I),
9183 0);
9184 }
9185}
9186
9187/// Check an Objective-C dictionary literal being converted to the given
9188/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009189void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9190 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009191 if (!S.NSDictionaryDecl)
9192 return;
9193
9194 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9195 if (!TargetObjCPtr)
9196 return;
9197
9198 if (TargetObjCPtr->isUnspecialized() ||
9199 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9200 != S.NSDictionaryDecl->getCanonicalDecl())
9201 return;
9202
9203 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9204 if (TypeArgs.size() != 2)
9205 return;
9206
9207 QualType TargetKeyType = TypeArgs[0];
9208 QualType TargetObjectType = TypeArgs[1];
9209 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9210 auto Element = DictionaryLiteral->getKeyValueElement(I);
9211 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9212 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9213 }
9214}
9215
Richard Trieufc404c72016-02-05 23:02:38 +00009216// Helper function to filter out cases for constant width constant conversion.
9217// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009218bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9219 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00009220 // If initializing from a constant, and the constant starts with '0',
9221 // then it is a binary, octal, or hexadecimal. Allow these constants
9222 // to fill all the bits, even if there is a sign change.
9223 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9224 const char FirstLiteralCharacter =
9225 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9226 if (FirstLiteralCharacter == '0')
9227 return false;
9228 }
9229
9230 // If the CC location points to a '{', and the type is char, then assume
9231 // assume it is an array initialization.
9232 if (CC.isValid() && T->isCharType()) {
9233 const char FirstContextCharacter =
9234 S.getSourceManager().getCharacterData(CC)[0];
9235 if (FirstContextCharacter == '{')
9236 return false;
9237 }
9238
9239 return true;
9240}
9241
John McCallcc7e5bf2010-05-06 08:58:33 +00009242void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00009243 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009244 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00009245
John McCallcc7e5bf2010-05-06 08:58:33 +00009246 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9247 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9248 if (Source == Target) return;
9249 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00009250
Chandler Carruthc22845a2011-07-26 05:40:03 +00009251 // If the conversion context location is invalid don't complain. We also
9252 // don't want to emit a warning if the issue occurs from the expansion of
9253 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9254 // delay this check as long as possible. Once we detect we are in that
9255 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009256 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00009257 return;
9258
Richard Trieu021baa32011-09-23 20:10:00 +00009259 // Diagnose implicit casts to bool.
9260 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9261 if (isa<StringLiteral>(E))
9262 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00009263 // and expressions, for instance, assert(0 && "error here"), are
9264 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00009265 return DiagnoseImpCast(S, E, T, CC,
9266 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00009267 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9268 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9269 // This covers the literal expressions that evaluate to Objective-C
9270 // objects.
9271 return DiagnoseImpCast(S, E, T, CC,
9272 diag::warn_impcast_objective_c_literal_to_bool);
9273 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009274 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9275 // Warn on pointer to bool conversion that is always true.
9276 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9277 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00009278 }
Richard Trieu021baa32011-09-23 20:10:00 +00009279 }
John McCall263a48b2010-01-04 23:31:57 +00009280
Douglas Gregor5054cb02015-07-07 03:58:22 +00009281 // Check implicit casts from Objective-C collection literals to specialized
9282 // collection types, e.g., NSArray<NSString *> *.
9283 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9284 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9285 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9286 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9287
John McCall263a48b2010-01-04 23:31:57 +00009288 // Strip vector types.
9289 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009290 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009291 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009292 return;
John McCallacf0ee52010-10-08 02:01:28 +00009293 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009294 }
Chris Lattneree7286f2011-06-14 04:51:15 +00009295
9296 // If the vector cast is cast between two vectors of the same size, it is
9297 // a bitcast, not a conversion.
9298 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9299 return;
John McCall263a48b2010-01-04 23:31:57 +00009300
9301 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9302 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9303 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00009304 if (auto VecTy = dyn_cast<VectorType>(Target))
9305 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00009306
9307 // Strip complex types.
9308 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009309 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009310 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009311 return;
9312
John McCallacf0ee52010-10-08 02:01:28 +00009313 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009314 }
John McCall263a48b2010-01-04 23:31:57 +00009315
9316 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9317 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9318 }
9319
9320 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9321 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9322
9323 // If the source is floating point...
9324 if (SourceBT && SourceBT->isFloatingPoint()) {
9325 // ...and the target is floating point...
9326 if (TargetBT && TargetBT->isFloatingPoint()) {
9327 // ...then warn if we're dropping FP rank.
9328
9329 // Builtin FP kinds are ordered by increasing FP rank.
9330 if (SourceBT->getKind() > TargetBT->getKind()) {
9331 // Don't warn about float constants that are precisely
9332 // representable in the target type.
9333 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009334 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00009335 // Value might be a float, a float vector, or a float complex.
9336 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00009337 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9338 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00009339 return;
9340 }
9341
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009342 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009343 return;
9344
John McCallacf0ee52010-10-08 02:01:28 +00009345 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00009346 }
9347 // ... or possibly if we're increasing rank, too
9348 else if (TargetBT->getKind() > SourceBT->getKind()) {
9349 if (S.SourceMgr.isInSystemMacro(CC))
9350 return;
9351
9352 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00009353 }
9354 return;
9355 }
9356
Richard Trieube234c32016-04-21 21:04:55 +00009357 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00009358 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009359 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009360 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00009361
Richard Trieube234c32016-04-21 21:04:55 +00009362 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00009363 }
John McCall263a48b2010-01-04 23:31:57 +00009364
Richard Smith54894fd2015-12-30 01:06:52 +00009365 // Detect the case where a call result is converted from floating-point to
9366 // to bool, and the final argument to the call is converted from bool, to
9367 // discover this typo:
9368 //
9369 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9370 //
9371 // FIXME: This is an incredibly special case; is there some more general
9372 // way to detect this class of misplaced-parentheses bug?
9373 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009374 // Check last argument of function call to see if it is an
9375 // implicit cast from a type matching the type the result
9376 // is being cast to.
9377 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00009378 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009379 Expr *LastA = CEx->getArg(NumArgs - 1);
9380 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00009381 if (isa<ImplicitCastExpr>(LastA) &&
9382 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009383 // Warn on this floating-point to bool conversion
9384 DiagnoseImpCast(S, E, T, CC,
9385 diag::warn_impcast_floating_point_to_bool);
9386 }
9387 }
9388 }
John McCall263a48b2010-01-04 23:31:57 +00009389 return;
9390 }
9391
Richard Trieu5b993502014-10-15 03:42:06 +00009392 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00009393
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009394 S.DiscardMisalignedMemberAddress(Target, E);
9395
David Blaikie9366d2b2012-06-19 21:19:06 +00009396 if (!Source->isIntegerType() || !Target->isIntegerType())
9397 return;
9398
David Blaikie7555b6a2012-05-15 16:56:36 +00009399 // TODO: remove this early return once the false positives for constant->bool
9400 // in templates, macros, etc, are reduced or removed.
9401 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9402 return;
9403
John McCallcc7e5bf2010-05-06 08:58:33 +00009404 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00009405 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00009406
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009407 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00009408 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009409 // TODO: this should happen for bitfield stores, too.
9410 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00009411 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009412 if (S.SourceMgr.isInSystemMacro(CC))
9413 return;
9414
John McCall18a2c2c2010-11-09 22:22:12 +00009415 std::string PrettySourceValue = Value.toString(10);
9416 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009417
Ted Kremenek33ba9952011-10-22 02:37:33 +00009418 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9419 S.PDiag(diag::warn_impcast_integer_precision_constant)
9420 << PrettySourceValue << PrettyTargetValue
9421 << E->getType() << T << E->getSourceRange()
9422 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00009423 return;
9424 }
9425
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009426 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9427 if (S.SourceMgr.isInSystemMacro(CC))
9428 return;
9429
David Blaikie9455da02012-04-12 22:40:54 +00009430 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00009431 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9432 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00009433 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00009434 }
9435
Richard Trieudcb55572016-01-29 23:51:16 +00009436 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9437 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9438 // Warn when doing a signed to signed conversion, warn if the positive
9439 // source value is exactly the width of the target type, which will
9440 // cause a negative value to be stored.
9441
9442 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00009443 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9444 !S.SourceMgr.isInSystemMacro(CC)) {
9445 if (isSameWidthConstantConversion(S, E, T, CC)) {
9446 std::string PrettySourceValue = Value.toString(10);
9447 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00009448
Richard Trieufc404c72016-02-05 23:02:38 +00009449 S.DiagRuntimeBehavior(
9450 E->getExprLoc(), E,
9451 S.PDiag(diag::warn_impcast_integer_precision_constant)
9452 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9453 << E->getSourceRange() << clang::SourceRange(CC));
9454 return;
Richard Trieudcb55572016-01-29 23:51:16 +00009455 }
9456 }
Richard Trieufc404c72016-02-05 23:02:38 +00009457
Richard Trieudcb55572016-01-29 23:51:16 +00009458 // Fall through for non-constants to give a sign conversion warning.
9459 }
9460
John McCallcc7e5bf2010-05-06 08:58:33 +00009461 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9462 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9463 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009464 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009465 return;
9466
John McCallcc7e5bf2010-05-06 08:58:33 +00009467 unsigned DiagID = diag::warn_impcast_integer_sign;
9468
9469 // Traditionally, gcc has warned about this under -Wsign-compare.
9470 // We also want to warn about it in -Wconversion.
9471 // So if -Wconversion is off, use a completely identical diagnostic
9472 // in the sign-compare group.
9473 // The conditional-checking code will
9474 if (ICContext) {
9475 DiagID = diag::warn_impcast_integer_sign_conditional;
9476 *ICContext = true;
9477 }
9478
John McCallacf0ee52010-10-08 02:01:28 +00009479 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00009480 }
9481
Douglas Gregora78f1932011-02-22 02:45:07 +00009482 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00009483 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9484 // type, to give us better diagnostics.
9485 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009486 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00009487 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9488 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9489 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9490 SourceType = S.Context.getTypeDeclType(Enum);
9491 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9492 }
9493 }
9494
Douglas Gregora78f1932011-02-22 02:45:07 +00009495 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9496 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00009497 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9498 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009499 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009500 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009501 return;
9502
Douglas Gregor364f7db2011-03-12 00:14:31 +00009503 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00009504 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009505 }
John McCall263a48b2010-01-04 23:31:57 +00009506}
9507
David Blaikie18e9ac72012-05-15 21:57:38 +00009508void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9509 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009510
9511void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00009512 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009513 E = E->IgnoreParenImpCasts();
9514
9515 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00009516 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009517
John McCallacf0ee52010-10-08 02:01:28 +00009518 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009519 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009520 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00009521}
9522
David Blaikie18e9ac72012-05-15 21:57:38 +00009523void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9524 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00009525 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009526
9527 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00009528 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9529 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009530
9531 // If -Wconversion would have warned about either of the candidates
9532 // for a signedness conversion to the context type...
9533 if (!Suspicious) return;
9534
9535 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009536 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00009537 return;
9538
John McCallcc7e5bf2010-05-06 08:58:33 +00009539 // ...then check whether it would have warned about either of the
9540 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00009541 if (E->getType() == T) return;
9542
9543 Suspicious = false;
9544 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9545 E->getType(), CC, &Suspicious);
9546 if (!Suspicious)
9547 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00009548 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009549}
9550
Richard Trieu65724892014-11-15 06:37:39 +00009551/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9552/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009553void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00009554 if (S.getLangOpts().Bool)
9555 return;
9556 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9557}
9558
John McCallcc7e5bf2010-05-06 08:58:33 +00009559/// AnalyzeImplicitConversions - Find and report any interesting
9560/// implicit conversions in the given expression. There are a couple
9561/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009562void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00009563 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00009564 Expr *E = OrigE->IgnoreParenImpCasts();
9565
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00009566 if (E->isTypeDependent() || E->isValueDependent())
9567 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00009568
John McCallcc7e5bf2010-05-06 08:58:33 +00009569 // For conditional operators, we analyze the arguments as if they
9570 // were being fed directly into the output.
9571 if (isa<ConditionalOperator>(E)) {
9572 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00009573 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009574 return;
9575 }
9576
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009577 // Check implicit argument conversions for function calls.
9578 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9579 CheckImplicitArgumentConversions(S, Call, CC);
9580
John McCallcc7e5bf2010-05-06 08:58:33 +00009581 // Go ahead and check any implicit conversions we might have skipped.
9582 // The non-canonical typecheck is just an optimization;
9583 // CheckImplicitConversion will filter out dead implicit conversions.
9584 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009585 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009586
9587 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00009588
9589 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9590 // The bound subexpressions in a PseudoObjectExpr are not reachable
9591 // as transitive children.
9592 // FIXME: Use a more uniform representation for this.
9593 for (auto *SE : POE->semantics())
9594 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9595 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00009596 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00009597
John McCallcc7e5bf2010-05-06 08:58:33 +00009598 // Skip past explicit casts.
9599 if (isa<ExplicitCastExpr>(E)) {
9600 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00009601 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009602 }
9603
John McCalld2a53122010-11-09 23:24:47 +00009604 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9605 // Do a somewhat different check with comparison operators.
9606 if (BO->isComparisonOp())
9607 return AnalyzeComparison(S, BO);
9608
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009609 // And with simple assignments.
9610 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00009611 return AnalyzeAssignment(S, BO);
9612 }
John McCallcc7e5bf2010-05-06 08:58:33 +00009613
9614 // These break the otherwise-useful invariant below. Fortunately,
9615 // we don't really need to recurse into them, because any internal
9616 // expressions should have been analyzed already when they were
9617 // built into statements.
9618 if (isa<StmtExpr>(E)) return;
9619
9620 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00009621 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00009622
9623 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00009624 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00009625 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00009626 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00009627 for (Stmt *SubStmt : E->children()) {
9628 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00009629 if (!ChildExpr)
9630 continue;
9631
Richard Trieu955231d2014-01-25 01:10:35 +00009632 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00009633 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00009634 // Ignore checking string literals that are in logical and operators.
9635 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00009636 continue;
9637 AnalyzeImplicitConversions(S, ChildExpr, CC);
9638 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009639
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009640 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00009641 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9642 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009643 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00009644
9645 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9646 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009647 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009648 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009649
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009650 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9651 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00009652 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009653}
9654
9655} // end anonymous namespace
9656
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009657/// Diagnose integer type and any valid implicit convertion to it.
9658static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9659 // Taking into account implicit conversions,
9660 // allow any integer.
9661 if (!E->getType()->isIntegerType()) {
9662 S.Diag(E->getLocStart(),
9663 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9664 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009665 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009666 // Potentially emit standard warnings for implicit conversions if enabled
9667 // using -Wconversion.
9668 CheckImplicitConversion(S, E, IntT, E->getLocStart());
9669 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009670}
9671
Richard Trieuc1888e02014-06-28 23:25:37 +00009672// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9673// Returns true when emitting a warning about taking the address of a reference.
9674static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00009675 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00009676 E = E->IgnoreParenImpCasts();
9677
9678 const FunctionDecl *FD = nullptr;
9679
9680 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9681 if (!DRE->getDecl()->getType()->isReferenceType())
9682 return false;
9683 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9684 if (!M->getMemberDecl()->getType()->isReferenceType())
9685 return false;
9686 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00009687 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00009688 return false;
9689 FD = Call->getDirectCallee();
9690 } else {
9691 return false;
9692 }
9693
9694 SemaRef.Diag(E->getExprLoc(), PD);
9695
9696 // If possible, point to location of function.
9697 if (FD) {
9698 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9699 }
9700
9701 return true;
9702}
9703
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009704// Returns true if the SourceLocation is expanded from any macro body.
9705// Returns false if the SourceLocation is invalid, is from not in a macro
9706// expansion, or is from expanded from a top-level macro argument.
9707static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9708 if (Loc.isInvalid())
9709 return false;
9710
9711 while (Loc.isMacroID()) {
9712 if (SM.isMacroBodyExpansion(Loc))
9713 return true;
9714 Loc = SM.getImmediateMacroCallerLoc(Loc);
9715 }
9716
9717 return false;
9718}
9719
Richard Trieu3bb8b562014-02-26 02:36:06 +00009720/// \brief Diagnose pointers that are always non-null.
9721/// \param E the expression containing the pointer
9722/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9723/// compared to a null pointer
9724/// \param IsEqual True when the comparison is equal to a null pointer
9725/// \param Range Extra SourceRange to highlight in the diagnostic
9726void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9727 Expr::NullPointerConstantKind NullKind,
9728 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00009729 if (!E)
9730 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009731
9732 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009733 if (E->getExprLoc().isMacroID()) {
9734 const SourceManager &SM = getSourceManager();
9735 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9736 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00009737 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009738 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009739 E = E->IgnoreImpCasts();
9740
9741 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9742
Richard Trieuf7432752014-06-06 21:39:26 +00009743 if (isa<CXXThisExpr>(E)) {
9744 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9745 : diag::warn_this_bool_conversion;
9746 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9747 return;
9748 }
9749
Richard Trieu3bb8b562014-02-26 02:36:06 +00009750 bool IsAddressOf = false;
9751
9752 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9753 if (UO->getOpcode() != UO_AddrOf)
9754 return;
9755 IsAddressOf = true;
9756 E = UO->getSubExpr();
9757 }
9758
Richard Trieuc1888e02014-06-28 23:25:37 +00009759 if (IsAddressOf) {
9760 unsigned DiagID = IsCompare
9761 ? diag::warn_address_of_reference_null_compare
9762 : diag::warn_address_of_reference_bool_conversion;
9763 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9764 << IsEqual;
9765 if (CheckForReference(*this, E, PD)) {
9766 return;
9767 }
9768 }
9769
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009770 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9771 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00009772 std::string Str;
9773 llvm::raw_string_ostream S(Str);
9774 E->printPretty(S, nullptr, getPrintingPolicy());
9775 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9776 : diag::warn_cast_nonnull_to_bool;
9777 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9778 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009779 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00009780 };
9781
9782 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9783 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9784 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009785 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9786 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009787 return;
9788 }
9789 }
9790 }
9791
Richard Trieu3bb8b562014-02-26 02:36:06 +00009792 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00009793 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009794 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9795 D = R->getDecl();
9796 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9797 D = M->getMemberDecl();
9798 }
9799
9800 // Weak Decls can be null.
9801 if (!D || D->isWeak())
9802 return;
George Burgess IV850269a2015-12-08 22:02:00 +00009803
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009804 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00009805 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9806 if (getCurFunction() &&
9807 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009808 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9809 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009810 return;
9811 }
9812
9813 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +00009814 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +00009815 assert(ParamIter != FD->param_end());
9816 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9817
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009818 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9819 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009820 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +00009821 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009822 }
George Burgess IV850269a2015-12-08 22:02:00 +00009823
9824 for (unsigned ArgNo : NonNull->args()) {
9825 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009826 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009827 return;
9828 }
George Burgess IV850269a2015-12-08 22:02:00 +00009829 }
9830 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009831 }
9832 }
George Burgess IV850269a2015-12-08 22:02:00 +00009833 }
9834
Richard Trieu3bb8b562014-02-26 02:36:06 +00009835 QualType T = D->getType();
9836 const bool IsArray = T->isArrayType();
9837 const bool IsFunction = T->isFunctionType();
9838
Richard Trieuc1888e02014-06-28 23:25:37 +00009839 // Address of function is used to silence the function warning.
9840 if (IsAddressOf && IsFunction) {
9841 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009842 }
9843
9844 // Found nothing.
9845 if (!IsAddressOf && !IsFunction && !IsArray)
9846 return;
9847
9848 // Pretty print the expression for the diagnostic.
9849 std::string Str;
9850 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00009851 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00009852
9853 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9854 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00009855 enum {
9856 AddressOf,
9857 FunctionPointer,
9858 ArrayPointer
9859 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009860 if (IsAddressOf)
9861 DiagType = AddressOf;
9862 else if (IsFunction)
9863 DiagType = FunctionPointer;
9864 else if (IsArray)
9865 DiagType = ArrayPointer;
9866 else
9867 llvm_unreachable("Could not determine diagnostic.");
9868 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9869 << Range << IsEqual;
9870
9871 if (!IsFunction)
9872 return;
9873
9874 // Suggest '&' to silence the function warning.
9875 Diag(E->getExprLoc(), diag::note_function_warning_silence)
9876 << FixItHint::CreateInsertion(E->getLocStart(), "&");
9877
9878 // Check to see if '()' fixit should be emitted.
9879 QualType ReturnType;
9880 UnresolvedSet<4> NonTemplateOverloads;
9881 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9882 if (ReturnType.isNull())
9883 return;
9884
9885 if (IsCompare) {
9886 // There are two cases here. If there is null constant, the only suggest
9887 // for a pointer return type. If the null is 0, then suggest if the return
9888 // type is a pointer or an integer type.
9889 if (!ReturnType->isPointerType()) {
9890 if (NullKind == Expr::NPCK_ZeroExpression ||
9891 NullKind == Expr::NPCK_ZeroLiteral) {
9892 if (!ReturnType->isIntegerType())
9893 return;
9894 } else {
9895 return;
9896 }
9897 }
9898 } else { // !IsCompare
9899 // For function to bool, only suggest if the function pointer has bool
9900 // return type.
9901 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9902 return;
9903 }
9904 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00009905 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00009906}
9907
John McCallcc7e5bf2010-05-06 08:58:33 +00009908/// Diagnoses "dangerous" implicit conversions within the given
9909/// expression (which is a full expression). Implements -Wconversion
9910/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009911///
9912/// \param CC the "context" location of the implicit conversion, i.e.
9913/// the most location of the syntactic entity requiring the implicit
9914/// conversion
9915void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009916 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00009917 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00009918 return;
9919
9920 // Don't diagnose for value- or type-dependent expressions.
9921 if (E->isTypeDependent() || E->isValueDependent())
9922 return;
9923
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009924 // Check for array bounds violations in cases where the check isn't triggered
9925 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9926 // ArraySubscriptExpr is on the RHS of a variable initialization.
9927 CheckArrayAccess(E);
9928
John McCallacf0ee52010-10-08 02:01:28 +00009929 // This is not the right CC for (e.g.) a variable initialization.
9930 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009931}
9932
Richard Trieu65724892014-11-15 06:37:39 +00009933/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9934/// Input argument E is a logical expression.
9935void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9936 ::CheckBoolLikeConversion(*this, E, CC);
9937}
9938
Richard Smith9f7df0c2017-06-26 23:19:32 +00009939/// Diagnose when expression is an integer constant expression and its evaluation
9940/// results in integer overflow
9941void Sema::CheckForIntOverflow (Expr *E) {
9942 // Use a work list to deal with nested struct initializers.
9943 SmallVector<Expr *, 2> Exprs(1, E);
9944
9945 do {
9946 Expr *E = Exprs.pop_back_val();
9947
9948 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9949 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9950 continue;
9951 }
9952
9953 if (auto InitList = dyn_cast<InitListExpr>(E))
9954 Exprs.append(InitList->inits().begin(), InitList->inits().end());
9955
9956 if (isa<ObjCBoxedExpr>(E))
9957 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9958 } while (!Exprs.empty());
9959}
9960
Richard Smithc406cb72013-01-17 01:17:56 +00009961namespace {
9962/// \brief Visitor for expressions which looks for unsequenced operations on the
9963/// same object.
9964class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009965 typedef EvaluatedExprVisitor<SequenceChecker> Base;
9966
Richard Smithc406cb72013-01-17 01:17:56 +00009967 /// \brief A tree of sequenced regions within an expression. Two regions are
9968 /// unsequenced if one is an ancestor or a descendent of the other. When we
9969 /// finish processing an expression with sequencing, such as a comma
9970 /// expression, we fold its tree nodes into its parent, since they are
9971 /// unsequenced with respect to nodes we will visit later.
9972 class SequenceTree {
9973 struct Value {
9974 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9975 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +00009976 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +00009977 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009978 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00009979
9980 public:
9981 /// \brief A region within an expression which may be sequenced with respect
9982 /// to some other region.
9983 class Seq {
9984 explicit Seq(unsigned N) : Index(N) {}
9985 unsigned Index;
9986 friend class SequenceTree;
9987 public:
9988 Seq() : Index(0) {}
9989 };
9990
9991 SequenceTree() { Values.push_back(Value(0)); }
9992 Seq root() const { return Seq(0); }
9993
9994 /// \brief Create a new sequence of operations, which is an unsequenced
9995 /// subset of \p Parent. This sequence of operations is sequenced with
9996 /// respect to other children of \p Parent.
9997 Seq allocate(Seq Parent) {
9998 Values.push_back(Value(Parent.Index));
9999 return Seq(Values.size() - 1);
10000 }
10001
10002 /// \brief Merge a sequence of operations into its parent.
10003 void merge(Seq S) {
10004 Values[S.Index].Merged = true;
10005 }
10006
10007 /// \brief Determine whether two operations are unsequenced. This operation
10008 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10009 /// should have been merged into its parent as appropriate.
10010 bool isUnsequenced(Seq Cur, Seq Old) {
10011 unsigned C = representative(Cur.Index);
10012 unsigned Target = representative(Old.Index);
10013 while (C >= Target) {
10014 if (C == Target)
10015 return true;
10016 C = Values[C].Parent;
10017 }
10018 return false;
10019 }
10020
10021 private:
10022 /// \brief Pick a representative for a sequence.
10023 unsigned representative(unsigned K) {
10024 if (Values[K].Merged)
10025 // Perform path compression as we go.
10026 return Values[K].Parent = representative(Values[K].Parent);
10027 return K;
10028 }
10029 };
10030
10031 /// An object for which we can track unsequenced uses.
10032 typedef NamedDecl *Object;
10033
10034 /// Different flavors of object usage which we track. We only track the
10035 /// least-sequenced usage of each kind.
10036 enum UsageKind {
10037 /// A read of an object. Multiple unsequenced reads are OK.
10038 UK_Use,
10039 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000010040 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000010041 UK_ModAsValue,
10042 /// A modification of an object which is not sequenced before the value
10043 /// computation of the expression, such as n++.
10044 UK_ModAsSideEffect,
10045
10046 UK_Count = UK_ModAsSideEffect + 1
10047 };
10048
10049 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +000010050 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +000010051 Expr *Use;
10052 SequenceTree::Seq Seq;
10053 };
10054
10055 struct UsageInfo {
10056 UsageInfo() : Diagnosed(false) {}
10057 Usage Uses[UK_Count];
10058 /// Have we issued a diagnostic for this variable already?
10059 bool Diagnosed;
10060 };
10061 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
10062
10063 Sema &SemaRef;
10064 /// Sequenced regions within the expression.
10065 SequenceTree Tree;
10066 /// Declaration modifications and references which we have seen.
10067 UsageInfoMap UsageMap;
10068 /// The region we are currently within.
10069 SequenceTree::Seq Region;
10070 /// Filled in with declarations which were modified as a side-effect
10071 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010072 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +000010073 /// Expressions to check later. We defer checking these to reduce
10074 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010075 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000010076
10077 /// RAII object wrapping the visitation of a sequenced subexpression of an
10078 /// expression. At the end of this process, the side-effects of the evaluation
10079 /// become sequenced with respect to the value computation of the result, so
10080 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10081 /// UK_ModAsValue.
10082 struct SequencedSubexpression {
10083 SequencedSubexpression(SequenceChecker &Self)
10084 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10085 Self.ModAsSideEffect = &ModAsSideEffect;
10086 }
10087 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000010088 for (auto &M : llvm::reverse(ModAsSideEffect)) {
10089 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000010090 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000010091 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10092 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000010093 }
10094 Self.ModAsSideEffect = OldModAsSideEffect;
10095 }
10096
10097 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010098 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
10099 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000010100 };
10101
Richard Smith40238f02013-06-20 22:21:56 +000010102 /// RAII object wrapping the visitation of a subexpression which we might
10103 /// choose to evaluate as a constant. If any subexpression is evaluated and
10104 /// found to be non-constant, this allows us to suppress the evaluation of
10105 /// the outer expression.
10106 class EvaluationTracker {
10107 public:
10108 EvaluationTracker(SequenceChecker &Self)
10109 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
10110 Self.EvalTracker = this;
10111 }
10112 ~EvaluationTracker() {
10113 Self.EvalTracker = Prev;
10114 if (Prev)
10115 Prev->EvalOK &= EvalOK;
10116 }
10117
10118 bool evaluate(const Expr *E, bool &Result) {
10119 if (!EvalOK || E->isValueDependent())
10120 return false;
10121 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10122 return EvalOK;
10123 }
10124
10125 private:
10126 SequenceChecker &Self;
10127 EvaluationTracker *Prev;
10128 bool EvalOK;
10129 } *EvalTracker;
10130
Richard Smithc406cb72013-01-17 01:17:56 +000010131 /// \brief Find the object which is produced by the specified expression,
10132 /// if any.
10133 Object getObject(Expr *E, bool Mod) const {
10134 E = E->IgnoreParenCasts();
10135 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10136 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10137 return getObject(UO->getSubExpr(), Mod);
10138 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10139 if (BO->getOpcode() == BO_Comma)
10140 return getObject(BO->getRHS(), Mod);
10141 if (Mod && BO->isAssignmentOp())
10142 return getObject(BO->getLHS(), Mod);
10143 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10144 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10145 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10146 return ME->getMemberDecl();
10147 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10148 // FIXME: If this is a reference, map through to its value.
10149 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000010150 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010151 }
10152
10153 /// \brief Note that an object was modified or used by an expression.
10154 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10155 Usage &U = UI.Uses[UK];
10156 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10157 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10158 ModAsSideEffect->push_back(std::make_pair(O, U));
10159 U.Use = Ref;
10160 U.Seq = Region;
10161 }
10162 }
10163 /// \brief Check whether a modification or use conflicts with a prior usage.
10164 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10165 bool IsModMod) {
10166 if (UI.Diagnosed)
10167 return;
10168
10169 const Usage &U = UI.Uses[OtherKind];
10170 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10171 return;
10172
10173 Expr *Mod = U.Use;
10174 Expr *ModOrUse = Ref;
10175 if (OtherKind == UK_Use)
10176 std::swap(Mod, ModOrUse);
10177
10178 SemaRef.Diag(Mod->getExprLoc(),
10179 IsModMod ? diag::warn_unsequenced_mod_mod
10180 : diag::warn_unsequenced_mod_use)
10181 << O << SourceRange(ModOrUse->getExprLoc());
10182 UI.Diagnosed = true;
10183 }
10184
10185 void notePreUse(Object O, Expr *Use) {
10186 UsageInfo &U = UsageMap[O];
10187 // Uses conflict with other modifications.
10188 checkUsage(O, U, Use, UK_ModAsValue, false);
10189 }
10190 void notePostUse(Object O, Expr *Use) {
10191 UsageInfo &U = UsageMap[O];
10192 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10193 addUsage(U, O, Use, UK_Use);
10194 }
10195
10196 void notePreMod(Object O, Expr *Mod) {
10197 UsageInfo &U = UsageMap[O];
10198 // Modifications conflict with other modifications and with uses.
10199 checkUsage(O, U, Mod, UK_ModAsValue, true);
10200 checkUsage(O, U, Mod, UK_Use, false);
10201 }
10202 void notePostMod(Object O, Expr *Use, UsageKind UK) {
10203 UsageInfo &U = UsageMap[O];
10204 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10205 addUsage(U, O, Use, UK);
10206 }
10207
10208public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010209 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +000010210 : Base(S.Context), SemaRef(S), Region(Tree.root()),
10211 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010212 Visit(E);
10213 }
10214
10215 void VisitStmt(Stmt *S) {
10216 // Skip all statements which aren't expressions for now.
10217 }
10218
10219 void VisitExpr(Expr *E) {
10220 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000010221 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000010222 }
10223
10224 void VisitCastExpr(CastExpr *E) {
10225 Object O = Object();
10226 if (E->getCastKind() == CK_LValueToRValue)
10227 O = getObject(E->getSubExpr(), false);
10228
10229 if (O)
10230 notePreUse(O, E);
10231 VisitExpr(E);
10232 if (O)
10233 notePostUse(O, E);
10234 }
10235
10236 void VisitBinComma(BinaryOperator *BO) {
10237 // C++11 [expr.comma]p1:
10238 // Every value computation and side effect associated with the left
10239 // expression is sequenced before every value computation and side
10240 // effect associated with the right expression.
10241 SequenceTree::Seq LHS = Tree.allocate(Region);
10242 SequenceTree::Seq RHS = Tree.allocate(Region);
10243 SequenceTree::Seq OldRegion = Region;
10244
10245 {
10246 SequencedSubexpression SeqLHS(*this);
10247 Region = LHS;
10248 Visit(BO->getLHS());
10249 }
10250
10251 Region = RHS;
10252 Visit(BO->getRHS());
10253
10254 Region = OldRegion;
10255
10256 // Forget that LHS and RHS are sequenced. They are both unsequenced
10257 // with respect to other stuff.
10258 Tree.merge(LHS);
10259 Tree.merge(RHS);
10260 }
10261
10262 void VisitBinAssign(BinaryOperator *BO) {
10263 // The modification is sequenced after the value computation of the LHS
10264 // and RHS, so check it before inspecting the operands and update the
10265 // map afterwards.
10266 Object O = getObject(BO->getLHS(), true);
10267 if (!O)
10268 return VisitExpr(BO);
10269
10270 notePreMod(O, BO);
10271
10272 // C++11 [expr.ass]p7:
10273 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10274 // only once.
10275 //
10276 // Therefore, for a compound assignment operator, O is considered used
10277 // everywhere except within the evaluation of E1 itself.
10278 if (isa<CompoundAssignOperator>(BO))
10279 notePreUse(O, BO);
10280
10281 Visit(BO->getLHS());
10282
10283 if (isa<CompoundAssignOperator>(BO))
10284 notePostUse(O, BO);
10285
10286 Visit(BO->getRHS());
10287
Richard Smith83e37bee2013-06-26 23:16:51 +000010288 // C++11 [expr.ass]p1:
10289 // the assignment is sequenced [...] before the value computation of the
10290 // assignment expression.
10291 // C11 6.5.16/3 has no such rule.
10292 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10293 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010294 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010295
Richard Smithc406cb72013-01-17 01:17:56 +000010296 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10297 VisitBinAssign(CAO);
10298 }
10299
10300 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10301 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10302 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10303 Object O = getObject(UO->getSubExpr(), true);
10304 if (!O)
10305 return VisitExpr(UO);
10306
10307 notePreMod(O, UO);
10308 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000010309 // C++11 [expr.pre.incr]p1:
10310 // the expression ++x is equivalent to x+=1
10311 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10312 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010313 }
10314
10315 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10316 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10317 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10318 Object O = getObject(UO->getSubExpr(), true);
10319 if (!O)
10320 return VisitExpr(UO);
10321
10322 notePreMod(O, UO);
10323 Visit(UO->getSubExpr());
10324 notePostMod(O, UO, UK_ModAsSideEffect);
10325 }
10326
10327 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10328 void VisitBinLOr(BinaryOperator *BO) {
10329 // The side-effects of the LHS of an '&&' are sequenced before the
10330 // value computation of the RHS, and hence before the value computation
10331 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10332 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000010333 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010334 {
10335 SequencedSubexpression Sequenced(*this);
10336 Visit(BO->getLHS());
10337 }
10338
10339 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010340 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010341 if (!Result)
10342 Visit(BO->getRHS());
10343 } else {
10344 // Check for unsequenced operations in the RHS, treating it as an
10345 // entirely separate evaluation.
10346 //
10347 // FIXME: If there are operations in the RHS which are unsequenced
10348 // with respect to operations outside the RHS, and those operations
10349 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000010350 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010351 }
Richard Smithc406cb72013-01-17 01:17:56 +000010352 }
10353 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000010354 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010355 {
10356 SequencedSubexpression Sequenced(*this);
10357 Visit(BO->getLHS());
10358 }
10359
10360 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010361 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010362 if (Result)
10363 Visit(BO->getRHS());
10364 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000010365 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010366 }
Richard Smithc406cb72013-01-17 01:17:56 +000010367 }
10368
10369 // Only visit the condition, unless we can be sure which subexpression will
10370 // be chosen.
10371 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000010372 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000010373 {
10374 SequencedSubexpression Sequenced(*this);
10375 Visit(CO->getCond());
10376 }
Richard Smithc406cb72013-01-17 01:17:56 +000010377
10378 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010379 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000010380 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010381 else {
Richard Smithd33f5202013-01-17 23:18:09 +000010382 WorkList.push_back(CO->getTrueExpr());
10383 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010384 }
Richard Smithc406cb72013-01-17 01:17:56 +000010385 }
10386
Richard Smithe3dbfe02013-06-30 10:40:20 +000010387 void VisitCallExpr(CallExpr *CE) {
10388 // C++11 [intro.execution]p15:
10389 // When calling a function [...], every value computation and side effect
10390 // associated with any argument expression, or with the postfix expression
10391 // designating the called function, is sequenced before execution of every
10392 // expression or statement in the body of the function [and thus before
10393 // the value computation of its result].
10394 SequencedSubexpression Sequenced(*this);
10395 Base::VisitCallExpr(CE);
10396
10397 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10398 }
10399
Richard Smithc406cb72013-01-17 01:17:56 +000010400 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010401 // This is a call, so all subexpressions are sequenced before the result.
10402 SequencedSubexpression Sequenced(*this);
10403
Richard Smithc406cb72013-01-17 01:17:56 +000010404 if (!CCE->isListInitialization())
10405 return VisitExpr(CCE);
10406
10407 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010408 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010409 SequenceTree::Seq Parent = Region;
10410 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10411 E = CCE->arg_end();
10412 I != E; ++I) {
10413 Region = Tree.allocate(Parent);
10414 Elts.push_back(Region);
10415 Visit(*I);
10416 }
10417
10418 // Forget that the initializers are sequenced.
10419 Region = Parent;
10420 for (unsigned I = 0; I < Elts.size(); ++I)
10421 Tree.merge(Elts[I]);
10422 }
10423
10424 void VisitInitListExpr(InitListExpr *ILE) {
10425 if (!SemaRef.getLangOpts().CPlusPlus11)
10426 return VisitExpr(ILE);
10427
10428 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010429 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010430 SequenceTree::Seq Parent = Region;
10431 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10432 Expr *E = ILE->getInit(I);
10433 if (!E) continue;
10434 Region = Tree.allocate(Parent);
10435 Elts.push_back(Region);
10436 Visit(E);
10437 }
10438
10439 // Forget that the initializers are sequenced.
10440 Region = Parent;
10441 for (unsigned I = 0; I < Elts.size(); ++I)
10442 Tree.merge(Elts[I]);
10443 }
10444};
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010445} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +000010446
10447void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010448 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000010449 WorkList.push_back(E);
10450 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000010451 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000010452 SequenceChecker(*this, Item, WorkList);
10453 }
Richard Smithc406cb72013-01-17 01:17:56 +000010454}
10455
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010456void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10457 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010458 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000010459 if (!E->isInstantiationDependent())
10460 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010461 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000010462 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010463 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000010464}
10465
John McCall1f425642010-11-11 03:21:53 +000010466void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10467 FieldDecl *BitField,
10468 Expr *Init) {
10469 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10470}
10471
David Majnemer61a5bbf2015-04-07 22:08:51 +000010472static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10473 SourceLocation Loc) {
10474 if (!PType->isVariablyModifiedType())
10475 return;
10476 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10477 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10478 return;
10479 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000010480 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10481 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10482 return;
10483 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000010484 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10485 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10486 return;
10487 }
10488
10489 const ArrayType *AT = S.Context.getAsArrayType(PType);
10490 if (!AT)
10491 return;
10492
10493 if (AT->getSizeModifier() != ArrayType::Star) {
10494 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10495 return;
10496 }
10497
10498 S.Diag(Loc, diag::err_array_star_in_function_definition);
10499}
10500
Mike Stump0c2ec772010-01-21 03:59:47 +000010501/// CheckParmsForFunctionDef - Check that the parameters of the given
10502/// function are appropriate for the definition of a function. This
10503/// takes care of any checks that cannot be performed on the
10504/// declaration itself, e.g., that the types of each of the function
10505/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000010506bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000010507 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010508 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000010509 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010510 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10511 // function declarator that is part of a function definition of
10512 // that function shall not have incomplete type.
10513 //
10514 // This is also C++ [dcl.fct]p6.
10515 if (!Param->isInvalidDecl() &&
10516 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010517 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010518 Param->setInvalidDecl();
10519 HasInvalidParm = true;
10520 }
10521
10522 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10523 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000010524 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000010525 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000010526 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000010527 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000010528 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000010529
10530 // C99 6.7.5.3p12:
10531 // If the function declarator is not part of a definition of that
10532 // function, parameters may have incomplete type and may use the [*]
10533 // notation in their sequences of declarator specifiers to specify
10534 // variable length array types.
10535 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000010536 // FIXME: This diagnostic should point the '[*]' if source-location
10537 // information is added for it.
10538 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010539
10540 // MSVC destroys objects passed by value in the callee. Therefore a
10541 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010542 // object's destructor. However, we don't perform any direct access check
10543 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +000010544 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10545 .getCXXABI()
10546 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +000010547 if (!Param->isInvalidDecl()) {
10548 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10549 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10550 if (!ClassDecl->isInvalidDecl() &&
10551 !ClassDecl->hasIrrelevantDestructor() &&
10552 !ClassDecl->isDependentContext()) {
10553 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10554 MarkFunctionReferenced(Param->getLocation(), Destructor);
10555 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10556 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010557 }
10558 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010559 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010560
10561 // Parameters with the pass_object_size attribute only need to be marked
10562 // constant at function definitions. Because we lack information about
10563 // whether we're on a declaration or definition when we're instantiating the
10564 // attribute, we need to check for constness here.
10565 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10566 if (!Param->getType().isConstQualified())
10567 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10568 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000010569 }
10570
10571 return HasInvalidParm;
10572}
John McCall2b5c1b22010-08-12 21:44:57 +000010573
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010574/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10575/// or MemberExpr.
10576static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10577 ASTContext &Context) {
10578 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10579 return Context.getDeclAlign(DRE->getDecl());
10580
10581 if (const auto *ME = dyn_cast<MemberExpr>(E))
10582 return Context.getDeclAlign(ME->getMemberDecl());
10583
10584 return TypeAlign;
10585}
10586
John McCall2b5c1b22010-08-12 21:44:57 +000010587/// CheckCastAlign - Implements -Wcast-align, which warns when a
10588/// pointer cast increases the alignment requirements.
10589void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10590 // This is actually a lot of work to potentially be doing on every
10591 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010592 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000010593 return;
10594
10595 // Ignore dependent types.
10596 if (T->isDependentType() || Op->getType()->isDependentType())
10597 return;
10598
10599 // Require that the destination be a pointer type.
10600 const PointerType *DestPtr = T->getAs<PointerType>();
10601 if (!DestPtr) return;
10602
10603 // If the destination has alignment 1, we're done.
10604 QualType DestPointee = DestPtr->getPointeeType();
10605 if (DestPointee->isIncompleteType()) return;
10606 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10607 if (DestAlign.isOne()) return;
10608
10609 // Require that the source be a pointer type.
10610 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10611 if (!SrcPtr) return;
10612 QualType SrcPointee = SrcPtr->getPointeeType();
10613
10614 // Whitelist casts from cv void*. We already implicitly
10615 // whitelisted casts to cv void*, since they have alignment 1.
10616 // Also whitelist casts involving incomplete types, which implicitly
10617 // includes 'void'.
10618 if (SrcPointee->isIncompleteType()) return;
10619
10620 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010621
10622 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10623 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10624 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10625 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10626 if (UO->getOpcode() == UO_AddrOf)
10627 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10628 }
10629
John McCall2b5c1b22010-08-12 21:44:57 +000010630 if (SrcAlign >= DestAlign) return;
10631
10632 Diag(TRange.getBegin(), diag::warn_cast_align)
10633 << Op->getType() << T
10634 << static_cast<unsigned>(SrcAlign.getQuantity())
10635 << static_cast<unsigned>(DestAlign.getQuantity())
10636 << TRange << Op->getSourceRange();
10637}
10638
Chandler Carruth28389f02011-08-05 09:10:50 +000010639/// \brief Check whether this array fits the idiom of a size-one tail padded
10640/// array member of a struct.
10641///
10642/// We avoid emitting out-of-bounds access warnings for such arrays as they are
10643/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000010644static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000010645 const NamedDecl *ND) {
10646 if (Size != 1 || !ND) return false;
10647
10648 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10649 if (!FD) return false;
10650
10651 // Don't consider sizes resulting from macro expansions or template argument
10652 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000010653
10654 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010655 while (TInfo) {
10656 TypeLoc TL = TInfo->getTypeLoc();
10657 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000010658 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10659 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010660 TInfo = TDL->getTypeSourceInfo();
10661 continue;
10662 }
David Blaikie6adc78e2013-02-18 22:06:02 +000010663 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10664 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000010665 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10666 return false;
10667 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010668 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000010669 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010670
10671 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000010672 if (!RD) return false;
10673 if (RD->isUnion()) return false;
10674 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10675 if (!CRD->isStandardLayout()) return false;
10676 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010677
Benjamin Kramer8c543672011-08-06 03:04:42 +000010678 // See if this is the last field decl in the record.
10679 const Decl *D = FD;
10680 while ((D = D->getNextDeclInContext()))
10681 if (isa<FieldDecl>(D))
10682 return false;
10683 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000010684}
10685
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010686void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010687 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000010688 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010689 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010690 if (IndexExpr->isValueDependent())
10691 return;
10692
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010693 const Type *EffectiveType =
10694 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010695 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010696 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010697 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010698 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000010699 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000010700
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010701 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000010702 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000010703 return;
Richard Smith13f67182011-12-16 19:31:14 +000010704 if (IndexNegated)
10705 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000010706
Craig Topperc3ec1492014-05-26 06:22:03 +000010707 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000010708 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10709 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +000010710 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +000010711 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +000010712
Ted Kremeneke4b316c2011-02-23 23:06:04 +000010713 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010714 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000010715 if (!size.isStrictlyPositive())
10716 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010717
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010718 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000010719 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010720 // Make sure we're comparing apples to apples when comparing index to size
10721 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10722 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000010723 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000010724 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010725 if (ptrarith_typesize != array_typesize) {
10726 // There's a cast to a different size type involved
10727 uint64_t ratio = array_typesize / ptrarith_typesize;
10728 // TODO: Be smarter about handling cases where array_typesize is not a
10729 // multiple of ptrarith_typesize
10730 if (ptrarith_typesize * ratio == array_typesize)
10731 size *= llvm::APInt(size.getBitWidth(), ratio);
10732 }
10733 }
10734
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010735 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010736 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010737 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010738 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010739
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010740 // For array subscripting the index must be less than size, but for pointer
10741 // arithmetic also allow the index (offset) to be equal to size since
10742 // computing the next address after the end of the array is legal and
10743 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010744 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000010745 return;
10746
10747 // Also don't warn for arrays of size 1 which are members of some
10748 // structure. These are often used to approximate flexible arrays in C89
10749 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010750 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000010751 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010752
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010753 // Suppress the warning if the subscript expression (as identified by the
10754 // ']' location) and the index expression are both from macro expansions
10755 // within a system header.
10756 if (ASE) {
10757 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10758 ASE->getRBracketLoc());
10759 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10760 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10761 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000010762 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010763 return;
10764 }
10765 }
10766
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010767 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010768 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010769 DiagID = diag::warn_array_index_exceeds_bounds;
10770
10771 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10772 PDiag(DiagID) << index.toString(10, true)
10773 << size.toString(10, true)
10774 << (unsigned)size.getLimitedValue(~0U)
10775 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010776 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010777 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010778 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010779 DiagID = diag::warn_ptr_arith_precedes_bounds;
10780 if (index.isNegative()) index = -index;
10781 }
10782
10783 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10784 PDiag(DiagID) << index.toString(10, true)
10785 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000010786 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000010787
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000010788 if (!ND) {
10789 // Try harder to find a NamedDecl to point at in the note.
10790 while (const ArraySubscriptExpr *ASE =
10791 dyn_cast<ArraySubscriptExpr>(BaseExpr))
10792 BaseExpr = ASE->getBase()->IgnoreParenCasts();
10793 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10794 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10795 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10796 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10797 }
10798
Chandler Carruth1af88f12011-02-17 21:10:52 +000010799 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010800 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10801 PDiag(diag::note_array_index_out_of_bounds)
10802 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000010803}
10804
Ted Kremenekdf26df72011-03-01 18:41:00 +000010805void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010806 int AllowOnePastEnd = 0;
10807 while (expr) {
10808 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000010809 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010810 case Stmt::ArraySubscriptExprClass: {
10811 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010812 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010813 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +000010814 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010815 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010816 case Stmt::OMPArraySectionExprClass: {
10817 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10818 if (ASE->getLowerBound())
10819 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10820 /*ASE=*/nullptr, AllowOnePastEnd > 0);
10821 return;
10822 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010823 case Stmt::UnaryOperatorClass: {
10824 // Only unwrap the * and & unary operators
10825 const UnaryOperator *UO = cast<UnaryOperator>(expr);
10826 expr = UO->getSubExpr();
10827 switch (UO->getOpcode()) {
10828 case UO_AddrOf:
10829 AllowOnePastEnd++;
10830 break;
10831 case UO_Deref:
10832 AllowOnePastEnd--;
10833 break;
10834 default:
10835 return;
10836 }
10837 break;
10838 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010839 case Stmt::ConditionalOperatorClass: {
10840 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10841 if (const Expr *lhs = cond->getLHS())
10842 CheckArrayAccess(lhs);
10843 if (const Expr *rhs = cond->getRHS())
10844 CheckArrayAccess(rhs);
10845 return;
10846 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000010847 case Stmt::CXXOperatorCallExprClass: {
10848 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
10849 for (const auto *Arg : OCE->arguments())
10850 CheckArrayAccess(Arg);
10851 return;
10852 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010853 default:
10854 return;
10855 }
Peter Collingbourne91147592011-04-15 00:35:48 +000010856 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010857}
John McCall31168b02011-06-15 23:02:42 +000010858
10859//===--- CHECK: Objective-C retain cycles ----------------------------------//
10860
10861namespace {
10862 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +000010863 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +000010864 VarDecl *Variable;
10865 SourceRange Range;
10866 SourceLocation Loc;
10867 bool Indirect;
10868
10869 void setLocsFrom(Expr *e) {
10870 Loc = e->getExprLoc();
10871 Range = e->getSourceRange();
10872 }
10873 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010874} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010875
10876/// Consider whether capturing the given variable can possibly lead to
10877/// a retain cycle.
10878static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010879 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000010880 // lifetime. In MRR, it's captured strongly if the variable is
10881 // __block and has an appropriate type.
10882 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10883 return false;
10884
10885 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010886 if (ref)
10887 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000010888 return true;
10889}
10890
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010891static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000010892 while (true) {
10893 e = e->IgnoreParens();
10894 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10895 switch (cast->getCastKind()) {
10896 case CK_BitCast:
10897 case CK_LValueBitCast:
10898 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000010899 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000010900 e = cast->getSubExpr();
10901 continue;
10902
John McCall31168b02011-06-15 23:02:42 +000010903 default:
10904 return false;
10905 }
10906 }
10907
10908 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10909 ObjCIvarDecl *ivar = ref->getDecl();
10910 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10911 return false;
10912
10913 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010914 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000010915 return false;
10916
10917 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10918 owner.Indirect = true;
10919 return true;
10920 }
10921
10922 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10923 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10924 if (!var) return false;
10925 return considerVariable(var, ref, owner);
10926 }
10927
John McCall31168b02011-06-15 23:02:42 +000010928 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10929 if (member->isArrow()) return false;
10930
10931 // Don't count this as an indirect ownership.
10932 e = member->getBase();
10933 continue;
10934 }
10935
John McCallfe96e0b2011-11-06 09:01:30 +000010936 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10937 // Only pay attention to pseudo-objects on property references.
10938 ObjCPropertyRefExpr *pre
10939 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10940 ->IgnoreParens());
10941 if (!pre) return false;
10942 if (pre->isImplicitProperty()) return false;
10943 ObjCPropertyDecl *property = pre->getExplicitProperty();
10944 if (!property->isRetaining() &&
10945 !(property->getPropertyIvarDecl() &&
10946 property->getPropertyIvarDecl()->getType()
10947 .getObjCLifetime() == Qualifiers::OCL_Strong))
10948 return false;
10949
10950 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010951 if (pre->isSuperReceiver()) {
10952 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10953 if (!owner.Variable)
10954 return false;
10955 owner.Loc = pre->getLocation();
10956 owner.Range = pre->getSourceRange();
10957 return true;
10958 }
John McCallfe96e0b2011-11-06 09:01:30 +000010959 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10960 ->getSourceExpr());
10961 continue;
10962 }
10963
John McCall31168b02011-06-15 23:02:42 +000010964 // Array ivars?
10965
10966 return false;
10967 }
10968}
10969
10970namespace {
10971 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10972 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10973 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010974 Context(Context), Variable(variable), Capturer(nullptr),
10975 VarWillBeReased(false) {}
10976 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000010977 VarDecl *Variable;
10978 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010979 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +000010980
10981 void VisitDeclRefExpr(DeclRefExpr *ref) {
10982 if (ref->getDecl() == Variable && !Capturer)
10983 Capturer = ref;
10984 }
10985
John McCall31168b02011-06-15 23:02:42 +000010986 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10987 if (Capturer) return;
10988 Visit(ref->getBase());
10989 if (Capturer && ref->isFreeIvar())
10990 Capturer = ref;
10991 }
10992
10993 void VisitBlockExpr(BlockExpr *block) {
10994 // Look inside nested blocks
10995 if (block->getBlockDecl()->capturesVariable(Variable))
10996 Visit(block->getBlockDecl()->getBody());
10997 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000010998
10999 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11000 if (Capturer) return;
11001 if (OVE->getSourceExpr())
11002 Visit(OVE->getSourceExpr());
11003 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011004 void VisitBinaryOperator(BinaryOperator *BinOp) {
11005 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11006 return;
11007 Expr *LHS = BinOp->getLHS();
11008 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11009 if (DRE->getDecl() != Variable)
11010 return;
11011 if (Expr *RHS = BinOp->getRHS()) {
11012 RHS = RHS->IgnoreParenCasts();
11013 llvm::APSInt Value;
11014 VarWillBeReased =
11015 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11016 }
11017 }
11018 }
John McCall31168b02011-06-15 23:02:42 +000011019 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011020} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000011021
11022/// Check whether the given argument is a block which captures a
11023/// variable.
11024static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11025 assert(owner.Variable && owner.Loc.isValid());
11026
11027 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000011028
11029 // Look through [^{...} copy] and Block_copy(^{...}).
11030 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11031 Selector Cmd = ME->getSelector();
11032 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11033 e = ME->getInstanceReceiver();
11034 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000011035 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000011036 e = e->IgnoreParenCasts();
11037 }
11038 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11039 if (CE->getNumArgs() == 1) {
11040 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000011041 if (Fn) {
11042 const IdentifierInfo *FnI = Fn->getIdentifier();
11043 if (FnI && FnI->isStr("_Block_copy")) {
11044 e = CE->getArg(0)->IgnoreParenCasts();
11045 }
11046 }
Jordan Rose67e887c2012-09-17 17:54:30 +000011047 }
11048 }
11049
John McCall31168b02011-06-15 23:02:42 +000011050 BlockExpr *block = dyn_cast<BlockExpr>(e);
11051 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000011052 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011053
11054 FindCaptureVisitor visitor(S.Context, owner.Variable);
11055 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011056 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000011057}
11058
11059static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11060 RetainCycleOwner &owner) {
11061 assert(capturer);
11062 assert(owner.Variable && owner.Loc.isValid());
11063
11064 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11065 << owner.Variable << capturer->getSourceRange();
11066 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11067 << owner.Indirect << owner.Range;
11068}
11069
11070/// Check for a keyword selector that starts with the word 'add' or
11071/// 'set'.
11072static bool isSetterLikeSelector(Selector sel) {
11073 if (sel.isUnarySelector()) return false;
11074
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011075 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000011076 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011077 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000011078 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011079 else if (str.startswith("add")) {
11080 // Specially whitelist 'addOperationWithBlock:'.
11081 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11082 return false;
11083 str = str.substr(3);
11084 }
John McCall31168b02011-06-15 23:02:42 +000011085 else
11086 return false;
11087
11088 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000011089 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000011090}
11091
Benjamin Kramer3a743452015-03-09 15:03:32 +000011092static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11093 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011094 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11095 Message->getReceiverInterface(),
11096 NSAPI::ClassId_NSMutableArray);
11097 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011098 return None;
11099 }
11100
11101 Selector Sel = Message->getSelector();
11102
11103 Optional<NSAPI::NSArrayMethodKind> MKOpt =
11104 S.NSAPIObj->getNSArrayMethodKind(Sel);
11105 if (!MKOpt) {
11106 return None;
11107 }
11108
11109 NSAPI::NSArrayMethodKind MK = *MKOpt;
11110
11111 switch (MK) {
11112 case NSAPI::NSMutableArr_addObject:
11113 case NSAPI::NSMutableArr_insertObjectAtIndex:
11114 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11115 return 0;
11116 case NSAPI::NSMutableArr_replaceObjectAtIndex:
11117 return 1;
11118
11119 default:
11120 return None;
11121 }
11122
11123 return None;
11124}
11125
11126static
11127Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11128 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011129 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11130 Message->getReceiverInterface(),
11131 NSAPI::ClassId_NSMutableDictionary);
11132 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011133 return None;
11134 }
11135
11136 Selector Sel = Message->getSelector();
11137
11138 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11139 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11140 if (!MKOpt) {
11141 return None;
11142 }
11143
11144 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11145
11146 switch (MK) {
11147 case NSAPI::NSMutableDict_setObjectForKey:
11148 case NSAPI::NSMutableDict_setValueForKey:
11149 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11150 return 0;
11151
11152 default:
11153 return None;
11154 }
11155
11156 return None;
11157}
11158
11159static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011160 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11161 Message->getReceiverInterface(),
11162 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000011163
Alex Denisov5dfac812015-08-06 04:51:14 +000011164 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11165 Message->getReceiverInterface(),
11166 NSAPI::ClassId_NSMutableOrderedSet);
11167 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011168 return None;
11169 }
11170
11171 Selector Sel = Message->getSelector();
11172
11173 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11174 if (!MKOpt) {
11175 return None;
11176 }
11177
11178 NSAPI::NSSetMethodKind MK = *MKOpt;
11179
11180 switch (MK) {
11181 case NSAPI::NSMutableSet_addObject:
11182 case NSAPI::NSOrderedSet_setObjectAtIndex:
11183 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11184 case NSAPI::NSOrderedSet_insertObjectAtIndex:
11185 return 0;
11186 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11187 return 1;
11188 }
11189
11190 return None;
11191}
11192
11193void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11194 if (!Message->isInstanceMessage()) {
11195 return;
11196 }
11197
11198 Optional<int> ArgOpt;
11199
11200 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11201 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11202 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11203 return;
11204 }
11205
11206 int ArgIndex = *ArgOpt;
11207
Alex Denisove1d882c2015-03-04 17:55:52 +000011208 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11209 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11210 Arg = OE->getSourceExpr()->IgnoreImpCasts();
11211 }
11212
Alex Denisov5dfac812015-08-06 04:51:14 +000011213 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011214 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011215 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011216 Diag(Message->getSourceRange().getBegin(),
11217 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000011218 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000011219 }
11220 }
Alex Denisov5dfac812015-08-06 04:51:14 +000011221 } else {
11222 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11223
11224 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11225 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11226 }
11227
11228 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11229 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11230 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11231 ValueDecl *Decl = ReceiverRE->getDecl();
11232 Diag(Message->getSourceRange().getBegin(),
11233 diag::warn_objc_circular_container)
11234 << Decl->getName() << Decl->getName();
11235 if (!ArgRE->isObjCSelfExpr()) {
11236 Diag(Decl->getLocation(),
11237 diag::note_objc_circular_container_declared_here)
11238 << Decl->getName();
11239 }
11240 }
11241 }
11242 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11243 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11244 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11245 ObjCIvarDecl *Decl = IvarRE->getDecl();
11246 Diag(Message->getSourceRange().getBegin(),
11247 diag::warn_objc_circular_container)
11248 << Decl->getName() << Decl->getName();
11249 Diag(Decl->getLocation(),
11250 diag::note_objc_circular_container_declared_here)
11251 << Decl->getName();
11252 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011253 }
11254 }
11255 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011256}
11257
John McCall31168b02011-06-15 23:02:42 +000011258/// Check a message send to see if it's likely to cause a retain cycle.
11259void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11260 // Only check instance methods whose selector looks like a setter.
11261 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11262 return;
11263
11264 // Try to find a variable that the receiver is strongly owned by.
11265 RetainCycleOwner owner;
11266 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011267 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000011268 return;
11269 } else {
11270 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11271 owner.Variable = getCurMethodDecl()->getSelfDecl();
11272 owner.Loc = msg->getSuperLoc();
11273 owner.Range = msg->getSuperLoc();
11274 }
11275
11276 // Check whether the receiver is captured by any of the arguments.
11277 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
11278 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
11279 return diagnoseRetainCycle(*this, capturer, owner);
11280}
11281
11282/// Check a property assign to see if it's likely to cause a retain cycle.
11283void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11284 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011285 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000011286 return;
11287
11288 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11289 diagnoseRetainCycle(*this, capturer, owner);
11290}
11291
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011292void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11293 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000011294 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011295 return;
11296
11297 // Because we don't have an expression for the variable, we have to set the
11298 // location explicitly here.
11299 Owner.Loc = Var->getLocation();
11300 Owner.Range = Var->getSourceRange();
11301
11302 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11303 diagnoseRetainCycle(*this, Capturer, Owner);
11304}
11305
Ted Kremenek9304da92012-12-21 08:04:28 +000011306static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11307 Expr *RHS, bool isProperty) {
11308 // Check if RHS is an Objective-C object literal, which also can get
11309 // immediately zapped in a weak reference. Note that we explicitly
11310 // allow ObjCStringLiterals, since those are designed to never really die.
11311 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011312
Ted Kremenek64873352012-12-21 22:46:35 +000011313 // This enum needs to match with the 'select' in
11314 // warn_objc_arc_literal_assign (off-by-1).
11315 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11316 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11317 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011318
11319 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000011320 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000011321 << (isProperty ? 0 : 1)
11322 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011323
11324 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000011325}
11326
Ted Kremenekc1f014a2012-12-21 19:45:30 +000011327static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11328 Qualifiers::ObjCLifetime LT,
11329 Expr *RHS, bool isProperty) {
11330 // Strip off any implicit cast added to get to the one ARC-specific.
11331 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11332 if (cast->getCastKind() == CK_ARCConsumeObject) {
11333 S.Diag(Loc, diag::warn_arc_retained_assign)
11334 << (LT == Qualifiers::OCL_ExplicitNone)
11335 << (isProperty ? 0 : 1)
11336 << RHS->getSourceRange();
11337 return true;
11338 }
11339 RHS = cast->getSubExpr();
11340 }
11341
11342 if (LT == Qualifiers::OCL_Weak &&
11343 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11344 return true;
11345
11346 return false;
11347}
11348
Ted Kremenekb36234d2012-12-21 08:04:20 +000011349bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11350 QualType LHS, Expr *RHS) {
11351 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11352
11353 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11354 return false;
11355
11356 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11357 return true;
11358
11359 return false;
11360}
11361
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011362void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11363 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011364 QualType LHSType;
11365 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011366 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011367 ObjCPropertyRefExpr *PRE
11368 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11369 if (PRE && !PRE->isImplicitProperty()) {
11370 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11371 if (PD)
11372 LHSType = PD->getType();
11373 }
11374
11375 if (LHSType.isNull())
11376 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000011377
11378 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11379
11380 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011381 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000011382 getCurFunction()->markSafeWeakUse(LHS);
11383 }
11384
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011385 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11386 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000011387
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011388 // FIXME. Check for other life times.
11389 if (LT != Qualifiers::OCL_None)
11390 return;
11391
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011392 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011393 if (PRE->isImplicitProperty())
11394 return;
11395 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11396 if (!PD)
11397 return;
11398
Bill Wendling44426052012-12-20 19:22:21 +000011399 unsigned Attributes = PD->getPropertyAttributes();
11400 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011401 // when 'assign' attribute was not explicitly specified
11402 // by user, ignore it and rely on property type itself
11403 // for lifetime info.
11404 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11405 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11406 LHSType->isObjCRetainableType())
11407 return;
11408
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011409 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000011410 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011411 Diag(Loc, diag::warn_arc_retained_property_assign)
11412 << RHS->getSourceRange();
11413 return;
11414 }
11415 RHS = cast->getSubExpr();
11416 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011417 }
Bill Wendling44426052012-12-20 19:22:21 +000011418 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000011419 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11420 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000011421 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011422 }
11423}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011424
11425//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11426
11427namespace {
11428bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11429 SourceLocation StmtLoc,
11430 const NullStmt *Body) {
11431 // Do not warn if the body is a macro that expands to nothing, e.g:
11432 //
11433 // #define CALL(x)
11434 // if (condition)
11435 // CALL(0);
11436 //
11437 if (Body->hasLeadingEmptyMacro())
11438 return false;
11439
11440 // Get line numbers of statement and body.
11441 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000011442 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011443 &StmtLineInvalid);
11444 if (StmtLineInvalid)
11445 return false;
11446
11447 bool BodyLineInvalid;
11448 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11449 &BodyLineInvalid);
11450 if (BodyLineInvalid)
11451 return false;
11452
11453 // Warn if null statement and body are on the same line.
11454 if (StmtLine != BodyLine)
11455 return false;
11456
11457 return true;
11458}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011459} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011460
11461void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11462 const Stmt *Body,
11463 unsigned DiagID) {
11464 // Since this is a syntactic check, don't emit diagnostic for template
11465 // instantiations, this just adds noise.
11466 if (CurrentInstantiationScope)
11467 return;
11468
11469 // The body should be a null statement.
11470 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11471 if (!NBody)
11472 return;
11473
11474 // Do the usual checks.
11475 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11476 return;
11477
11478 Diag(NBody->getSemiLoc(), DiagID);
11479 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11480}
11481
11482void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11483 const Stmt *PossibleBody) {
11484 assert(!CurrentInstantiationScope); // Ensured by caller
11485
11486 SourceLocation StmtLoc;
11487 const Stmt *Body;
11488 unsigned DiagID;
11489 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11490 StmtLoc = FS->getRParenLoc();
11491 Body = FS->getBody();
11492 DiagID = diag::warn_empty_for_body;
11493 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11494 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11495 Body = WS->getBody();
11496 DiagID = diag::warn_empty_while_body;
11497 } else
11498 return; // Neither `for' nor `while'.
11499
11500 // The body should be a null statement.
11501 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11502 if (!NBody)
11503 return;
11504
11505 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011506 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011507 return;
11508
11509 // Do the usual checks.
11510 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11511 return;
11512
11513 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11514 // noise level low, emit diagnostics only if for/while is followed by a
11515 // CompoundStmt, e.g.:
11516 // for (int i = 0; i < n; i++);
11517 // {
11518 // a(i);
11519 // }
11520 // or if for/while is followed by a statement with more indentation
11521 // than for/while itself:
11522 // for (int i = 0; i < n; i++);
11523 // a(i);
11524 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11525 if (!ProbableTypo) {
11526 bool BodyColInvalid;
11527 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11528 PossibleBody->getLocStart(),
11529 &BodyColInvalid);
11530 if (BodyColInvalid)
11531 return;
11532
11533 bool StmtColInvalid;
11534 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11535 S->getLocStart(),
11536 &StmtColInvalid);
11537 if (StmtColInvalid)
11538 return;
11539
11540 if (BodyCol > StmtCol)
11541 ProbableTypo = true;
11542 }
11543
11544 if (ProbableTypo) {
11545 Diag(NBody->getSemiLoc(), DiagID);
11546 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11547 }
11548}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011549
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011550//===--- CHECK: Warn on self move with std::move. -------------------------===//
11551
11552/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11553void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11554 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011555 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11556 return;
11557
Richard Smith51ec0cf2017-02-21 01:17:38 +000011558 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011559 return;
11560
11561 // Strip parens and casts away.
11562 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11563 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11564
11565 // Check for a call expression
11566 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11567 if (!CE || CE->getNumArgs() != 1)
11568 return;
11569
11570 // Check for a call to std::move
11571 const FunctionDecl *FD = CE->getDirectCallee();
11572 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11573 !FD->getIdentifier()->isStr("move"))
11574 return;
11575
11576 // Get argument from std::move
11577 RHSExpr = CE->getArg(0);
11578
11579 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11580 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11581
11582 // Two DeclRefExpr's, check that the decls are the same.
11583 if (LHSDeclRef && RHSDeclRef) {
11584 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11585 return;
11586 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11587 RHSDeclRef->getDecl()->getCanonicalDecl())
11588 return;
11589
11590 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11591 << LHSExpr->getSourceRange()
11592 << RHSExpr->getSourceRange();
11593 return;
11594 }
11595
11596 // Member variables require a different approach to check for self moves.
11597 // MemberExpr's are the same if every nested MemberExpr refers to the same
11598 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11599 // the base Expr's are CXXThisExpr's.
11600 const Expr *LHSBase = LHSExpr;
11601 const Expr *RHSBase = RHSExpr;
11602 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11603 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11604 if (!LHSME || !RHSME)
11605 return;
11606
11607 while (LHSME && RHSME) {
11608 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11609 RHSME->getMemberDecl()->getCanonicalDecl())
11610 return;
11611
11612 LHSBase = LHSME->getBase();
11613 RHSBase = RHSME->getBase();
11614 LHSME = dyn_cast<MemberExpr>(LHSBase);
11615 RHSME = dyn_cast<MemberExpr>(RHSBase);
11616 }
11617
11618 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11619 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11620 if (LHSDeclRef && RHSDeclRef) {
11621 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11622 return;
11623 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11624 RHSDeclRef->getDecl()->getCanonicalDecl())
11625 return;
11626
11627 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11628 << LHSExpr->getSourceRange()
11629 << RHSExpr->getSourceRange();
11630 return;
11631 }
11632
11633 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11634 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11635 << LHSExpr->getSourceRange()
11636 << RHSExpr->getSourceRange();
11637}
11638
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011639//===--- Layout compatibility ----------------------------------------------//
11640
11641namespace {
11642
11643bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11644
11645/// \brief Check if two enumeration types are layout-compatible.
11646bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11647 // C++11 [dcl.enum] p8:
11648 // Two enumeration types are layout-compatible if they have the same
11649 // underlying type.
11650 return ED1->isComplete() && ED2->isComplete() &&
11651 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11652}
11653
11654/// \brief Check if two fields are layout-compatible.
11655bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11656 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11657 return false;
11658
11659 if (Field1->isBitField() != Field2->isBitField())
11660 return false;
11661
11662 if (Field1->isBitField()) {
11663 // Make sure that the bit-fields are the same length.
11664 unsigned Bits1 = Field1->getBitWidthValue(C);
11665 unsigned Bits2 = Field2->getBitWidthValue(C);
11666
11667 if (Bits1 != Bits2)
11668 return false;
11669 }
11670
11671 return true;
11672}
11673
11674/// \brief Check if two standard-layout structs are layout-compatible.
11675/// (C++11 [class.mem] p17)
11676bool isLayoutCompatibleStruct(ASTContext &C,
11677 RecordDecl *RD1,
11678 RecordDecl *RD2) {
11679 // If both records are C++ classes, check that base classes match.
11680 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11681 // If one of records is a CXXRecordDecl we are in C++ mode,
11682 // thus the other one is a CXXRecordDecl, too.
11683 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11684 // Check number of base classes.
11685 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11686 return false;
11687
11688 // Check the base classes.
11689 for (CXXRecordDecl::base_class_const_iterator
11690 Base1 = D1CXX->bases_begin(),
11691 BaseEnd1 = D1CXX->bases_end(),
11692 Base2 = D2CXX->bases_begin();
11693 Base1 != BaseEnd1;
11694 ++Base1, ++Base2) {
11695 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11696 return false;
11697 }
11698 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11699 // If only RD2 is a C++ class, it should have zero base classes.
11700 if (D2CXX->getNumBases() > 0)
11701 return false;
11702 }
11703
11704 // Check the fields.
11705 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11706 Field2End = RD2->field_end(),
11707 Field1 = RD1->field_begin(),
11708 Field1End = RD1->field_end();
11709 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11710 if (!isLayoutCompatible(C, *Field1, *Field2))
11711 return false;
11712 }
11713 if (Field1 != Field1End || Field2 != Field2End)
11714 return false;
11715
11716 return true;
11717}
11718
11719/// \brief Check if two standard-layout unions are layout-compatible.
11720/// (C++11 [class.mem] p18)
11721bool isLayoutCompatibleUnion(ASTContext &C,
11722 RecordDecl *RD1,
11723 RecordDecl *RD2) {
11724 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011725 for (auto *Field2 : RD2->fields())
11726 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011727
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011728 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011729 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11730 I = UnmatchedFields.begin(),
11731 E = UnmatchedFields.end();
11732
11733 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011734 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011735 bool Result = UnmatchedFields.erase(*I);
11736 (void) Result;
11737 assert(Result);
11738 break;
11739 }
11740 }
11741 if (I == E)
11742 return false;
11743 }
11744
11745 return UnmatchedFields.empty();
11746}
11747
11748bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11749 if (RD1->isUnion() != RD2->isUnion())
11750 return false;
11751
11752 if (RD1->isUnion())
11753 return isLayoutCompatibleUnion(C, RD1, RD2);
11754 else
11755 return isLayoutCompatibleStruct(C, RD1, RD2);
11756}
11757
11758/// \brief Check if two types are layout-compatible in C++11 sense.
11759bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11760 if (T1.isNull() || T2.isNull())
11761 return false;
11762
11763 // C++11 [basic.types] p11:
11764 // If two types T1 and T2 are the same type, then T1 and T2 are
11765 // layout-compatible types.
11766 if (C.hasSameType(T1, T2))
11767 return true;
11768
11769 T1 = T1.getCanonicalType().getUnqualifiedType();
11770 T2 = T2.getCanonicalType().getUnqualifiedType();
11771
11772 const Type::TypeClass TC1 = T1->getTypeClass();
11773 const Type::TypeClass TC2 = T2->getTypeClass();
11774
11775 if (TC1 != TC2)
11776 return false;
11777
11778 if (TC1 == Type::Enum) {
11779 return isLayoutCompatible(C,
11780 cast<EnumType>(T1)->getDecl(),
11781 cast<EnumType>(T2)->getDecl());
11782 } else if (TC1 == Type::Record) {
11783 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11784 return false;
11785
11786 return isLayoutCompatible(C,
11787 cast<RecordType>(T1)->getDecl(),
11788 cast<RecordType>(T2)->getDecl());
11789 }
11790
11791 return false;
11792}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011793} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011794
11795//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11796
11797namespace {
11798/// \brief Given a type tag expression find the type tag itself.
11799///
11800/// \param TypeExpr Type tag expression, as it appears in user's code.
11801///
11802/// \param VD Declaration of an identifier that appears in a type tag.
11803///
11804/// \param MagicValue Type tag magic value.
11805bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11806 const ValueDecl **VD, uint64_t *MagicValue) {
11807 while(true) {
11808 if (!TypeExpr)
11809 return false;
11810
11811 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11812
11813 switch (TypeExpr->getStmtClass()) {
11814 case Stmt::UnaryOperatorClass: {
11815 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11816 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11817 TypeExpr = UO->getSubExpr();
11818 continue;
11819 }
11820 return false;
11821 }
11822
11823 case Stmt::DeclRefExprClass: {
11824 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11825 *VD = DRE->getDecl();
11826 return true;
11827 }
11828
11829 case Stmt::IntegerLiteralClass: {
11830 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11831 llvm::APInt MagicValueAPInt = IL->getValue();
11832 if (MagicValueAPInt.getActiveBits() <= 64) {
11833 *MagicValue = MagicValueAPInt.getZExtValue();
11834 return true;
11835 } else
11836 return false;
11837 }
11838
11839 case Stmt::BinaryConditionalOperatorClass:
11840 case Stmt::ConditionalOperatorClass: {
11841 const AbstractConditionalOperator *ACO =
11842 cast<AbstractConditionalOperator>(TypeExpr);
11843 bool Result;
11844 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11845 if (Result)
11846 TypeExpr = ACO->getTrueExpr();
11847 else
11848 TypeExpr = ACO->getFalseExpr();
11849 continue;
11850 }
11851 return false;
11852 }
11853
11854 case Stmt::BinaryOperatorClass: {
11855 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11856 if (BO->getOpcode() == BO_Comma) {
11857 TypeExpr = BO->getRHS();
11858 continue;
11859 }
11860 return false;
11861 }
11862
11863 default:
11864 return false;
11865 }
11866 }
11867}
11868
11869/// \brief Retrieve the C type corresponding to type tag TypeExpr.
11870///
11871/// \param TypeExpr Expression that specifies a type tag.
11872///
11873/// \param MagicValues Registered magic values.
11874///
11875/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11876/// kind.
11877///
11878/// \param TypeInfo Information about the corresponding C type.
11879///
11880/// \returns true if the corresponding C type was found.
11881bool GetMatchingCType(
11882 const IdentifierInfo *ArgumentKind,
11883 const Expr *TypeExpr, const ASTContext &Ctx,
11884 const llvm::DenseMap<Sema::TypeTagMagicValue,
11885 Sema::TypeTagData> *MagicValues,
11886 bool &FoundWrongKind,
11887 Sema::TypeTagData &TypeInfo) {
11888 FoundWrongKind = false;
11889
11890 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000011891 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011892
11893 uint64_t MagicValue;
11894
11895 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11896 return false;
11897
11898 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000011899 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011900 if (I->getArgumentKind() != ArgumentKind) {
11901 FoundWrongKind = true;
11902 return false;
11903 }
11904 TypeInfo.Type = I->getMatchingCType();
11905 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11906 TypeInfo.MustBeNull = I->getMustBeNull();
11907 return true;
11908 }
11909 return false;
11910 }
11911
11912 if (!MagicValues)
11913 return false;
11914
11915 llvm::DenseMap<Sema::TypeTagMagicValue,
11916 Sema::TypeTagData>::const_iterator I =
11917 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11918 if (I == MagicValues->end())
11919 return false;
11920
11921 TypeInfo = I->second;
11922 return true;
11923}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011924} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011925
11926void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11927 uint64_t MagicValue, QualType Type,
11928 bool LayoutCompatible,
11929 bool MustBeNull) {
11930 if (!TypeTagForDatatypeMagicValues)
11931 TypeTagForDatatypeMagicValues.reset(
11932 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11933
11934 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11935 (*TypeTagForDatatypeMagicValues)[Magic] =
11936 TypeTagData(Type, LayoutCompatible, MustBeNull);
11937}
11938
11939namespace {
11940bool IsSameCharType(QualType T1, QualType T2) {
11941 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11942 if (!BT1)
11943 return false;
11944
11945 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11946 if (!BT2)
11947 return false;
11948
11949 BuiltinType::Kind T1Kind = BT1->getKind();
11950 BuiltinType::Kind T2Kind = BT2->getKind();
11951
11952 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
11953 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
11954 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11955 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11956}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011957} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011958
11959void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11960 const Expr * const *ExprArgs) {
11961 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11962 bool IsPointerAttr = Attr->getIsPointer();
11963
11964 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11965 bool FoundWrongKind;
11966 TypeTagData TypeInfo;
11967 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11968 TypeTagForDatatypeMagicValues.get(),
11969 FoundWrongKind, TypeInfo)) {
11970 if (FoundWrongKind)
11971 Diag(TypeTagExpr->getExprLoc(),
11972 diag::warn_type_tag_for_datatype_wrong_kind)
11973 << TypeTagExpr->getSourceRange();
11974 return;
11975 }
11976
11977 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11978 if (IsPointerAttr) {
11979 // Skip implicit cast of pointer to `void *' (as a function argument).
11980 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000011981 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000011982 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011983 ArgumentExpr = ICE->getSubExpr();
11984 }
11985 QualType ArgumentType = ArgumentExpr->getType();
11986
11987 // Passing a `void*' pointer shouldn't trigger a warning.
11988 if (IsPointerAttr && ArgumentType->isVoidPointerType())
11989 return;
11990
11991 if (TypeInfo.MustBeNull) {
11992 // Type tag with matching void type requires a null pointer.
11993 if (!ArgumentExpr->isNullPointerConstant(Context,
11994 Expr::NPC_ValueDependentIsNotNull)) {
11995 Diag(ArgumentExpr->getExprLoc(),
11996 diag::warn_type_safety_null_pointer_required)
11997 << ArgumentKind->getName()
11998 << ArgumentExpr->getSourceRange()
11999 << TypeTagExpr->getSourceRange();
12000 }
12001 return;
12002 }
12003
12004 QualType RequiredType = TypeInfo.Type;
12005 if (IsPointerAttr)
12006 RequiredType = Context.getPointerType(RequiredType);
12007
12008 bool mismatch = false;
12009 if (!TypeInfo.LayoutCompatible) {
12010 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12011
12012 // C++11 [basic.fundamental] p1:
12013 // Plain char, signed char, and unsigned char are three distinct types.
12014 //
12015 // But we treat plain `char' as equivalent to `signed char' or `unsigned
12016 // char' depending on the current char signedness mode.
12017 if (mismatch)
12018 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12019 RequiredType->getPointeeType())) ||
12020 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12021 mismatch = false;
12022 } else
12023 if (IsPointerAttr)
12024 mismatch = !isLayoutCompatible(Context,
12025 ArgumentType->getPointeeType(),
12026 RequiredType->getPointeeType());
12027 else
12028 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12029
12030 if (mismatch)
12031 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000012032 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012033 << TypeInfo.LayoutCompatible << RequiredType
12034 << ArgumentExpr->getSourceRange()
12035 << TypeTagExpr->getSourceRange();
12036}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012037
12038void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12039 CharUnits Alignment) {
12040 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12041}
12042
12043void Sema::DiagnoseMisalignedMembers() {
12044 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000012045 const NamedDecl *ND = m.RD;
12046 if (ND->getName().empty()) {
12047 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12048 ND = TD;
12049 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012050 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000012051 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012052 }
12053 MisalignedMembers.clear();
12054}
12055
12056void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012057 E = E->IgnoreParens();
12058 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012059 return;
12060 if (isa<UnaryOperator>(E) &&
12061 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12062 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12063 if (isa<MemberExpr>(Op)) {
12064 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12065 MisalignedMember(Op));
12066 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012067 (T->isIntegerType() ||
12068 (T->isPointerType() &&
12069 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012070 MisalignedMembers.erase(MA);
12071 }
12072 }
12073}
12074
12075void Sema::RefersToMemberWithReducedAlignment(
12076 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000012077 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12078 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012079 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012080 if (!ME)
12081 return;
12082
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000012083 // No need to check expressions with an __unaligned-qualified type.
12084 if (E->getType().getQualifiers().hasUnaligned())
12085 return;
12086
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012087 // For a chain of MemberExpr like "a.b.c.d" this list
12088 // will keep FieldDecl's like [d, c, b].
12089 SmallVector<FieldDecl *, 4> ReverseMemberChain;
12090 const MemberExpr *TopME = nullptr;
12091 bool AnyIsPacked = false;
12092 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012093 QualType BaseType = ME->getBase()->getType();
12094 if (ME->isArrow())
12095 BaseType = BaseType->getPointeeType();
12096 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
12097
12098 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012099 auto *FD = dyn_cast<FieldDecl>(MD);
12100 // We do not care about non-data members.
12101 if (!FD || FD->isInvalidDecl())
12102 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012103
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012104 AnyIsPacked =
12105 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12106 ReverseMemberChain.push_back(FD);
12107
12108 TopME = ME;
12109 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12110 } while (ME);
12111 assert(TopME && "We did not compute a topmost MemberExpr!");
12112
12113 // Not the scope of this diagnostic.
12114 if (!AnyIsPacked)
12115 return;
12116
12117 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12118 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12119 // TODO: The innermost base of the member expression may be too complicated.
12120 // For now, just disregard these cases. This is left for future
12121 // improvement.
12122 if (!DRE && !isa<CXXThisExpr>(TopBase))
12123 return;
12124
12125 // Alignment expected by the whole expression.
12126 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12127
12128 // No need to do anything else with this case.
12129 if (ExpectedAlignment.isOne())
12130 return;
12131
12132 // Synthesize offset of the whole access.
12133 CharUnits Offset;
12134 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12135 I++) {
12136 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12137 }
12138
12139 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12140 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12141 ReverseMemberChain.back()->getParent()->getTypeForDecl());
12142
12143 // The base expression of the innermost MemberExpr may give
12144 // stronger guarantees than the class containing the member.
12145 if (DRE && !TopME->isArrow()) {
12146 const ValueDecl *VD = DRE->getDecl();
12147 if (!VD->getType()->isReferenceType())
12148 CompleteObjectAlignment =
12149 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12150 }
12151
12152 // Check if the synthesized offset fulfills the alignment.
12153 if (Offset % ExpectedAlignment != 0 ||
12154 // It may fulfill the offset it but the effective alignment may still be
12155 // lower than the expected expression alignment.
12156 CompleteObjectAlignment < ExpectedAlignment) {
12157 // If this happens, we want to determine a sensible culprit of this.
12158 // Intuitively, watching the chain of member expressions from right to
12159 // left, we start with the required alignment (as required by the field
12160 // type) but some packed attribute in that chain has reduced the alignment.
12161 // It may happen that another packed structure increases it again. But if
12162 // we are here such increase has not been enough. So pointing the first
12163 // FieldDecl that either is packed or else its RecordDecl is,
12164 // seems reasonable.
12165 FieldDecl *FD = nullptr;
12166 CharUnits Alignment;
12167 for (FieldDecl *FDI : ReverseMemberChain) {
12168 if (FDI->hasAttr<PackedAttr>() ||
12169 FDI->getParent()->hasAttr<PackedAttr>()) {
12170 FD = FDI;
12171 Alignment = std::min(
12172 Context.getTypeAlignInChars(FD->getType()),
12173 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12174 break;
12175 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012176 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012177 assert(FD && "We did not find a packed FieldDecl!");
12178 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012179 }
12180}
12181
12182void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12183 using namespace std::placeholders;
12184 RefersToMemberWithReducedAlignment(
12185 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12186 _2, _3, _4));
12187}
12188