blob: f5dd9b68a694c49ccb62016080b76a5d2b3f682b [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 Stulova58984e72017-02-16 12:27:47 +0000411 if (Arg2->getType().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:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000762 if (SemaBuiltinVAStart(TheCall))
763 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000764 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000765 case Builtin::BI__va_start: {
766 switch (Context.getTargetInfo().getTriple().getArch()) {
767 case llvm::Triple::arm:
768 case llvm::Triple::thumb:
769 if (SemaBuiltinVAStartARM(TheCall))
770 return ExprError();
771 break;
772 default:
773 if (SemaBuiltinVAStart(TheCall))
774 return ExprError();
775 break;
776 }
777 break;
778 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000779 case Builtin::BI__builtin_isgreater:
780 case Builtin::BI__builtin_isgreaterequal:
781 case Builtin::BI__builtin_isless:
782 case Builtin::BI__builtin_islessequal:
783 case Builtin::BI__builtin_islessgreater:
784 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000785 if (SemaBuiltinUnorderedCompare(TheCall))
786 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000787 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000788 case Builtin::BI__builtin_fpclassify:
789 if (SemaBuiltinFPClassification(TheCall, 6))
790 return ExprError();
791 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000792 case Builtin::BI__builtin_isfinite:
793 case Builtin::BI__builtin_isinf:
794 case Builtin::BI__builtin_isinf_sign:
795 case Builtin::BI__builtin_isnan:
796 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000797 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000798 return ExprError();
799 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000800 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000801 return SemaBuiltinShuffleVector(TheCall);
802 // TheCall will be freed by the smart pointer here, but that's fine, since
803 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000804 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000805 if (SemaBuiltinPrefetch(TheCall))
806 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000807 break;
David Majnemer51169932016-10-31 05:37:48 +0000808 case Builtin::BI__builtin_alloca_with_align:
809 if (SemaBuiltinAllocaWithAlign(TheCall))
810 return ExprError();
811 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000812 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000813 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000814 if (SemaBuiltinAssume(TheCall))
815 return ExprError();
816 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000817 case Builtin::BI__builtin_assume_aligned:
818 if (SemaBuiltinAssumeAligned(TheCall))
819 return ExprError();
820 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000821 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000822 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000823 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000824 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000825 case Builtin::BI__builtin_longjmp:
826 if (SemaBuiltinLongjmp(TheCall))
827 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000828 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000829 case Builtin::BI__builtin_setjmp:
830 if (SemaBuiltinSetjmp(TheCall))
831 return ExprError();
832 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000833 case Builtin::BI_setjmp:
834 case Builtin::BI_setjmpex:
835 if (checkArgCount(*this, TheCall, 1))
836 return true;
837 break;
John McCallbebede42011-02-26 05:39:39 +0000838
839 case Builtin::BI__builtin_classify_type:
840 if (checkArgCount(*this, TheCall, 1)) return true;
841 TheCall->setType(Context.IntTy);
842 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000843 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000844 if (checkArgCount(*this, TheCall, 1)) return true;
845 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000846 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000847 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000848 case Builtin::BI__sync_fetch_and_add_1:
849 case Builtin::BI__sync_fetch_and_add_2:
850 case Builtin::BI__sync_fetch_and_add_4:
851 case Builtin::BI__sync_fetch_and_add_8:
852 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000853 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000854 case Builtin::BI__sync_fetch_and_sub_1:
855 case Builtin::BI__sync_fetch_and_sub_2:
856 case Builtin::BI__sync_fetch_and_sub_4:
857 case Builtin::BI__sync_fetch_and_sub_8:
858 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000859 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000860 case Builtin::BI__sync_fetch_and_or_1:
861 case Builtin::BI__sync_fetch_and_or_2:
862 case Builtin::BI__sync_fetch_and_or_4:
863 case Builtin::BI__sync_fetch_and_or_8:
864 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000865 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000866 case Builtin::BI__sync_fetch_and_and_1:
867 case Builtin::BI__sync_fetch_and_and_2:
868 case Builtin::BI__sync_fetch_and_and_4:
869 case Builtin::BI__sync_fetch_and_and_8:
870 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000871 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000872 case Builtin::BI__sync_fetch_and_xor_1:
873 case Builtin::BI__sync_fetch_and_xor_2:
874 case Builtin::BI__sync_fetch_and_xor_4:
875 case Builtin::BI__sync_fetch_and_xor_8:
876 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000877 case Builtin::BI__sync_fetch_and_nand:
878 case Builtin::BI__sync_fetch_and_nand_1:
879 case Builtin::BI__sync_fetch_and_nand_2:
880 case Builtin::BI__sync_fetch_and_nand_4:
881 case Builtin::BI__sync_fetch_and_nand_8:
882 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000883 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000884 case Builtin::BI__sync_add_and_fetch_1:
885 case Builtin::BI__sync_add_and_fetch_2:
886 case Builtin::BI__sync_add_and_fetch_4:
887 case Builtin::BI__sync_add_and_fetch_8:
888 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000889 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000890 case Builtin::BI__sync_sub_and_fetch_1:
891 case Builtin::BI__sync_sub_and_fetch_2:
892 case Builtin::BI__sync_sub_and_fetch_4:
893 case Builtin::BI__sync_sub_and_fetch_8:
894 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000895 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000896 case Builtin::BI__sync_and_and_fetch_1:
897 case Builtin::BI__sync_and_and_fetch_2:
898 case Builtin::BI__sync_and_and_fetch_4:
899 case Builtin::BI__sync_and_and_fetch_8:
900 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000901 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000902 case Builtin::BI__sync_or_and_fetch_1:
903 case Builtin::BI__sync_or_and_fetch_2:
904 case Builtin::BI__sync_or_and_fetch_4:
905 case Builtin::BI__sync_or_and_fetch_8:
906 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000907 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000908 case Builtin::BI__sync_xor_and_fetch_1:
909 case Builtin::BI__sync_xor_and_fetch_2:
910 case Builtin::BI__sync_xor_and_fetch_4:
911 case Builtin::BI__sync_xor_and_fetch_8:
912 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000913 case Builtin::BI__sync_nand_and_fetch:
914 case Builtin::BI__sync_nand_and_fetch_1:
915 case Builtin::BI__sync_nand_and_fetch_2:
916 case Builtin::BI__sync_nand_and_fetch_4:
917 case Builtin::BI__sync_nand_and_fetch_8:
918 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000919 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000920 case Builtin::BI__sync_val_compare_and_swap_1:
921 case Builtin::BI__sync_val_compare_and_swap_2:
922 case Builtin::BI__sync_val_compare_and_swap_4:
923 case Builtin::BI__sync_val_compare_and_swap_8:
924 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000925 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000926 case Builtin::BI__sync_bool_compare_and_swap_1:
927 case Builtin::BI__sync_bool_compare_and_swap_2:
928 case Builtin::BI__sync_bool_compare_and_swap_4:
929 case Builtin::BI__sync_bool_compare_and_swap_8:
930 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000931 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000932 case Builtin::BI__sync_lock_test_and_set_1:
933 case Builtin::BI__sync_lock_test_and_set_2:
934 case Builtin::BI__sync_lock_test_and_set_4:
935 case Builtin::BI__sync_lock_test_and_set_8:
936 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000937 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000938 case Builtin::BI__sync_lock_release_1:
939 case Builtin::BI__sync_lock_release_2:
940 case Builtin::BI__sync_lock_release_4:
941 case Builtin::BI__sync_lock_release_8:
942 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000943 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000944 case Builtin::BI__sync_swap_1:
945 case Builtin::BI__sync_swap_2:
946 case Builtin::BI__sync_swap_4:
947 case Builtin::BI__sync_swap_8:
948 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000949 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000950 case Builtin::BI__builtin_nontemporal_load:
951 case Builtin::BI__builtin_nontemporal_store:
952 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000953#define BUILTIN(ID, TYPE, ATTRS)
954#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
955 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000956 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000957#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000958 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000959 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000960 return ExprError();
961 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000962 case Builtin::BI__builtin_addressof:
963 if (SemaBuiltinAddressof(*this, TheCall))
964 return ExprError();
965 break;
John McCall03107a42015-10-29 20:48:01 +0000966 case Builtin::BI__builtin_add_overflow:
967 case Builtin::BI__builtin_sub_overflow:
968 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +0000969 if (SemaBuiltinOverflow(*this, TheCall))
970 return ExprError();
971 break;
Richard Smith760520b2014-06-03 23:27:44 +0000972 case Builtin::BI__builtin_operator_new:
973 case Builtin::BI__builtin_operator_delete:
974 if (!getLangOpts().CPlusPlus) {
975 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
976 << (BuiltinID == Builtin::BI__builtin_operator_new
977 ? "__builtin_operator_new"
978 : "__builtin_operator_delete")
979 << "C++";
980 return ExprError();
981 }
982 // CodeGen assumes it can find the global new and delete to call,
983 // so ensure that they are declared.
984 DeclareGlobalNewDelete();
985 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000986
987 // check secure string manipulation functions where overflows
988 // are detectable at compile time
989 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000990 case Builtin::BI__builtin___memmove_chk:
991 case Builtin::BI__builtin___memset_chk:
992 case Builtin::BI__builtin___strlcat_chk:
993 case Builtin::BI__builtin___strlcpy_chk:
994 case Builtin::BI__builtin___strncat_chk:
995 case Builtin::BI__builtin___strncpy_chk:
996 case Builtin::BI__builtin___stpncpy_chk:
997 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
998 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000999 case Builtin::BI__builtin___memccpy_chk:
1000 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1001 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001002 case Builtin::BI__builtin___snprintf_chk:
1003 case Builtin::BI__builtin___vsnprintf_chk:
1004 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1005 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001006 case Builtin::BI__builtin_call_with_static_chain:
1007 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1008 return ExprError();
1009 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001010 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001011 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001012 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1013 diag::err_seh___except_block))
1014 return ExprError();
1015 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001016 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001017 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001018 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1019 diag::err_seh___except_filter))
1020 return ExprError();
1021 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001022 case Builtin::BI__GetExceptionInfo:
1023 if (checkArgCount(*this, TheCall, 1))
1024 return ExprError();
1025
1026 if (CheckCXXThrowOperand(
1027 TheCall->getLocStart(),
1028 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1029 TheCall))
1030 return ExprError();
1031
1032 TheCall->setType(Context.VoidPtrTy);
1033 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001034 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001035 case Builtin::BIread_pipe:
1036 case Builtin::BIwrite_pipe:
1037 // Since those two functions are declared with var args, we need a semantic
1038 // check for the argument.
1039 if (SemaBuiltinRWPipe(*this, TheCall))
1040 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001041 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001042 break;
1043 case Builtin::BIreserve_read_pipe:
1044 case Builtin::BIreserve_write_pipe:
1045 case Builtin::BIwork_group_reserve_read_pipe:
1046 case Builtin::BIwork_group_reserve_write_pipe:
1047 case Builtin::BIsub_group_reserve_read_pipe:
1048 case Builtin::BIsub_group_reserve_write_pipe:
1049 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1050 return ExprError();
1051 // Since return type of reserve_read/write_pipe built-in function is
1052 // reserve_id_t, which is not defined in the builtin def file , we used int
1053 // as return type and need to override the return type of these functions.
1054 TheCall->setType(Context.OCLReserveIDTy);
1055 break;
1056 case Builtin::BIcommit_read_pipe:
1057 case Builtin::BIcommit_write_pipe:
1058 case Builtin::BIwork_group_commit_read_pipe:
1059 case Builtin::BIwork_group_commit_write_pipe:
1060 case Builtin::BIsub_group_commit_read_pipe:
1061 case Builtin::BIsub_group_commit_write_pipe:
1062 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1063 return ExprError();
1064 break;
1065 case Builtin::BIget_pipe_num_packets:
1066 case Builtin::BIget_pipe_max_packets:
1067 if (SemaBuiltinPipePackets(*this, TheCall))
1068 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001069 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001070 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001071 case Builtin::BIto_global:
1072 case Builtin::BIto_local:
1073 case Builtin::BIto_private:
1074 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1075 return ExprError();
1076 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001077 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1078 case Builtin::BIenqueue_kernel:
1079 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1080 return ExprError();
1081 break;
1082 case Builtin::BIget_kernel_work_group_size:
1083 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1084 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1085 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001086 break;
1087 case Builtin::BI__builtin_os_log_format:
1088 case Builtin::BI__builtin_os_log_format_buffer_size:
1089 if (SemaBuiltinOSLogFormat(TheCall)) {
1090 return ExprError();
1091 }
1092 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001093 }
Richard Smith760520b2014-06-03 23:27:44 +00001094
Nate Begeman4904e322010-06-08 02:47:44 +00001095 // Since the target specific builtins for each arch overlap, only check those
1096 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001097 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001098 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001099 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001100 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001101 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001102 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001103 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1104 return ExprError();
1105 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001106 case llvm::Triple::aarch64:
1107 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001108 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001109 return ExprError();
1110 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001111 case llvm::Triple::mips:
1112 case llvm::Triple::mipsel:
1113 case llvm::Triple::mips64:
1114 case llvm::Triple::mips64el:
1115 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1116 return ExprError();
1117 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001118 case llvm::Triple::systemz:
1119 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1120 return ExprError();
1121 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001122 case llvm::Triple::x86:
1123 case llvm::Triple::x86_64:
1124 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1125 return ExprError();
1126 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001127 case llvm::Triple::ppc:
1128 case llvm::Triple::ppc64:
1129 case llvm::Triple::ppc64le:
1130 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1131 return ExprError();
1132 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001133 default:
1134 break;
1135 }
1136 }
1137
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001138 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001139}
1140
Nate Begeman91e1fea2010-06-14 05:21:25 +00001141// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001142static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001143 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001144 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001145 switch (Type.getEltType()) {
1146 case NeonTypeFlags::Int8:
1147 case NeonTypeFlags::Poly8:
1148 return shift ? 7 : (8 << IsQuad) - 1;
1149 case NeonTypeFlags::Int16:
1150 case NeonTypeFlags::Poly16:
1151 return shift ? 15 : (4 << IsQuad) - 1;
1152 case NeonTypeFlags::Int32:
1153 return shift ? 31 : (2 << IsQuad) - 1;
1154 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001155 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001156 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001157 case NeonTypeFlags::Poly128:
1158 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001159 case NeonTypeFlags::Float16:
1160 assert(!shift && "cannot shift float types!");
1161 return (4 << IsQuad) - 1;
1162 case NeonTypeFlags::Float32:
1163 assert(!shift && "cannot shift float types!");
1164 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001165 case NeonTypeFlags::Float64:
1166 assert(!shift && "cannot shift float types!");
1167 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001168 }
David Blaikie8a40f702012-01-17 06:56:22 +00001169 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001170}
1171
Bob Wilsone4d77232011-11-08 05:04:11 +00001172/// getNeonEltType - Return the QualType corresponding to the elements of
1173/// the vector type specified by the NeonTypeFlags. This is used to check
1174/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001175static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001176 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001177 switch (Flags.getEltType()) {
1178 case NeonTypeFlags::Int8:
1179 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1180 case NeonTypeFlags::Int16:
1181 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1182 case NeonTypeFlags::Int32:
1183 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1184 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001185 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001186 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1187 else
1188 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1189 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001190 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001191 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001192 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001193 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001194 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001195 if (IsInt64Long)
1196 return Context.UnsignedLongTy;
1197 else
1198 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001199 case NeonTypeFlags::Poly128:
1200 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001201 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001202 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001203 case NeonTypeFlags::Float32:
1204 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001205 case NeonTypeFlags::Float64:
1206 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001207 }
David Blaikie8a40f702012-01-17 06:56:22 +00001208 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001209}
1210
Tim Northover12670412014-02-19 10:37:05 +00001211bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001212 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001213 uint64_t mask = 0;
1214 unsigned TV = 0;
1215 int PtrArgNum = -1;
1216 bool HasConstPtr = false;
1217 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001218#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001219#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001220#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001221 }
1222
1223 // For NEON intrinsics which are overloaded on vector element type, validate
1224 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001225 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001226 if (mask) {
1227 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1228 return true;
1229
1230 TV = Result.getLimitedValue(64);
1231 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1232 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001233 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001234 }
1235
1236 if (PtrArgNum >= 0) {
1237 // Check that pointer arguments have the specified type.
1238 Expr *Arg = TheCall->getArg(PtrArgNum);
1239 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1240 Arg = ICE->getSubExpr();
1241 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1242 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001243
Tim Northovera2ee4332014-03-29 15:09:45 +00001244 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
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) {
Nate Begeman55483092010-06-09 01:10:23 +00001394 llvm::APSInt Result;
1395
Tim Northover6aacd492013-07-16 09:47:53 +00001396 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001397 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1398 BuiltinID == ARM::BI__builtin_arm_strex ||
1399 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001400 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001401 }
1402
Yi Kong26d104a2014-08-13 19:18:14 +00001403 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1404 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1405 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1406 }
1407
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001408 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1409 BuiltinID == ARM::BI__builtin_arm_wsr64)
1410 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1411
1412 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1413 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1414 BuiltinID == ARM::BI__builtin_arm_wsr ||
1415 BuiltinID == ARM::BI__builtin_arm_wsrp)
1416 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1417
Tim Northover12670412014-02-19 10:37:05 +00001418 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1419 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001420
Yi Kong4efadfb2014-07-03 16:01:25 +00001421 // For intrinsics which take an immediate value as part of the instruction,
1422 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001423 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001424 switch (BuiltinID) {
1425 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001426 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1427 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001428 case ARM::BI__builtin_arm_vcvtr_f:
1429 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001430 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001431 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001432 case ARM::BI__builtin_arm_isb:
1433 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001434 }
Nate Begemand773fe62010-06-13 04:47:52 +00001435
Nate Begemanf568b072010-08-03 21:32:34 +00001436 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001437 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001438}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001439
Tim Northover573cbee2014-05-24 12:52:07 +00001440bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001441 CallExpr *TheCall) {
1442 llvm::APSInt Result;
1443
Tim Northover573cbee2014-05-24 12:52:07 +00001444 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001445 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1446 BuiltinID == AArch64::BI__builtin_arm_strex ||
1447 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001448 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1449 }
1450
Yi Konga5548432014-08-13 19:18:20 +00001451 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1452 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1453 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1454 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1455 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1456 }
1457
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001458 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1459 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001460 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001461
1462 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1463 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1464 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1465 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1466 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1467
Tim Northovera2ee4332014-03-29 15:09:45 +00001468 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1469 return true;
1470
Yi Kong19a29ac2014-07-17 10:52:06 +00001471 // For intrinsics which take an immediate value as part of the instruction,
1472 // range check them here.
1473 unsigned i = 0, l = 0, u = 0;
1474 switch (BuiltinID) {
1475 default: return false;
1476 case AArch64::BI__builtin_arm_dmb:
1477 case AArch64::BI__builtin_arm_dsb:
1478 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1479 }
1480
Yi Kong19a29ac2014-07-17 10:52:06 +00001481 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001482}
1483
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001484// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1485// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1486// ordering for DSP is unspecified. MSA is ordered by the data format used
1487// by the underlying instruction i.e., df/m, df/n and then by size.
1488//
1489// FIXME: The size tests here should instead be tablegen'd along with the
1490// definitions from include/clang/Basic/BuiltinsMips.def.
1491// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1492// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001493bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001494 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001495 switch (BuiltinID) {
1496 default: return false;
1497 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1498 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001499 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1500 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1501 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1502 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1503 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001504 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1505 // df/m field.
1506 // These intrinsics take an unsigned 3 bit immediate.
1507 case Mips::BI__builtin_msa_bclri_b:
1508 case Mips::BI__builtin_msa_bnegi_b:
1509 case Mips::BI__builtin_msa_bseti_b:
1510 case Mips::BI__builtin_msa_sat_s_b:
1511 case Mips::BI__builtin_msa_sat_u_b:
1512 case Mips::BI__builtin_msa_slli_b:
1513 case Mips::BI__builtin_msa_srai_b:
1514 case Mips::BI__builtin_msa_srari_b:
1515 case Mips::BI__builtin_msa_srli_b:
1516 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1517 case Mips::BI__builtin_msa_binsli_b:
1518 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1519 // These intrinsics take an unsigned 4 bit immediate.
1520 case Mips::BI__builtin_msa_bclri_h:
1521 case Mips::BI__builtin_msa_bnegi_h:
1522 case Mips::BI__builtin_msa_bseti_h:
1523 case Mips::BI__builtin_msa_sat_s_h:
1524 case Mips::BI__builtin_msa_sat_u_h:
1525 case Mips::BI__builtin_msa_slli_h:
1526 case Mips::BI__builtin_msa_srai_h:
1527 case Mips::BI__builtin_msa_srari_h:
1528 case Mips::BI__builtin_msa_srli_h:
1529 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1530 case Mips::BI__builtin_msa_binsli_h:
1531 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1532 // These intrinsics take an unsigned 5 bit immedate.
1533 // The first block of intrinsics actually have an unsigned 5 bit field,
1534 // not a df/n field.
1535 case Mips::BI__builtin_msa_clei_u_b:
1536 case Mips::BI__builtin_msa_clei_u_h:
1537 case Mips::BI__builtin_msa_clei_u_w:
1538 case Mips::BI__builtin_msa_clei_u_d:
1539 case Mips::BI__builtin_msa_clti_u_b:
1540 case Mips::BI__builtin_msa_clti_u_h:
1541 case Mips::BI__builtin_msa_clti_u_w:
1542 case Mips::BI__builtin_msa_clti_u_d:
1543 case Mips::BI__builtin_msa_maxi_u_b:
1544 case Mips::BI__builtin_msa_maxi_u_h:
1545 case Mips::BI__builtin_msa_maxi_u_w:
1546 case Mips::BI__builtin_msa_maxi_u_d:
1547 case Mips::BI__builtin_msa_mini_u_b:
1548 case Mips::BI__builtin_msa_mini_u_h:
1549 case Mips::BI__builtin_msa_mini_u_w:
1550 case Mips::BI__builtin_msa_mini_u_d:
1551 case Mips::BI__builtin_msa_addvi_b:
1552 case Mips::BI__builtin_msa_addvi_h:
1553 case Mips::BI__builtin_msa_addvi_w:
1554 case Mips::BI__builtin_msa_addvi_d:
1555 case Mips::BI__builtin_msa_bclri_w:
1556 case Mips::BI__builtin_msa_bnegi_w:
1557 case Mips::BI__builtin_msa_bseti_w:
1558 case Mips::BI__builtin_msa_sat_s_w:
1559 case Mips::BI__builtin_msa_sat_u_w:
1560 case Mips::BI__builtin_msa_slli_w:
1561 case Mips::BI__builtin_msa_srai_w:
1562 case Mips::BI__builtin_msa_srari_w:
1563 case Mips::BI__builtin_msa_srli_w:
1564 case Mips::BI__builtin_msa_srlri_w:
1565 case Mips::BI__builtin_msa_subvi_b:
1566 case Mips::BI__builtin_msa_subvi_h:
1567 case Mips::BI__builtin_msa_subvi_w:
1568 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1569 case Mips::BI__builtin_msa_binsli_w:
1570 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1571 // These intrinsics take an unsigned 6 bit immediate.
1572 case Mips::BI__builtin_msa_bclri_d:
1573 case Mips::BI__builtin_msa_bnegi_d:
1574 case Mips::BI__builtin_msa_bseti_d:
1575 case Mips::BI__builtin_msa_sat_s_d:
1576 case Mips::BI__builtin_msa_sat_u_d:
1577 case Mips::BI__builtin_msa_slli_d:
1578 case Mips::BI__builtin_msa_srai_d:
1579 case Mips::BI__builtin_msa_srari_d:
1580 case Mips::BI__builtin_msa_srli_d:
1581 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1582 case Mips::BI__builtin_msa_binsli_d:
1583 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1584 // These intrinsics take a signed 5 bit immediate.
1585 case Mips::BI__builtin_msa_ceqi_b:
1586 case Mips::BI__builtin_msa_ceqi_h:
1587 case Mips::BI__builtin_msa_ceqi_w:
1588 case Mips::BI__builtin_msa_ceqi_d:
1589 case Mips::BI__builtin_msa_clti_s_b:
1590 case Mips::BI__builtin_msa_clti_s_h:
1591 case Mips::BI__builtin_msa_clti_s_w:
1592 case Mips::BI__builtin_msa_clti_s_d:
1593 case Mips::BI__builtin_msa_clei_s_b:
1594 case Mips::BI__builtin_msa_clei_s_h:
1595 case Mips::BI__builtin_msa_clei_s_w:
1596 case Mips::BI__builtin_msa_clei_s_d:
1597 case Mips::BI__builtin_msa_maxi_s_b:
1598 case Mips::BI__builtin_msa_maxi_s_h:
1599 case Mips::BI__builtin_msa_maxi_s_w:
1600 case Mips::BI__builtin_msa_maxi_s_d:
1601 case Mips::BI__builtin_msa_mini_s_b:
1602 case Mips::BI__builtin_msa_mini_s_h:
1603 case Mips::BI__builtin_msa_mini_s_w:
1604 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1605 // These intrinsics take an unsigned 8 bit immediate.
1606 case Mips::BI__builtin_msa_andi_b:
1607 case Mips::BI__builtin_msa_nori_b:
1608 case Mips::BI__builtin_msa_ori_b:
1609 case Mips::BI__builtin_msa_shf_b:
1610 case Mips::BI__builtin_msa_shf_h:
1611 case Mips::BI__builtin_msa_shf_w:
1612 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1613 case Mips::BI__builtin_msa_bseli_b:
1614 case Mips::BI__builtin_msa_bmnzi_b:
1615 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1616 // df/n format
1617 // These intrinsics take an unsigned 4 bit immediate.
1618 case Mips::BI__builtin_msa_copy_s_b:
1619 case Mips::BI__builtin_msa_copy_u_b:
1620 case Mips::BI__builtin_msa_insve_b:
1621 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001622 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1623 // These intrinsics take an unsigned 3 bit immediate.
1624 case Mips::BI__builtin_msa_copy_s_h:
1625 case Mips::BI__builtin_msa_copy_u_h:
1626 case Mips::BI__builtin_msa_insve_h:
1627 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001628 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1629 // These intrinsics take an unsigned 2 bit immediate.
1630 case Mips::BI__builtin_msa_copy_s_w:
1631 case Mips::BI__builtin_msa_copy_u_w:
1632 case Mips::BI__builtin_msa_insve_w:
1633 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001634 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1635 // These intrinsics take an unsigned 1 bit immediate.
1636 case Mips::BI__builtin_msa_copy_s_d:
1637 case Mips::BI__builtin_msa_copy_u_d:
1638 case Mips::BI__builtin_msa_insve_d:
1639 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001640 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1641 // Memory offsets and immediate loads.
1642 // These intrinsics take a signed 10 bit immediate.
1643 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 127; break;
1644 case Mips::BI__builtin_msa_ldi_h:
1645 case Mips::BI__builtin_msa_ldi_w:
1646 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1647 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1648 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1649 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1650 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1651 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1652 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1653 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1654 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001655 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001656
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001657 if (!m)
1658 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1659
1660 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1661 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001662}
1663
Kit Bartone50adcb2015-03-30 19:40:59 +00001664bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1665 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001666 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1667 BuiltinID == PPC::BI__builtin_divdeu ||
1668 BuiltinID == PPC::BI__builtin_bpermd;
1669 bool IsTarget64Bit = Context.getTargetInfo()
1670 .getTypeWidth(Context
1671 .getTargetInfo()
1672 .getIntPtrType()) == 64;
1673 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1674 BuiltinID == PPC::BI__builtin_divweu ||
1675 BuiltinID == PPC::BI__builtin_divde ||
1676 BuiltinID == PPC::BI__builtin_divdeu;
1677
1678 if (Is64BitBltin && !IsTarget64Bit)
1679 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1680 << TheCall->getSourceRange();
1681
1682 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1683 (BuiltinID == PPC::BI__builtin_bpermd &&
1684 !Context.getTargetInfo().hasFeature("bpermd")))
1685 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1686 << TheCall->getSourceRange();
1687
Kit Bartone50adcb2015-03-30 19:40:59 +00001688 switch (BuiltinID) {
1689 default: return false;
1690 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1691 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1692 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1693 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1694 case PPC::BI__builtin_tbegin:
1695 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1696 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1697 case PPC::BI__builtin_tabortwc:
1698 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1699 case PPC::BI__builtin_tabortwci:
1700 case PPC::BI__builtin_tabortdci:
1701 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1702 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1703 }
1704 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1705}
1706
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001707bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1708 CallExpr *TheCall) {
1709 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1710 Expr *Arg = TheCall->getArg(0);
1711 llvm::APSInt AbortCode(32);
1712 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1713 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1714 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1715 << Arg->getSourceRange();
1716 }
1717
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001718 // For intrinsics which take an immediate value as part of the instruction,
1719 // range check them here.
1720 unsigned i = 0, l = 0, u = 0;
1721 switch (BuiltinID) {
1722 default: return false;
1723 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1724 case SystemZ::BI__builtin_s390_verimb:
1725 case SystemZ::BI__builtin_s390_verimh:
1726 case SystemZ::BI__builtin_s390_verimf:
1727 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1728 case SystemZ::BI__builtin_s390_vfaeb:
1729 case SystemZ::BI__builtin_s390_vfaeh:
1730 case SystemZ::BI__builtin_s390_vfaef:
1731 case SystemZ::BI__builtin_s390_vfaebs:
1732 case SystemZ::BI__builtin_s390_vfaehs:
1733 case SystemZ::BI__builtin_s390_vfaefs:
1734 case SystemZ::BI__builtin_s390_vfaezb:
1735 case SystemZ::BI__builtin_s390_vfaezh:
1736 case SystemZ::BI__builtin_s390_vfaezf:
1737 case SystemZ::BI__builtin_s390_vfaezbs:
1738 case SystemZ::BI__builtin_s390_vfaezhs:
1739 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1740 case SystemZ::BI__builtin_s390_vfidb:
1741 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1742 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1743 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1744 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1745 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1746 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1747 case SystemZ::BI__builtin_s390_vstrcb:
1748 case SystemZ::BI__builtin_s390_vstrch:
1749 case SystemZ::BI__builtin_s390_vstrcf:
1750 case SystemZ::BI__builtin_s390_vstrczb:
1751 case SystemZ::BI__builtin_s390_vstrczh:
1752 case SystemZ::BI__builtin_s390_vstrczf:
1753 case SystemZ::BI__builtin_s390_vstrcbs:
1754 case SystemZ::BI__builtin_s390_vstrchs:
1755 case SystemZ::BI__builtin_s390_vstrcfs:
1756 case SystemZ::BI__builtin_s390_vstrczbs:
1757 case SystemZ::BI__builtin_s390_vstrczhs:
1758 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1759 }
1760 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001761}
1762
Craig Topper5ba2c502015-11-07 08:08:31 +00001763/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1764/// This checks that the target supports __builtin_cpu_supports and
1765/// that the string argument is constant and valid.
1766static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1767 Expr *Arg = TheCall->getArg(0);
1768
1769 // Check if the argument is a string literal.
1770 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1771 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1772 << Arg->getSourceRange();
1773
1774 // Check the contents of the string.
1775 StringRef Feature =
1776 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1777 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1778 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1779 << Arg->getSourceRange();
1780 return false;
1781}
1782
Craig Toppera7e253e2016-09-23 04:48:31 +00001783// Check if the rounding mode is legal.
1784bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1785 // Indicates if this instruction has rounding control or just SAE.
1786 bool HasRC = false;
1787
1788 unsigned ArgNum = 0;
1789 switch (BuiltinID) {
1790 default:
1791 return false;
1792 case X86::BI__builtin_ia32_vcvttsd2si32:
1793 case X86::BI__builtin_ia32_vcvttsd2si64:
1794 case X86::BI__builtin_ia32_vcvttsd2usi32:
1795 case X86::BI__builtin_ia32_vcvttsd2usi64:
1796 case X86::BI__builtin_ia32_vcvttss2si32:
1797 case X86::BI__builtin_ia32_vcvttss2si64:
1798 case X86::BI__builtin_ia32_vcvttss2usi32:
1799 case X86::BI__builtin_ia32_vcvttss2usi64:
1800 ArgNum = 1;
1801 break;
1802 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1803 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1804 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1805 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1806 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1807 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1808 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1809 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1810 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1811 case X86::BI__builtin_ia32_exp2pd_mask:
1812 case X86::BI__builtin_ia32_exp2ps_mask:
1813 case X86::BI__builtin_ia32_getexppd512_mask:
1814 case X86::BI__builtin_ia32_getexpps512_mask:
1815 case X86::BI__builtin_ia32_rcp28pd_mask:
1816 case X86::BI__builtin_ia32_rcp28ps_mask:
1817 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1818 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1819 case X86::BI__builtin_ia32_vcomisd:
1820 case X86::BI__builtin_ia32_vcomiss:
1821 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1822 ArgNum = 3;
1823 break;
1824 case X86::BI__builtin_ia32_cmppd512_mask:
1825 case X86::BI__builtin_ia32_cmpps512_mask:
1826 case X86::BI__builtin_ia32_cmpsd_mask:
1827 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001828 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001829 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1830 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001831 case X86::BI__builtin_ia32_maxpd512_mask:
1832 case X86::BI__builtin_ia32_maxps512_mask:
1833 case X86::BI__builtin_ia32_maxsd_round_mask:
1834 case X86::BI__builtin_ia32_maxss_round_mask:
1835 case X86::BI__builtin_ia32_minpd512_mask:
1836 case X86::BI__builtin_ia32_minps512_mask:
1837 case X86::BI__builtin_ia32_minsd_round_mask:
1838 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001839 case X86::BI__builtin_ia32_rcp28sd_round_mask:
1840 case X86::BI__builtin_ia32_rcp28ss_round_mask:
1841 case X86::BI__builtin_ia32_reducepd512_mask:
1842 case X86::BI__builtin_ia32_reduceps512_mask:
1843 case X86::BI__builtin_ia32_rndscalepd_mask:
1844 case X86::BI__builtin_ia32_rndscaleps_mask:
1845 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1846 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1847 ArgNum = 4;
1848 break;
1849 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001850 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001851 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001852 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001853 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001854 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001855 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001856 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001857 case X86::BI__builtin_ia32_rangepd512_mask:
1858 case X86::BI__builtin_ia32_rangeps512_mask:
1859 case X86::BI__builtin_ia32_rangesd128_round_mask:
1860 case X86::BI__builtin_ia32_rangess128_round_mask:
1861 case X86::BI__builtin_ia32_reducesd_mask:
1862 case X86::BI__builtin_ia32_reducess_mask:
1863 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1864 case X86::BI__builtin_ia32_rndscaless_round_mask:
1865 ArgNum = 5;
1866 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00001867 case X86::BI__builtin_ia32_vcvtsd2si64:
1868 case X86::BI__builtin_ia32_vcvtsd2si32:
1869 case X86::BI__builtin_ia32_vcvtsd2usi32:
1870 case X86::BI__builtin_ia32_vcvtsd2usi64:
1871 case X86::BI__builtin_ia32_vcvtss2si32:
1872 case X86::BI__builtin_ia32_vcvtss2si64:
1873 case X86::BI__builtin_ia32_vcvtss2usi32:
1874 case X86::BI__builtin_ia32_vcvtss2usi64:
1875 ArgNum = 1;
1876 HasRC = true;
1877 break;
Craig Topper8e066312016-11-07 07:01:09 +00001878 case X86::BI__builtin_ia32_cvtsi2sd64:
1879 case X86::BI__builtin_ia32_cvtsi2ss32:
1880 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00001881 case X86::BI__builtin_ia32_cvtusi2sd64:
1882 case X86::BI__builtin_ia32_cvtusi2ss32:
1883 case X86::BI__builtin_ia32_cvtusi2ss64:
1884 ArgNum = 2;
1885 HasRC = true;
1886 break;
1887 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1888 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1889 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1890 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1891 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1892 case X86::BI__builtin_ia32_cvtps2qq512_mask:
1893 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1894 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1895 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1896 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1897 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001898 case X86::BI__builtin_ia32_sqrtpd512_mask:
1899 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001900 ArgNum = 3;
1901 HasRC = true;
1902 break;
1903 case X86::BI__builtin_ia32_addpd512_mask:
1904 case X86::BI__builtin_ia32_addps512_mask:
1905 case X86::BI__builtin_ia32_divpd512_mask:
1906 case X86::BI__builtin_ia32_divps512_mask:
1907 case X86::BI__builtin_ia32_mulpd512_mask:
1908 case X86::BI__builtin_ia32_mulps512_mask:
1909 case X86::BI__builtin_ia32_subpd512_mask:
1910 case X86::BI__builtin_ia32_subps512_mask:
1911 case X86::BI__builtin_ia32_addss_round_mask:
1912 case X86::BI__builtin_ia32_addsd_round_mask:
1913 case X86::BI__builtin_ia32_divss_round_mask:
1914 case X86::BI__builtin_ia32_divsd_round_mask:
1915 case X86::BI__builtin_ia32_mulss_round_mask:
1916 case X86::BI__builtin_ia32_mulsd_round_mask:
1917 case X86::BI__builtin_ia32_subss_round_mask:
1918 case X86::BI__builtin_ia32_subsd_round_mask:
1919 case X86::BI__builtin_ia32_scalefpd512_mask:
1920 case X86::BI__builtin_ia32_scalefps512_mask:
1921 case X86::BI__builtin_ia32_scalefsd_round_mask:
1922 case X86::BI__builtin_ia32_scalefss_round_mask:
1923 case X86::BI__builtin_ia32_getmantpd512_mask:
1924 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001925 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
1926 case X86::BI__builtin_ia32_sqrtsd_round_mask:
1927 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001928 case X86::BI__builtin_ia32_vfmaddpd512_mask:
1929 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1930 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1931 case X86::BI__builtin_ia32_vfmaddps512_mask:
1932 case X86::BI__builtin_ia32_vfmaddps512_mask3:
1933 case X86::BI__builtin_ia32_vfmaddps512_maskz:
1934 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1935 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1936 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1937 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1938 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1939 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1940 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1941 case X86::BI__builtin_ia32_vfmsubps512_mask3:
1942 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1943 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1944 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1945 case X86::BI__builtin_ia32_vfnmaddps512_mask:
1946 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1947 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1948 case X86::BI__builtin_ia32_vfnmsubps512_mask:
1949 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1950 case X86::BI__builtin_ia32_vfmaddsd3_mask:
1951 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1952 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1953 case X86::BI__builtin_ia32_vfmaddss3_mask:
1954 case X86::BI__builtin_ia32_vfmaddss3_maskz:
1955 case X86::BI__builtin_ia32_vfmaddss3_mask3:
1956 ArgNum = 4;
1957 HasRC = true;
1958 break;
1959 case X86::BI__builtin_ia32_getmantsd_round_mask:
1960 case X86::BI__builtin_ia32_getmantss_round_mask:
1961 ArgNum = 5;
1962 HasRC = true;
1963 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00001964 }
1965
1966 llvm::APSInt Result;
1967
1968 // We can't check the value of a dependent argument.
1969 Expr *Arg = TheCall->getArg(ArgNum);
1970 if (Arg->isTypeDependent() || Arg->isValueDependent())
1971 return false;
1972
1973 // Check constant-ness first.
1974 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1975 return true;
1976
1977 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1978 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1979 // combined with ROUND_NO_EXC.
1980 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1981 Result == 8/*ROUND_NO_EXC*/ ||
1982 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1983 return false;
1984
1985 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1986 << Arg->getSourceRange();
1987}
1988
Craig Topperdf5beb22017-03-13 17:16:50 +00001989// Check if the gather/scatter scale is legal.
1990bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
1991 CallExpr *TheCall) {
1992 unsigned ArgNum = 0;
1993 switch (BuiltinID) {
1994 default:
1995 return false;
1996 case X86::BI__builtin_ia32_gatherpfdpd:
1997 case X86::BI__builtin_ia32_gatherpfdps:
1998 case X86::BI__builtin_ia32_gatherpfqpd:
1999 case X86::BI__builtin_ia32_gatherpfqps:
2000 case X86::BI__builtin_ia32_scatterpfdpd:
2001 case X86::BI__builtin_ia32_scatterpfdps:
2002 case X86::BI__builtin_ia32_scatterpfqpd:
2003 case X86::BI__builtin_ia32_scatterpfqps:
2004 ArgNum = 3;
2005 break;
2006 case X86::BI__builtin_ia32_gatherd_pd:
2007 case X86::BI__builtin_ia32_gatherd_pd256:
2008 case X86::BI__builtin_ia32_gatherq_pd:
2009 case X86::BI__builtin_ia32_gatherq_pd256:
2010 case X86::BI__builtin_ia32_gatherd_ps:
2011 case X86::BI__builtin_ia32_gatherd_ps256:
2012 case X86::BI__builtin_ia32_gatherq_ps:
2013 case X86::BI__builtin_ia32_gatherq_ps256:
2014 case X86::BI__builtin_ia32_gatherd_q:
2015 case X86::BI__builtin_ia32_gatherd_q256:
2016 case X86::BI__builtin_ia32_gatherq_q:
2017 case X86::BI__builtin_ia32_gatherq_q256:
2018 case X86::BI__builtin_ia32_gatherd_d:
2019 case X86::BI__builtin_ia32_gatherd_d256:
2020 case X86::BI__builtin_ia32_gatherq_d:
2021 case X86::BI__builtin_ia32_gatherq_d256:
2022 case X86::BI__builtin_ia32_gather3div2df:
2023 case X86::BI__builtin_ia32_gather3div2di:
2024 case X86::BI__builtin_ia32_gather3div4df:
2025 case X86::BI__builtin_ia32_gather3div4di:
2026 case X86::BI__builtin_ia32_gather3div4sf:
2027 case X86::BI__builtin_ia32_gather3div4si:
2028 case X86::BI__builtin_ia32_gather3div8sf:
2029 case X86::BI__builtin_ia32_gather3div8si:
2030 case X86::BI__builtin_ia32_gather3siv2df:
2031 case X86::BI__builtin_ia32_gather3siv2di:
2032 case X86::BI__builtin_ia32_gather3siv4df:
2033 case X86::BI__builtin_ia32_gather3siv4di:
2034 case X86::BI__builtin_ia32_gather3siv4sf:
2035 case X86::BI__builtin_ia32_gather3siv4si:
2036 case X86::BI__builtin_ia32_gather3siv8sf:
2037 case X86::BI__builtin_ia32_gather3siv8si:
2038 case X86::BI__builtin_ia32_gathersiv8df:
2039 case X86::BI__builtin_ia32_gathersiv16sf:
2040 case X86::BI__builtin_ia32_gatherdiv8df:
2041 case X86::BI__builtin_ia32_gatherdiv16sf:
2042 case X86::BI__builtin_ia32_gathersiv8di:
2043 case X86::BI__builtin_ia32_gathersiv16si:
2044 case X86::BI__builtin_ia32_gatherdiv8di:
2045 case X86::BI__builtin_ia32_gatherdiv16si:
2046 case X86::BI__builtin_ia32_scatterdiv2df:
2047 case X86::BI__builtin_ia32_scatterdiv2di:
2048 case X86::BI__builtin_ia32_scatterdiv4df:
2049 case X86::BI__builtin_ia32_scatterdiv4di:
2050 case X86::BI__builtin_ia32_scatterdiv4sf:
2051 case X86::BI__builtin_ia32_scatterdiv4si:
2052 case X86::BI__builtin_ia32_scatterdiv8sf:
2053 case X86::BI__builtin_ia32_scatterdiv8si:
2054 case X86::BI__builtin_ia32_scattersiv2df:
2055 case X86::BI__builtin_ia32_scattersiv2di:
2056 case X86::BI__builtin_ia32_scattersiv4df:
2057 case X86::BI__builtin_ia32_scattersiv4di:
2058 case X86::BI__builtin_ia32_scattersiv4sf:
2059 case X86::BI__builtin_ia32_scattersiv4si:
2060 case X86::BI__builtin_ia32_scattersiv8sf:
2061 case X86::BI__builtin_ia32_scattersiv8si:
2062 case X86::BI__builtin_ia32_scattersiv8df:
2063 case X86::BI__builtin_ia32_scattersiv16sf:
2064 case X86::BI__builtin_ia32_scatterdiv8df:
2065 case X86::BI__builtin_ia32_scatterdiv16sf:
2066 case X86::BI__builtin_ia32_scattersiv8di:
2067 case X86::BI__builtin_ia32_scattersiv16si:
2068 case X86::BI__builtin_ia32_scatterdiv8di:
2069 case X86::BI__builtin_ia32_scatterdiv16si:
2070 ArgNum = 4;
2071 break;
2072 }
2073
2074 llvm::APSInt Result;
2075
2076 // We can't check the value of a dependent argument.
2077 Expr *Arg = TheCall->getArg(ArgNum);
2078 if (Arg->isTypeDependent() || Arg->isValueDependent())
2079 return false;
2080
2081 // Check constant-ness first.
2082 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2083 return true;
2084
2085 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2086 return false;
2087
2088 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2089 << Arg->getSourceRange();
2090}
2091
Craig Topperf0ddc892016-09-23 04:48:27 +00002092bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2093 if (BuiltinID == X86::BI__builtin_cpu_supports)
2094 return SemaBuiltinCpuSupports(*this, TheCall);
2095
2096 if (BuiltinID == X86::BI__builtin_ms_va_start)
2097 return SemaBuiltinMSVAStart(TheCall);
2098
Craig Toppera7e253e2016-09-23 04:48:31 +00002099 // If the intrinsic has rounding or SAE make sure its valid.
2100 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2101 return true;
2102
Craig Topperdf5beb22017-03-13 17:16:50 +00002103 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2104 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2105 return true;
2106
Craig Topperf0ddc892016-09-23 04:48:27 +00002107 // For intrinsics which take an immediate value as part of the instruction,
2108 // range check them here.
2109 int i = 0, l = 0, u = 0;
2110 switch (BuiltinID) {
2111 default:
2112 return false;
Richard Trieucc3949d2016-02-18 22:34:54 +00002113 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00002114 i = 1; l = 0; u = 3;
2115 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002116 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00002117 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2118 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2119 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2120 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002121 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002122 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002123 case X86::BI__builtin_ia32_vpermil2pd:
2124 case X86::BI__builtin_ia32_vpermil2pd256:
2125 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002126 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002127 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002128 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002129 case X86::BI__builtin_ia32_cmpb128_mask:
2130 case X86::BI__builtin_ia32_cmpw128_mask:
2131 case X86::BI__builtin_ia32_cmpd128_mask:
2132 case X86::BI__builtin_ia32_cmpq128_mask:
2133 case X86::BI__builtin_ia32_cmpb256_mask:
2134 case X86::BI__builtin_ia32_cmpw256_mask:
2135 case X86::BI__builtin_ia32_cmpd256_mask:
2136 case X86::BI__builtin_ia32_cmpq256_mask:
2137 case X86::BI__builtin_ia32_cmpb512_mask:
2138 case X86::BI__builtin_ia32_cmpw512_mask:
2139 case X86::BI__builtin_ia32_cmpd512_mask:
2140 case X86::BI__builtin_ia32_cmpq512_mask:
2141 case X86::BI__builtin_ia32_ucmpb128_mask:
2142 case X86::BI__builtin_ia32_ucmpw128_mask:
2143 case X86::BI__builtin_ia32_ucmpd128_mask:
2144 case X86::BI__builtin_ia32_ucmpq128_mask:
2145 case X86::BI__builtin_ia32_ucmpb256_mask:
2146 case X86::BI__builtin_ia32_ucmpw256_mask:
2147 case X86::BI__builtin_ia32_ucmpd256_mask:
2148 case X86::BI__builtin_ia32_ucmpq256_mask:
2149 case X86::BI__builtin_ia32_ucmpb512_mask:
2150 case X86::BI__builtin_ia32_ucmpw512_mask:
2151 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002152 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002153 case X86::BI__builtin_ia32_vpcomub:
2154 case X86::BI__builtin_ia32_vpcomuw:
2155 case X86::BI__builtin_ia32_vpcomud:
2156 case X86::BI__builtin_ia32_vpcomuq:
2157 case X86::BI__builtin_ia32_vpcomb:
2158 case X86::BI__builtin_ia32_vpcomw:
2159 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002160 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00002161 i = 2; l = 0; u = 7;
2162 break;
2163 case X86::BI__builtin_ia32_roundps:
2164 case X86::BI__builtin_ia32_roundpd:
2165 case X86::BI__builtin_ia32_roundps256:
2166 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002167 i = 1; l = 0; u = 15;
2168 break;
2169 case X86::BI__builtin_ia32_roundss:
2170 case X86::BI__builtin_ia32_roundsd:
2171 case X86::BI__builtin_ia32_rangepd128_mask:
2172 case X86::BI__builtin_ia32_rangepd256_mask:
2173 case X86::BI__builtin_ia32_rangepd512_mask:
2174 case X86::BI__builtin_ia32_rangeps128_mask:
2175 case X86::BI__builtin_ia32_rangeps256_mask:
2176 case X86::BI__builtin_ia32_rangeps512_mask:
2177 case X86::BI__builtin_ia32_getmantsd_round_mask:
2178 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002179 i = 2; l = 0; u = 15;
2180 break;
2181 case X86::BI__builtin_ia32_cmpps:
2182 case X86::BI__builtin_ia32_cmpss:
2183 case X86::BI__builtin_ia32_cmppd:
2184 case X86::BI__builtin_ia32_cmpsd:
2185 case X86::BI__builtin_ia32_cmpps256:
2186 case X86::BI__builtin_ia32_cmppd256:
2187 case X86::BI__builtin_ia32_cmpps128_mask:
2188 case X86::BI__builtin_ia32_cmppd128_mask:
2189 case X86::BI__builtin_ia32_cmpps256_mask:
2190 case X86::BI__builtin_ia32_cmppd256_mask:
2191 case X86::BI__builtin_ia32_cmpps512_mask:
2192 case X86::BI__builtin_ia32_cmppd512_mask:
2193 case X86::BI__builtin_ia32_cmpsd_mask:
2194 case X86::BI__builtin_ia32_cmpss_mask:
2195 i = 2; l = 0; u = 31;
2196 break;
2197 case X86::BI__builtin_ia32_xabort:
2198 i = 0; l = -128; u = 255;
2199 break;
2200 case X86::BI__builtin_ia32_pshufw:
2201 case X86::BI__builtin_ia32_aeskeygenassist128:
2202 i = 1; l = -128; u = 255;
2203 break;
2204 case X86::BI__builtin_ia32_vcvtps2ph:
2205 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper39c87102016-05-18 03:18:12 +00002206 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2207 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2208 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2209 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2210 case X86::BI__builtin_ia32_rndscaleps_mask:
2211 case X86::BI__builtin_ia32_rndscalepd_mask:
2212 case X86::BI__builtin_ia32_reducepd128_mask:
2213 case X86::BI__builtin_ia32_reducepd256_mask:
2214 case X86::BI__builtin_ia32_reducepd512_mask:
2215 case X86::BI__builtin_ia32_reduceps128_mask:
2216 case X86::BI__builtin_ia32_reduceps256_mask:
2217 case X86::BI__builtin_ia32_reduceps512_mask:
2218 case X86::BI__builtin_ia32_prold512_mask:
2219 case X86::BI__builtin_ia32_prolq512_mask:
2220 case X86::BI__builtin_ia32_prold128_mask:
2221 case X86::BI__builtin_ia32_prold256_mask:
2222 case X86::BI__builtin_ia32_prolq128_mask:
2223 case X86::BI__builtin_ia32_prolq256_mask:
2224 case X86::BI__builtin_ia32_prord128_mask:
2225 case X86::BI__builtin_ia32_prord256_mask:
2226 case X86::BI__builtin_ia32_prorq128_mask:
2227 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002228 case X86::BI__builtin_ia32_fpclasspd128_mask:
2229 case X86::BI__builtin_ia32_fpclasspd256_mask:
2230 case X86::BI__builtin_ia32_fpclassps128_mask:
2231 case X86::BI__builtin_ia32_fpclassps256_mask:
2232 case X86::BI__builtin_ia32_fpclassps512_mask:
2233 case X86::BI__builtin_ia32_fpclasspd512_mask:
2234 case X86::BI__builtin_ia32_fpclasssd_mask:
2235 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002236 i = 1; l = 0; u = 255;
2237 break;
2238 case X86::BI__builtin_ia32_palignr:
2239 case X86::BI__builtin_ia32_insertps128:
2240 case X86::BI__builtin_ia32_dpps:
2241 case X86::BI__builtin_ia32_dppd:
2242 case X86::BI__builtin_ia32_dpps256:
2243 case X86::BI__builtin_ia32_mpsadbw128:
2244 case X86::BI__builtin_ia32_mpsadbw256:
2245 case X86::BI__builtin_ia32_pcmpistrm128:
2246 case X86::BI__builtin_ia32_pcmpistri128:
2247 case X86::BI__builtin_ia32_pcmpistria128:
2248 case X86::BI__builtin_ia32_pcmpistric128:
2249 case X86::BI__builtin_ia32_pcmpistrio128:
2250 case X86::BI__builtin_ia32_pcmpistris128:
2251 case X86::BI__builtin_ia32_pcmpistriz128:
2252 case X86::BI__builtin_ia32_pclmulqdq128:
2253 case X86::BI__builtin_ia32_vperm2f128_pd256:
2254 case X86::BI__builtin_ia32_vperm2f128_ps256:
2255 case X86::BI__builtin_ia32_vperm2f128_si256:
2256 case X86::BI__builtin_ia32_permti256:
2257 i = 2; l = -128; u = 255;
2258 break;
2259 case X86::BI__builtin_ia32_palignr128:
2260 case X86::BI__builtin_ia32_palignr256:
Craig Topper39c87102016-05-18 03:18:12 +00002261 case X86::BI__builtin_ia32_palignr512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002262 case X86::BI__builtin_ia32_vcomisd:
2263 case X86::BI__builtin_ia32_vcomiss:
2264 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2265 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2266 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2267 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002268 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2269 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2270 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2271 i = 2; l = 0; u = 255;
2272 break;
2273 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2274 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2275 case X86::BI__builtin_ia32_fixupimmps512_mask:
2276 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2277 case X86::BI__builtin_ia32_fixupimmsd_mask:
2278 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2279 case X86::BI__builtin_ia32_fixupimmss_mask:
2280 case X86::BI__builtin_ia32_fixupimmss_maskz:
2281 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2282 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2283 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2284 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2285 case X86::BI__builtin_ia32_fixupimmps128_mask:
2286 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2287 case X86::BI__builtin_ia32_fixupimmps256_mask:
2288 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2289 case X86::BI__builtin_ia32_pternlogd512_mask:
2290 case X86::BI__builtin_ia32_pternlogd512_maskz:
2291 case X86::BI__builtin_ia32_pternlogq512_mask:
2292 case X86::BI__builtin_ia32_pternlogq512_maskz:
2293 case X86::BI__builtin_ia32_pternlogd128_mask:
2294 case X86::BI__builtin_ia32_pternlogd128_maskz:
2295 case X86::BI__builtin_ia32_pternlogd256_mask:
2296 case X86::BI__builtin_ia32_pternlogd256_maskz:
2297 case X86::BI__builtin_ia32_pternlogq128_mask:
2298 case X86::BI__builtin_ia32_pternlogq128_maskz:
2299 case X86::BI__builtin_ia32_pternlogq256_mask:
2300 case X86::BI__builtin_ia32_pternlogq256_maskz:
2301 i = 3; l = 0; u = 255;
2302 break;
Craig Topper9625db02017-03-12 22:19:10 +00002303 case X86::BI__builtin_ia32_gatherpfdpd:
2304 case X86::BI__builtin_ia32_gatherpfdps:
2305 case X86::BI__builtin_ia32_gatherpfqpd:
2306 case X86::BI__builtin_ia32_gatherpfqps:
2307 case X86::BI__builtin_ia32_scatterpfdpd:
2308 case X86::BI__builtin_ia32_scatterpfdps:
2309 case X86::BI__builtin_ia32_scatterpfqpd:
2310 case X86::BI__builtin_ia32_scatterpfqps:
2311 i = 4; l = 1; u = 2;
2312 break;
Craig Topper39c87102016-05-18 03:18:12 +00002313 case X86::BI__builtin_ia32_pcmpestrm128:
2314 case X86::BI__builtin_ia32_pcmpestri128:
2315 case X86::BI__builtin_ia32_pcmpestria128:
2316 case X86::BI__builtin_ia32_pcmpestric128:
2317 case X86::BI__builtin_ia32_pcmpestrio128:
2318 case X86::BI__builtin_ia32_pcmpestris128:
2319 case X86::BI__builtin_ia32_pcmpestriz128:
2320 i = 4; l = -128; u = 255;
2321 break;
2322 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2323 case X86::BI__builtin_ia32_rndscaless_round_mask:
2324 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002325 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002326 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002327 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002328}
2329
Richard Smith55ce3522012-06-25 20:30:08 +00002330/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2331/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2332/// Returns true when the format fits the function and the FormatStringInfo has
2333/// been populated.
2334bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2335 FormatStringInfo *FSI) {
2336 FSI->HasVAListArg = Format->getFirstArg() == 0;
2337 FSI->FormatIdx = Format->getFormatIdx() - 1;
2338 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002339
Richard Smith55ce3522012-06-25 20:30:08 +00002340 // The way the format attribute works in GCC, the implicit this argument
2341 // of member functions is counted. However, it doesn't appear in our own
2342 // lists, so decrement format_idx in that case.
2343 if (IsCXXMember) {
2344 if(FSI->FormatIdx == 0)
2345 return false;
2346 --FSI->FormatIdx;
2347 if (FSI->FirstDataArg != 0)
2348 --FSI->FirstDataArg;
2349 }
2350 return true;
2351}
Mike Stump11289f42009-09-09 15:08:12 +00002352
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002353/// Checks if a the given expression evaluates to null.
2354///
2355/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002356static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002357 // If the expression has non-null type, it doesn't evaluate to null.
2358 if (auto nullability
2359 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2360 if (*nullability == NullabilityKind::NonNull)
2361 return false;
2362 }
2363
Ted Kremeneka146db32014-01-17 06:24:47 +00002364 // As a special case, transparent unions initialized with zero are
2365 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002366 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002367 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2368 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002369 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002370 if (const InitListExpr *ILE =
2371 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002372 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002373 }
2374
2375 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002376 return (!Expr->isValueDependent() &&
2377 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2378 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002379}
2380
2381static void CheckNonNullArgument(Sema &S,
2382 const Expr *ArgExpr,
2383 SourceLocation CallSiteLoc) {
2384 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002385 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2386 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002387}
2388
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002389bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2390 FormatStringInfo FSI;
2391 if ((GetFormatStringType(Format) == FST_NSString) &&
2392 getFormatStringInfo(Format, false, &FSI)) {
2393 Idx = FSI.FormatIdx;
2394 return true;
2395 }
2396 return false;
2397}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002398/// \brief Diagnose use of %s directive in an NSString which is being passed
2399/// as formatting string to formatting method.
2400static void
2401DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2402 const NamedDecl *FDecl,
2403 Expr **Args,
2404 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002405 unsigned Idx = 0;
2406 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002407 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2408 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002409 Idx = 2;
2410 Format = true;
2411 }
2412 else
2413 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2414 if (S.GetFormatNSStringIdx(I, Idx)) {
2415 Format = true;
2416 break;
2417 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002418 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002419 if (!Format || NumArgs <= Idx)
2420 return;
2421 const Expr *FormatExpr = Args[Idx];
2422 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2423 FormatExpr = CSCE->getSubExpr();
2424 const StringLiteral *FormatString;
2425 if (const ObjCStringLiteral *OSL =
2426 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2427 FormatString = OSL->getString();
2428 else
2429 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2430 if (!FormatString)
2431 return;
2432 if (S.FormatStringHasSArg(FormatString)) {
2433 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2434 << "%s" << 1 << 1;
2435 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2436 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002437 }
2438}
2439
Douglas Gregorb4866e82015-06-19 18:13:19 +00002440/// Determine whether the given type has a non-null nullability annotation.
2441static bool isNonNullType(ASTContext &ctx, QualType type) {
2442 if (auto nullability = type->getNullability(ctx))
2443 return *nullability == NullabilityKind::NonNull;
2444
2445 return false;
2446}
2447
Ted Kremenek2bc73332014-01-17 06:24:43 +00002448static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002449 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002450 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002451 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002452 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002453 assert((FDecl || Proto) && "Need a function declaration or prototype");
2454
Ted Kremenek9aedc152014-01-17 06:24:56 +00002455 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002456 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002457 if (FDecl) {
2458 // Handle the nonnull attribute on the function/method declaration itself.
2459 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2460 if (!NonNull->args_size()) {
2461 // Easy case: all pointer arguments are nonnull.
2462 for (const auto *Arg : Args)
2463 if (S.isValidPointerAttrType(Arg->getType()))
2464 CheckNonNullArgument(S, Arg, CallSiteLoc);
2465 return;
2466 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002467
Douglas Gregorb4866e82015-06-19 18:13:19 +00002468 for (unsigned Val : NonNull->args()) {
2469 if (Val >= Args.size())
2470 continue;
2471 if (NonNullArgs.empty())
2472 NonNullArgs.resize(Args.size());
2473 NonNullArgs.set(Val);
2474 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002475 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002476 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002477
Douglas Gregorb4866e82015-06-19 18:13:19 +00002478 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2479 // Handle the nonnull attribute on the parameters of the
2480 // function/method.
2481 ArrayRef<ParmVarDecl*> parms;
2482 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2483 parms = FD->parameters();
2484 else
2485 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2486
2487 unsigned ParamIndex = 0;
2488 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2489 I != E; ++I, ++ParamIndex) {
2490 const ParmVarDecl *PVD = *I;
2491 if (PVD->hasAttr<NonNullAttr>() ||
2492 isNonNullType(S.Context, PVD->getType())) {
2493 if (NonNullArgs.empty())
2494 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002495
Douglas Gregorb4866e82015-06-19 18:13:19 +00002496 NonNullArgs.set(ParamIndex);
2497 }
2498 }
2499 } else {
2500 // If we have a non-function, non-method declaration but no
2501 // function prototype, try to dig out the function prototype.
2502 if (!Proto) {
2503 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2504 QualType type = VD->getType().getNonReferenceType();
2505 if (auto pointerType = type->getAs<PointerType>())
2506 type = pointerType->getPointeeType();
2507 else if (auto blockType = type->getAs<BlockPointerType>())
2508 type = blockType->getPointeeType();
2509 // FIXME: data member pointers?
2510
2511 // Dig out the function prototype, if there is one.
2512 Proto = type->getAs<FunctionProtoType>();
2513 }
2514 }
2515
2516 // Fill in non-null argument information from the nullability
2517 // information on the parameter types (if we have them).
2518 if (Proto) {
2519 unsigned Index = 0;
2520 for (auto paramType : Proto->getParamTypes()) {
2521 if (isNonNullType(S.Context, paramType)) {
2522 if (NonNullArgs.empty())
2523 NonNullArgs.resize(Args.size());
2524
2525 NonNullArgs.set(Index);
2526 }
2527
2528 ++Index;
2529 }
2530 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002531 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002532
Douglas Gregorb4866e82015-06-19 18:13:19 +00002533 // Check for non-null arguments.
2534 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2535 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002536 if (NonNullArgs[ArgIndex])
2537 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002538 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002539}
2540
Richard Smith55ce3522012-06-25 20:30:08 +00002541/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00002542/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2543/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002544void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00002545 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2546 bool IsMemberFunction, SourceLocation Loc,
2547 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002548 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002549 if (CurContext->isDependentContext())
2550 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002551
Ted Kremenekb8176da2010-09-09 04:33:05 +00002552 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002553 llvm::SmallBitVector CheckedVarArgs;
2554 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002555 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002556 // Only create vector if there are format attributes.
2557 CheckedVarArgs.resize(Args.size());
2558
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002559 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002560 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002561 }
Richard Smithd7293d72013-08-05 18:49:43 +00002562 }
Richard Smith55ce3522012-06-25 20:30:08 +00002563
2564 // Refuse POD arguments that weren't caught by the format string
2565 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00002566 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2567 if (CallType != VariadicDoesNotApply &&
2568 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002569 unsigned NumParams = Proto ? Proto->getNumParams()
2570 : FDecl && isa<FunctionDecl>(FDecl)
2571 ? cast<FunctionDecl>(FDecl)->getNumParams()
2572 : FDecl && isa<ObjCMethodDecl>(FDecl)
2573 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2574 : 0;
2575
Alp Toker9cacbab2014-01-20 20:26:09 +00002576 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002577 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002578 if (const Expr *Arg = Args[ArgIdx]) {
2579 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2580 checkVariadicArgument(Arg, CallType);
2581 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002582 }
Richard Smithd7293d72013-08-05 18:49:43 +00002583 }
Mike Stump11289f42009-09-09 15:08:12 +00002584
Douglas Gregorb4866e82015-06-19 18:13:19 +00002585 if (FDecl || Proto) {
2586 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002587
Richard Trieu41bc0992013-06-22 00:20:41 +00002588 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002589 if (FDecl) {
2590 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2591 CheckArgumentWithTypeTag(I, Args.data());
2592 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002593 }
George Burgess IVce6284b2017-01-28 02:19:40 +00002594
2595 if (FD)
2596 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00002597}
2598
2599/// CheckConstructorCall - Check a constructor call for correctness and safety
2600/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002601void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2602 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002603 const FunctionProtoType *Proto,
2604 SourceLocation Loc) {
2605 VariadicCallType CallType =
2606 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00002607 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2608 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002609}
2610
2611/// CheckFunctionCall - Check a direct function call for various correctness
2612/// and safety properties not strictly enforced by the C type system.
2613bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2614 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002615 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2616 isa<CXXMethodDecl>(FDecl);
2617 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2618 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002619 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2620 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002621 Expr** Args = TheCall->getArgs();
2622 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00002623
2624 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00002625 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002626 // If this is a call to a member operator, hide the first argument
2627 // from checkCall.
2628 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00002629 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00002630 ++Args;
2631 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00002632 } else if (IsMemberFunction)
2633 ImplicitThis =
2634 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2635
2636 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002637 IsMemberFunction, TheCall->getRParenLoc(),
2638 TheCall->getCallee()->getSourceRange(), CallType);
2639
2640 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2641 // None of the checks below are needed for functions that don't have
2642 // simple names (e.g., C++ conversion functions).
2643 if (!FnInfo)
2644 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002645
Richard Trieua7f30b12016-12-06 01:42:28 +00002646 CheckAbsoluteValueFunction(TheCall, FDecl);
2647 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00002648
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002649 if (getLangOpts().ObjC1)
2650 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002651
Anna Zaks22122702012-01-17 00:37:07 +00002652 unsigned CMId = FDecl->getMemoryFunctionKind();
2653 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002654 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002655
Anna Zaks201d4892012-01-13 21:52:01 +00002656 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002657 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002658 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002659 else if (CMId == Builtin::BIstrncat)
2660 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002661 else
Anna Zaks22122702012-01-17 00:37:07 +00002662 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002663
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002664 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002665}
2666
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002667bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002668 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002669 VariadicCallType CallType =
2670 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002671
George Burgess IVce6284b2017-01-28 02:19:40 +00002672 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2673 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002674 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002675
2676 return false;
2677}
2678
Richard Trieu664c4c62013-06-20 21:03:13 +00002679bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2680 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002681 QualType Ty;
2682 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002683 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002684 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002685 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002686 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002687 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002688
Douglas Gregorb4866e82015-06-19 18:13:19 +00002689 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2690 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002691 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002692
Richard Trieu664c4c62013-06-20 21:03:13 +00002693 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002694 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002695 CallType = VariadicDoesNotApply;
2696 } else if (Ty->isBlockPointerType()) {
2697 CallType = VariadicBlock;
2698 } else { // Ty->isFunctionPointerType()
2699 CallType = VariadicFunction;
2700 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002701
George Burgess IVce6284b2017-01-28 02:19:40 +00002702 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002703 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2704 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002705 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002706
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002707 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002708}
2709
Richard Trieu41bc0992013-06-22 00:20:41 +00002710/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2711/// such as function pointers returned from functions.
2712bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002713 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002714 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00002715 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002716 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002717 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002718 TheCall->getCallee()->getSourceRange(), CallType);
2719
2720 return false;
2721}
2722
Tim Northovere94a34c2014-03-11 10:49:14 +00002723static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002724 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002725 return false;
2726
JF Bastiendda2cb12016-04-18 18:01:49 +00002727 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002728 switch (Op) {
2729 case AtomicExpr::AO__c11_atomic_init:
2730 llvm_unreachable("There is no ordering argument for an init");
2731
2732 case AtomicExpr::AO__c11_atomic_load:
2733 case AtomicExpr::AO__atomic_load_n:
2734 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002735 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2736 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002737
2738 case AtomicExpr::AO__c11_atomic_store:
2739 case AtomicExpr::AO__atomic_store:
2740 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002741 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2742 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2743 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002744
2745 default:
2746 return true;
2747 }
2748}
2749
Richard Smithfeea8832012-04-12 05:08:17 +00002750ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2751 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002752 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2753 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002754
Richard Smithfeea8832012-04-12 05:08:17 +00002755 // All these operations take one of the following forms:
2756 enum {
2757 // C __c11_atomic_init(A *, C)
2758 Init,
2759 // C __c11_atomic_load(A *, int)
2760 Load,
2761 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002762 LoadCopy,
2763 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002764 Copy,
2765 // C __c11_atomic_add(A *, M, int)
2766 Arithmetic,
2767 // C __atomic_exchange_n(A *, CP, int)
2768 Xchg,
2769 // void __atomic_exchange(A *, C *, CP, int)
2770 GNUXchg,
2771 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2772 C11CmpXchg,
2773 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2774 GNUCmpXchg
2775 } Form = Init;
Eric Fiselier8d662442016-03-30 23:39:56 +00002776 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2777 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002778 // where:
2779 // C is an appropriate type,
2780 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2781 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2782 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2783 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002784
Gabor Horvath98bd0982015-03-16 09:59:54 +00002785 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2786 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2787 AtomicExpr::AO__atomic_load,
2788 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00002789 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2790 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2791 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2792 Op == AtomicExpr::AO__atomic_store_n ||
2793 Op == AtomicExpr::AO__atomic_exchange_n ||
2794 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2795 bool IsAddSub = false;
2796
2797 switch (Op) {
2798 case AtomicExpr::AO__c11_atomic_init:
2799 Form = Init;
2800 break;
2801
2802 case AtomicExpr::AO__c11_atomic_load:
2803 case AtomicExpr::AO__atomic_load_n:
2804 Form = Load;
2805 break;
2806
Richard Smithfeea8832012-04-12 05:08:17 +00002807 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002808 Form = LoadCopy;
2809 break;
2810
2811 case AtomicExpr::AO__c11_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002812 case AtomicExpr::AO__atomic_store:
2813 case AtomicExpr::AO__atomic_store_n:
2814 Form = Copy;
2815 break;
2816
2817 case AtomicExpr::AO__c11_atomic_fetch_add:
2818 case AtomicExpr::AO__c11_atomic_fetch_sub:
2819 case AtomicExpr::AO__atomic_fetch_add:
2820 case AtomicExpr::AO__atomic_fetch_sub:
2821 case AtomicExpr::AO__atomic_add_fetch:
2822 case AtomicExpr::AO__atomic_sub_fetch:
2823 IsAddSub = true;
2824 // Fall through.
2825 case AtomicExpr::AO__c11_atomic_fetch_and:
2826 case AtomicExpr::AO__c11_atomic_fetch_or:
2827 case AtomicExpr::AO__c11_atomic_fetch_xor:
2828 case AtomicExpr::AO__atomic_fetch_and:
2829 case AtomicExpr::AO__atomic_fetch_or:
2830 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00002831 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00002832 case AtomicExpr::AO__atomic_and_fetch:
2833 case AtomicExpr::AO__atomic_or_fetch:
2834 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00002835 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00002836 Form = Arithmetic;
2837 break;
2838
2839 case AtomicExpr::AO__c11_atomic_exchange:
2840 case AtomicExpr::AO__atomic_exchange_n:
2841 Form = Xchg;
2842 break;
2843
2844 case AtomicExpr::AO__atomic_exchange:
2845 Form = GNUXchg;
2846 break;
2847
2848 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2849 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2850 Form = C11CmpXchg;
2851 break;
2852
2853 case AtomicExpr::AO__atomic_compare_exchange:
2854 case AtomicExpr::AO__atomic_compare_exchange_n:
2855 Form = GNUCmpXchg;
2856 break;
2857 }
2858
2859 // Check we have the right number of arguments.
2860 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002861 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002862 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002863 << TheCall->getCallee()->getSourceRange();
2864 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00002865 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2866 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002867 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002868 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002869 << TheCall->getCallee()->getSourceRange();
2870 return ExprError();
2871 }
2872
Richard Smithfeea8832012-04-12 05:08:17 +00002873 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002874 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00002875 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2876 if (ConvertedPtr.isInvalid())
2877 return ExprError();
2878
2879 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002880 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2881 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00002882 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002883 << Ptr->getType() << Ptr->getSourceRange();
2884 return ExprError();
2885 }
2886
Richard Smithfeea8832012-04-12 05:08:17 +00002887 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2888 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2889 QualType ValType = AtomTy; // 'C'
2890 if (IsC11) {
2891 if (!AtomTy->isAtomicType()) {
2892 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2893 << Ptr->getType() << Ptr->getSourceRange();
2894 return ExprError();
2895 }
Richard Smithe00921a2012-09-15 06:09:58 +00002896 if (AtomTy.isConstQualified()) {
2897 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2898 << Ptr->getType() << Ptr->getSourceRange();
2899 return ExprError();
2900 }
Richard Smithfeea8832012-04-12 05:08:17 +00002901 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00002902 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002903 if (ValType.isConstQualified()) {
2904 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2905 << Ptr->getType() << Ptr->getSourceRange();
2906 return ExprError();
2907 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002908 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002909
Richard Smithfeea8832012-04-12 05:08:17 +00002910 // For an arithmetic operation, the implied arithmetic must be well-formed.
2911 if (Form == Arithmetic) {
2912 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2913 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2914 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2915 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2916 return ExprError();
2917 }
2918 if (!IsAddSub && !ValType->isIntegerType()) {
2919 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2920 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2921 return ExprError();
2922 }
David Majnemere85cff82015-01-28 05:48:06 +00002923 if (IsC11 && ValType->isPointerType() &&
2924 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2925 diag::err_incomplete_type)) {
2926 return ExprError();
2927 }
Richard Smithfeea8832012-04-12 05:08:17 +00002928 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2929 // For __atomic_*_n operations, the value type must be a scalar integral or
2930 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002931 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00002932 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2933 return ExprError();
2934 }
2935
Eli Friedmanaa769812013-09-11 03:49:34 +00002936 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2937 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00002938 // For GNU atomics, require a trivially-copyable type. This is not part of
2939 // the GNU atomics specification, but we enforce it for sanity.
2940 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002941 << Ptr->getType() << Ptr->getSourceRange();
2942 return ExprError();
2943 }
2944
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002945 switch (ValType.getObjCLifetime()) {
2946 case Qualifiers::OCL_None:
2947 case Qualifiers::OCL_ExplicitNone:
2948 // okay
2949 break;
2950
2951 case Qualifiers::OCL_Weak:
2952 case Qualifiers::OCL_Strong:
2953 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002954 // FIXME: Can this happen? By this point, ValType should be known
2955 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002956 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2957 << ValType << Ptr->getSourceRange();
2958 return ExprError();
2959 }
2960
David Majnemerc6eb6502015-06-03 00:26:35 +00002961 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2962 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00002963 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00002964 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00002965 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002966 QualType ResultType = ValType;
Eric Fiselier8d662442016-03-30 23:39:56 +00002967 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002968 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002969 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002970 ResultType = Context.BoolTy;
2971
Richard Smithfeea8832012-04-12 05:08:17 +00002972 // The type of a parameter passed 'by value'. In the GNU atomics, such
2973 // arguments are actually passed as pointers.
2974 QualType ByValType = ValType; // 'CP'
2975 if (!IsC11 && !IsN)
2976 ByValType = Ptr->getType();
2977
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002978 // The first argument --- the pointer --- has a fixed type; we
2979 // deduce the types of the rest of the arguments accordingly. Walk
2980 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002981 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002982 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002983 if (i < NumVals[Form] + 1) {
2984 switch (i) {
2985 case 1:
2986 // The second argument is the non-atomic operand. For arithmetic, this
2987 // is always passed by value, and for a compare_exchange it is always
2988 // passed by address. For the rest, GNU uses by-address and C11 uses
2989 // by-value.
2990 assert(Form != Load);
2991 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2992 Ty = ValType;
2993 else if (Form == Copy || Form == Xchg)
2994 Ty = ByValType;
2995 else if (Form == Arithmetic)
2996 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002997 else {
2998 Expr *ValArg = TheCall->getArg(i);
Alex Lorenz67522152016-11-23 16:57:03 +00002999 // Treat this argument as _Nonnull as we want to show a warning if
3000 // NULL is passed into it.
3001 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003002 unsigned AS = 0;
3003 // Keep address space of non-atomic pointer type.
3004 if (const PointerType *PtrTy =
3005 ValArg->getType()->getAs<PointerType>()) {
3006 AS = PtrTy->getPointeeType().getAddressSpace();
3007 }
3008 Ty = Context.getPointerType(
3009 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3010 }
Richard Smithfeea8832012-04-12 05:08:17 +00003011 break;
3012 case 2:
3013 // The third argument to compare_exchange / GNU exchange is a
3014 // (pointer to a) desired value.
3015 Ty = ByValType;
3016 break;
3017 case 3:
3018 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3019 Ty = Context.BoolTy;
3020 break;
3021 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003022 } else {
3023 // The order(s) are always converted to int.
3024 Ty = Context.IntTy;
3025 }
Richard Smithfeea8832012-04-12 05:08:17 +00003026
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003027 InitializedEntity Entity =
3028 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00003029 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003030 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3031 if (Arg.isInvalid())
3032 return true;
3033 TheCall->setArg(i, Arg.get());
3034 }
3035
Richard Smithfeea8832012-04-12 05:08:17 +00003036 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003037 SmallVector<Expr*, 5> SubExprs;
3038 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00003039 switch (Form) {
3040 case Init:
3041 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00003042 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003043 break;
3044 case Load:
3045 SubExprs.push_back(TheCall->getArg(1)); // Order
3046 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00003047 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00003048 case Copy:
3049 case Arithmetic:
3050 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003051 SubExprs.push_back(TheCall->getArg(2)); // Order
3052 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003053 break;
3054 case GNUXchg:
3055 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3056 SubExprs.push_back(TheCall->getArg(3)); // Order
3057 SubExprs.push_back(TheCall->getArg(1)); // Val1
3058 SubExprs.push_back(TheCall->getArg(2)); // Val2
3059 break;
3060 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003061 SubExprs.push_back(TheCall->getArg(3)); // Order
3062 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003063 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00003064 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00003065 break;
3066 case GNUCmpXchg:
3067 SubExprs.push_back(TheCall->getArg(4)); // Order
3068 SubExprs.push_back(TheCall->getArg(1)); // Val1
3069 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3070 SubExprs.push_back(TheCall->getArg(2)); // Val2
3071 SubExprs.push_back(TheCall->getArg(3)); // Weak
3072 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003073 }
Tim Northovere94a34c2014-03-11 10:49:14 +00003074
3075 if (SubExprs.size() >= 2 && Form != Init) {
3076 llvm::APSInt Result(32);
3077 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3078 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00003079 Diag(SubExprs[1]->getLocStart(),
3080 diag::warn_atomic_op_has_invalid_memory_order)
3081 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00003082 }
3083
Fariborz Jahanian615de762013-05-28 17:37:39 +00003084 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3085 SubExprs, ResultType, Op,
3086 TheCall->getRParenLoc());
3087
3088 if ((Op == AtomicExpr::AO__c11_atomic_load ||
3089 (Op == AtomicExpr::AO__c11_atomic_store)) &&
3090 Context.AtomicUsesUnsupportedLibcall(AE))
3091 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
3092 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003093
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003094 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003095}
3096
John McCall29ad95b2011-08-27 01:09:30 +00003097/// checkBuiltinArgument - Given a call to a builtin function, perform
3098/// normal type-checking on the given argument, updating the call in
3099/// place. This is useful when a builtin function requires custom
3100/// type-checking for some of its arguments but not necessarily all of
3101/// them.
3102///
3103/// Returns true on error.
3104static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3105 FunctionDecl *Fn = E->getDirectCallee();
3106 assert(Fn && "builtin call without direct callee!");
3107
3108 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3109 InitializedEntity Entity =
3110 InitializedEntity::InitializeParameter(S.Context, Param);
3111
3112 ExprResult Arg = E->getArg(0);
3113 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3114 if (Arg.isInvalid())
3115 return true;
3116
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003117 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003118 return false;
3119}
3120
Chris Lattnerdc046542009-05-08 06:58:22 +00003121/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3122/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3123/// type of its first argument. The main ActOnCallExpr routines have already
3124/// promoted the types of arguments because all of these calls are prototyped as
3125/// void(...).
3126///
3127/// This function goes through and does final semantic checking for these
3128/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003129ExprResult
3130Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003131 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003132 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3133 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3134
3135 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003136 if (TheCall->getNumArgs() < 1) {
3137 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3138 << 0 << 1 << TheCall->getNumArgs()
3139 << TheCall->getCallee()->getSourceRange();
3140 return ExprError();
3141 }
Mike Stump11289f42009-09-09 15:08:12 +00003142
Chris Lattnerdc046542009-05-08 06:58:22 +00003143 // Inspect the first argument of the atomic builtin. This should always be
3144 // a pointer type, whose element is an integral scalar or pointer type.
3145 // Because it is a pointer type, we don't have to worry about any implicit
3146 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003147 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003148 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003149 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3150 if (FirstArgResult.isInvalid())
3151 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003152 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003153 TheCall->setArg(0, FirstArg);
3154
John McCall31168b02011-06-15 23:02:42 +00003155 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3156 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003157 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3158 << FirstArg->getType() << FirstArg->getSourceRange();
3159 return ExprError();
3160 }
Mike Stump11289f42009-09-09 15:08:12 +00003161
John McCall31168b02011-06-15 23:02:42 +00003162 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003163 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003164 !ValType->isBlockPointerType()) {
3165 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3166 << FirstArg->getType() << FirstArg->getSourceRange();
3167 return ExprError();
3168 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003169
John McCall31168b02011-06-15 23:02:42 +00003170 switch (ValType.getObjCLifetime()) {
3171 case Qualifiers::OCL_None:
3172 case Qualifiers::OCL_ExplicitNone:
3173 // okay
3174 break;
3175
3176 case Qualifiers::OCL_Weak:
3177 case Qualifiers::OCL_Strong:
3178 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003179 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003180 << ValType << FirstArg->getSourceRange();
3181 return ExprError();
3182 }
3183
John McCallb50451a2011-10-05 07:41:44 +00003184 // Strip any qualifiers off ValType.
3185 ValType = ValType.getUnqualifiedType();
3186
Chandler Carruth3973af72010-07-18 20:54:12 +00003187 // The majority of builtins return a value, but a few have special return
3188 // types, so allow them to override appropriately below.
3189 QualType ResultType = ValType;
3190
Chris Lattnerdc046542009-05-08 06:58:22 +00003191 // We need to figure out which concrete builtin this maps onto. For example,
3192 // __sync_fetch_and_add with a 2 byte object turns into
3193 // __sync_fetch_and_add_2.
3194#define BUILTIN_ROW(x) \
3195 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3196 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003197
Chris Lattnerdc046542009-05-08 06:58:22 +00003198 static const unsigned BuiltinIndices[][5] = {
3199 BUILTIN_ROW(__sync_fetch_and_add),
3200 BUILTIN_ROW(__sync_fetch_and_sub),
3201 BUILTIN_ROW(__sync_fetch_and_or),
3202 BUILTIN_ROW(__sync_fetch_and_and),
3203 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003204 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003205
Chris Lattnerdc046542009-05-08 06:58:22 +00003206 BUILTIN_ROW(__sync_add_and_fetch),
3207 BUILTIN_ROW(__sync_sub_and_fetch),
3208 BUILTIN_ROW(__sync_and_and_fetch),
3209 BUILTIN_ROW(__sync_or_and_fetch),
3210 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003211 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003212
Chris Lattnerdc046542009-05-08 06:58:22 +00003213 BUILTIN_ROW(__sync_val_compare_and_swap),
3214 BUILTIN_ROW(__sync_bool_compare_and_swap),
3215 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003216 BUILTIN_ROW(__sync_lock_release),
3217 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003218 };
Mike Stump11289f42009-09-09 15:08:12 +00003219#undef BUILTIN_ROW
3220
Chris Lattnerdc046542009-05-08 06:58:22 +00003221 // Determine the index of the size.
3222 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003223 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003224 case 1: SizeIndex = 0; break;
3225 case 2: SizeIndex = 1; break;
3226 case 4: SizeIndex = 2; break;
3227 case 8: SizeIndex = 3; break;
3228 case 16: SizeIndex = 4; break;
3229 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003230 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3231 << FirstArg->getType() << FirstArg->getSourceRange();
3232 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003233 }
Mike Stump11289f42009-09-09 15:08:12 +00003234
Chris Lattnerdc046542009-05-08 06:58:22 +00003235 // Each of these builtins has one pointer argument, followed by some number of
3236 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3237 // that we ignore. Find out which row of BuiltinIndices to read from as well
3238 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003239 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003240 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003241 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003242 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003243 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003244 case Builtin::BI__sync_fetch_and_add:
3245 case Builtin::BI__sync_fetch_and_add_1:
3246 case Builtin::BI__sync_fetch_and_add_2:
3247 case Builtin::BI__sync_fetch_and_add_4:
3248 case Builtin::BI__sync_fetch_and_add_8:
3249 case Builtin::BI__sync_fetch_and_add_16:
3250 BuiltinIndex = 0;
3251 break;
3252
3253 case Builtin::BI__sync_fetch_and_sub:
3254 case Builtin::BI__sync_fetch_and_sub_1:
3255 case Builtin::BI__sync_fetch_and_sub_2:
3256 case Builtin::BI__sync_fetch_and_sub_4:
3257 case Builtin::BI__sync_fetch_and_sub_8:
3258 case Builtin::BI__sync_fetch_and_sub_16:
3259 BuiltinIndex = 1;
3260 break;
3261
3262 case Builtin::BI__sync_fetch_and_or:
3263 case Builtin::BI__sync_fetch_and_or_1:
3264 case Builtin::BI__sync_fetch_and_or_2:
3265 case Builtin::BI__sync_fetch_and_or_4:
3266 case Builtin::BI__sync_fetch_and_or_8:
3267 case Builtin::BI__sync_fetch_and_or_16:
3268 BuiltinIndex = 2;
3269 break;
3270
3271 case Builtin::BI__sync_fetch_and_and:
3272 case Builtin::BI__sync_fetch_and_and_1:
3273 case Builtin::BI__sync_fetch_and_and_2:
3274 case Builtin::BI__sync_fetch_and_and_4:
3275 case Builtin::BI__sync_fetch_and_and_8:
3276 case Builtin::BI__sync_fetch_and_and_16:
3277 BuiltinIndex = 3;
3278 break;
Mike Stump11289f42009-09-09 15:08:12 +00003279
Douglas Gregor73722482011-11-28 16:30:08 +00003280 case Builtin::BI__sync_fetch_and_xor:
3281 case Builtin::BI__sync_fetch_and_xor_1:
3282 case Builtin::BI__sync_fetch_and_xor_2:
3283 case Builtin::BI__sync_fetch_and_xor_4:
3284 case Builtin::BI__sync_fetch_and_xor_8:
3285 case Builtin::BI__sync_fetch_and_xor_16:
3286 BuiltinIndex = 4;
3287 break;
3288
Hal Finkeld2208b52014-10-02 20:53:50 +00003289 case Builtin::BI__sync_fetch_and_nand:
3290 case Builtin::BI__sync_fetch_and_nand_1:
3291 case Builtin::BI__sync_fetch_and_nand_2:
3292 case Builtin::BI__sync_fetch_and_nand_4:
3293 case Builtin::BI__sync_fetch_and_nand_8:
3294 case Builtin::BI__sync_fetch_and_nand_16:
3295 BuiltinIndex = 5;
3296 WarnAboutSemanticsChange = true;
3297 break;
3298
Douglas Gregor73722482011-11-28 16:30:08 +00003299 case Builtin::BI__sync_add_and_fetch:
3300 case Builtin::BI__sync_add_and_fetch_1:
3301 case Builtin::BI__sync_add_and_fetch_2:
3302 case Builtin::BI__sync_add_and_fetch_4:
3303 case Builtin::BI__sync_add_and_fetch_8:
3304 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003305 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003306 break;
3307
3308 case Builtin::BI__sync_sub_and_fetch:
3309 case Builtin::BI__sync_sub_and_fetch_1:
3310 case Builtin::BI__sync_sub_and_fetch_2:
3311 case Builtin::BI__sync_sub_and_fetch_4:
3312 case Builtin::BI__sync_sub_and_fetch_8:
3313 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003314 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003315 break;
3316
3317 case Builtin::BI__sync_and_and_fetch:
3318 case Builtin::BI__sync_and_and_fetch_1:
3319 case Builtin::BI__sync_and_and_fetch_2:
3320 case Builtin::BI__sync_and_and_fetch_4:
3321 case Builtin::BI__sync_and_and_fetch_8:
3322 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003323 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003324 break;
3325
3326 case Builtin::BI__sync_or_and_fetch:
3327 case Builtin::BI__sync_or_and_fetch_1:
3328 case Builtin::BI__sync_or_and_fetch_2:
3329 case Builtin::BI__sync_or_and_fetch_4:
3330 case Builtin::BI__sync_or_and_fetch_8:
3331 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003332 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003333 break;
3334
3335 case Builtin::BI__sync_xor_and_fetch:
3336 case Builtin::BI__sync_xor_and_fetch_1:
3337 case Builtin::BI__sync_xor_and_fetch_2:
3338 case Builtin::BI__sync_xor_and_fetch_4:
3339 case Builtin::BI__sync_xor_and_fetch_8:
3340 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003341 BuiltinIndex = 10;
3342 break;
3343
3344 case Builtin::BI__sync_nand_and_fetch:
3345 case Builtin::BI__sync_nand_and_fetch_1:
3346 case Builtin::BI__sync_nand_and_fetch_2:
3347 case Builtin::BI__sync_nand_and_fetch_4:
3348 case Builtin::BI__sync_nand_and_fetch_8:
3349 case Builtin::BI__sync_nand_and_fetch_16:
3350 BuiltinIndex = 11;
3351 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003352 break;
Mike Stump11289f42009-09-09 15:08:12 +00003353
Chris Lattnerdc046542009-05-08 06:58:22 +00003354 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003355 case Builtin::BI__sync_val_compare_and_swap_1:
3356 case Builtin::BI__sync_val_compare_and_swap_2:
3357 case Builtin::BI__sync_val_compare_and_swap_4:
3358 case Builtin::BI__sync_val_compare_and_swap_8:
3359 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003360 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003361 NumFixed = 2;
3362 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003363
Chris Lattnerdc046542009-05-08 06:58:22 +00003364 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003365 case Builtin::BI__sync_bool_compare_and_swap_1:
3366 case Builtin::BI__sync_bool_compare_and_swap_2:
3367 case Builtin::BI__sync_bool_compare_and_swap_4:
3368 case Builtin::BI__sync_bool_compare_and_swap_8:
3369 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003370 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003371 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003372 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003373 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003374
3375 case Builtin::BI__sync_lock_test_and_set:
3376 case Builtin::BI__sync_lock_test_and_set_1:
3377 case Builtin::BI__sync_lock_test_and_set_2:
3378 case Builtin::BI__sync_lock_test_and_set_4:
3379 case Builtin::BI__sync_lock_test_and_set_8:
3380 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003381 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003382 break;
3383
Chris Lattnerdc046542009-05-08 06:58:22 +00003384 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003385 case Builtin::BI__sync_lock_release_1:
3386 case Builtin::BI__sync_lock_release_2:
3387 case Builtin::BI__sync_lock_release_4:
3388 case Builtin::BI__sync_lock_release_8:
3389 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003390 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003391 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003392 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003393 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003394
3395 case Builtin::BI__sync_swap:
3396 case Builtin::BI__sync_swap_1:
3397 case Builtin::BI__sync_swap_2:
3398 case Builtin::BI__sync_swap_4:
3399 case Builtin::BI__sync_swap_8:
3400 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003401 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003402 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003403 }
Mike Stump11289f42009-09-09 15:08:12 +00003404
Chris Lattnerdc046542009-05-08 06:58:22 +00003405 // Now that we know how many fixed arguments we expect, first check that we
3406 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003407 if (TheCall->getNumArgs() < 1+NumFixed) {
3408 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3409 << 0 << 1+NumFixed << TheCall->getNumArgs()
3410 << TheCall->getCallee()->getSourceRange();
3411 return ExprError();
3412 }
Mike Stump11289f42009-09-09 15:08:12 +00003413
Hal Finkeld2208b52014-10-02 20:53:50 +00003414 if (WarnAboutSemanticsChange) {
3415 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3416 << TheCall->getCallee()->getSourceRange();
3417 }
3418
Chris Lattner5b9241b2009-05-08 15:36:58 +00003419 // Get the decl for the concrete builtin from this, we can tell what the
3420 // concrete integer type we should convert to is.
3421 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003422 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003423 FunctionDecl *NewBuiltinDecl;
3424 if (NewBuiltinID == BuiltinID)
3425 NewBuiltinDecl = FDecl;
3426 else {
3427 // Perform builtin lookup to avoid redeclaring it.
3428 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3429 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3430 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3431 assert(Res.getFoundDecl());
3432 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003433 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003434 return ExprError();
3435 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003436
John McCallcf142162010-08-07 06:22:56 +00003437 // The first argument --- the pointer --- has a fixed type; we
3438 // deduce the types of the rest of the arguments accordingly. Walk
3439 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003440 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003441 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003442
Chris Lattnerdc046542009-05-08 06:58:22 +00003443 // GCC does an implicit conversion to the pointer or integer ValType. This
3444 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003445 // Initialize the argument.
3446 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3447 ValType, /*consume*/ false);
3448 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003449 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003450 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003451
Chris Lattnerdc046542009-05-08 06:58:22 +00003452 // Okay, we have something that *can* be converted to the right type. Check
3453 // to see if there is a potentially weird extension going on here. This can
3454 // happen when you do an atomic operation on something like an char* and
3455 // pass in 42. The 42 gets converted to char. This is even more strange
3456 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003457 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003458 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003459 }
Mike Stump11289f42009-09-09 15:08:12 +00003460
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003461 ASTContext& Context = this->getASTContext();
3462
3463 // Create a new DeclRefExpr to refer to the new decl.
3464 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3465 Context,
3466 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003467 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003468 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003469 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003470 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003471 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003472 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003473
Chris Lattnerdc046542009-05-08 06:58:22 +00003474 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003475 // FIXME: This loses syntactic information.
3476 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3477 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3478 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003479 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003480
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003481 // Change the result type of the call to match the original value type. This
3482 // is arbitrary, but the codegen for these builtins ins design to handle it
3483 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003484 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003485
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003486 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003487}
3488
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003489/// SemaBuiltinNontemporalOverloaded - We have a call to
3490/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3491/// overloaded function based on the pointer type of its last argument.
3492///
3493/// This function goes through and does final semantic checking for these
3494/// builtins.
3495ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3496 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3497 DeclRefExpr *DRE =
3498 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3499 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3500 unsigned BuiltinID = FDecl->getBuiltinID();
3501 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3502 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3503 "Unexpected nontemporal load/store builtin!");
3504 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3505 unsigned numArgs = isStore ? 2 : 1;
3506
3507 // Ensure that we have the proper number of arguments.
3508 if (checkArgCount(*this, TheCall, numArgs))
3509 return ExprError();
3510
3511 // Inspect the last argument of the nontemporal builtin. This should always
3512 // be a pointer type, from which we imply the type of the memory access.
3513 // Because it is a pointer type, we don't have to worry about any implicit
3514 // casts here.
3515 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3516 ExprResult PointerArgResult =
3517 DefaultFunctionArrayLvalueConversion(PointerArg);
3518
3519 if (PointerArgResult.isInvalid())
3520 return ExprError();
3521 PointerArg = PointerArgResult.get();
3522 TheCall->setArg(numArgs - 1, PointerArg);
3523
3524 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3525 if (!pointerType) {
3526 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3527 << PointerArg->getType() << PointerArg->getSourceRange();
3528 return ExprError();
3529 }
3530
3531 QualType ValType = pointerType->getPointeeType();
3532
3533 // Strip any qualifiers off ValType.
3534 ValType = ValType.getUnqualifiedType();
3535 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3536 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3537 !ValType->isVectorType()) {
3538 Diag(DRE->getLocStart(),
3539 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3540 << PointerArg->getType() << PointerArg->getSourceRange();
3541 return ExprError();
3542 }
3543
3544 if (!isStore) {
3545 TheCall->setType(ValType);
3546 return TheCallResult;
3547 }
3548
3549 ExprResult ValArg = TheCall->getArg(0);
3550 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3551 Context, ValType, /*consume*/ false);
3552 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3553 if (ValArg.isInvalid())
3554 return ExprError();
3555
3556 TheCall->setArg(0, ValArg.get());
3557 TheCall->setType(Context.VoidTy);
3558 return TheCallResult;
3559}
3560
Chris Lattner6436fb62009-02-18 06:01:06 +00003561/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003562/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003563/// Note: It might also make sense to do the UTF-16 conversion here (would
3564/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003565bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003566 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003567 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3568
Douglas Gregorfb65e592011-07-27 05:40:30 +00003569 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003570 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3571 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003572 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003573 }
Mike Stump11289f42009-09-09 15:08:12 +00003574
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003575 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003576 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003577 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00003578 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3579 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3580 llvm::UTF16 *ToPtr = &ToBuf[0];
3581
3582 llvm::ConversionResult Result =
3583 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3584 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003585 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00003586 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003587 Diag(Arg->getLocStart(),
3588 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3589 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003590 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003591}
3592
Mehdi Amini06d367c2016-10-24 20:39:34 +00003593/// CheckObjCString - Checks that the format string argument to the os_log()
3594/// and os_trace() functions is correct, and converts it to const char *.
3595ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3596 Arg = Arg->IgnoreParenCasts();
3597 auto *Literal = dyn_cast<StringLiteral>(Arg);
3598 if (!Literal) {
3599 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3600 Literal = ObjcLiteral->getString();
3601 }
3602 }
3603
3604 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3605 return ExprError(
3606 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3607 << Arg->getSourceRange());
3608 }
3609
3610 ExprResult Result(Literal);
3611 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3612 InitializedEntity Entity =
3613 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3614 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3615 return Result;
3616}
3617
Charles Davisc7d5c942015-09-17 20:55:33 +00003618/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3619/// for validity. Emit an error and return true on failure; return false
3620/// on success.
3621bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003622 Expr *Fn = TheCall->getCallee();
3623 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003624 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003625 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003626 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3627 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003628 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003629 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003630 return true;
3631 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003632
3633 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003634 return Diag(TheCall->getLocEnd(),
3635 diag::err_typecheck_call_too_few_args_at_least)
3636 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003637 }
3638
John McCall29ad95b2011-08-27 01:09:30 +00003639 // Type-check the first argument normally.
3640 if (checkBuiltinArgument(*this, TheCall, 0))
3641 return true;
3642
Chris Lattnere202e6a2007-12-20 00:05:45 +00003643 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00003644 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00003645 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00003646 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00003647 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00003648 else if (FunctionDecl *FD = getCurFunctionDecl())
3649 isVariadic = FD->isVariadic();
3650 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00003651 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00003652
Chris Lattnere202e6a2007-12-20 00:05:45 +00003653 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003654 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3655 return true;
3656 }
Mike Stump11289f42009-09-09 15:08:12 +00003657
Chris Lattner43be2e62007-12-19 23:59:04 +00003658 // Verify that the second argument to the builtin is the last argument of the
3659 // current function or method.
3660 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003661 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003662
Nico Weber9eea7642013-05-24 23:31:57 +00003663 // These are valid if SecondArgIsLastNamedArgument is false after the next
3664 // block.
3665 QualType Type;
3666 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003667 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003668
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003669 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3670 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003671 // FIXME: This isn't correct for methods (results in bogus warning).
3672 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003673 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00003674 if (CurBlock)
David Majnemera3debed2016-06-24 05:33:44 +00003675 LastArg = CurBlock->TheDecl->parameters().back();
Steve Naroff439a3e42009-04-15 19:33:47 +00003676 else if (FunctionDecl *FD = getCurFunctionDecl())
David Majnemera3debed2016-06-24 05:33:44 +00003677 LastArg = FD->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003678 else
David Majnemera3debed2016-06-24 05:33:44 +00003679 LastArg = getCurMethodDecl()->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003680 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00003681
3682 Type = PV->getType();
3683 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003684 IsCRegister =
3685 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003686 }
3687 }
Mike Stump11289f42009-09-09 15:08:12 +00003688
Chris Lattner43be2e62007-12-19 23:59:04 +00003689 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003690 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003691 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003692 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00003693 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3694 // Promotable integers are UB, but enumerations need a bit of
3695 // extra checking to see what their promotable type actually is.
3696 if (!Type->isPromotableIntegerType())
3697 return false;
3698 if (!Type->isEnumeralType())
3699 return true;
3700 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3701 return !(ED &&
3702 Context.typesAreCompatible(ED->getPromotionType(), Type));
3703 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00003704 unsigned Reason = 0;
3705 if (Type->isReferenceType()) Reason = 1;
3706 else if (IsCRegister) Reason = 2;
3707 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003708 Diag(ParamLoc, diag::note_parameter_type) << Type;
3709 }
3710
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003711 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003712 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003713}
Chris Lattner43be2e62007-12-19 23:59:04 +00003714
Charles Davisc7d5c942015-09-17 20:55:33 +00003715/// Check the arguments to '__builtin_va_start' for validity, and that
3716/// it was called from a function of the native ABI.
3717/// Emit an error and return true on failure; return false on success.
3718bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3719 // On x86-64 Unix, don't allow this in Win64 ABI functions.
3720 // On x64 Windows, don't allow this in System V ABI functions.
3721 // (Yes, that means there's no corresponding way to support variadic
3722 // System V ABI functions on Windows.)
3723 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3724 unsigned OS = Context.getTargetInfo().getTriple().getOS();
3725 clang::CallingConv CC = CC_C;
3726 if (const FunctionDecl *FD = getCurFunctionDecl())
3727 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3728 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3729 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3730 return Diag(TheCall->getCallee()->getLocStart(),
3731 diag::err_va_start_used_in_wrong_abi_function)
3732 << (OS != llvm::Triple::Win32);
3733 }
3734 return SemaBuiltinVAStartImpl(TheCall);
3735}
3736
3737/// Check the arguments to '__builtin_ms_va_start' for validity, and that
3738/// it was called from a Win64 ABI function.
3739/// Emit an error and return true on failure; return false on success.
3740bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3741 // This only makes sense for x86-64.
3742 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3743 Expr *Callee = TheCall->getCallee();
3744 if (TT.getArch() != llvm::Triple::x86_64)
3745 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3746 // Don't allow this in System V ABI functions.
3747 clang::CallingConv CC = CC_C;
3748 if (const FunctionDecl *FD = getCurFunctionDecl())
3749 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3750 if (CC == CC_X86_64SysV ||
3751 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3752 return Diag(Callee->getLocStart(),
3753 diag::err_ms_va_start_used_in_sysv_function);
3754 return SemaBuiltinVAStartImpl(TheCall);
3755}
3756
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003757bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3758 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3759 // const char *named_addr);
3760
3761 Expr *Func = Call->getCallee();
3762
3763 if (Call->getNumArgs() < 3)
3764 return Diag(Call->getLocEnd(),
3765 diag::err_typecheck_call_too_few_args_at_least)
3766 << 0 /*function call*/ << 3 << Call->getNumArgs();
3767
3768 // Determine whether the current function is variadic or not.
3769 bool IsVariadic;
3770 if (BlockScopeInfo *CurBlock = getCurBlock())
3771 IsVariadic = CurBlock->TheDecl->isVariadic();
3772 else if (FunctionDecl *FD = getCurFunctionDecl())
3773 IsVariadic = FD->isVariadic();
3774 else if (ObjCMethodDecl *MD = getCurMethodDecl())
3775 IsVariadic = MD->isVariadic();
3776 else
3777 llvm_unreachable("unexpected statement type");
3778
3779 if (!IsVariadic) {
3780 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3781 return true;
3782 }
3783
3784 // Type-check the first argument normally.
3785 if (checkBuiltinArgument(*this, Call, 0))
3786 return true;
3787
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003788 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003789 unsigned ArgNo;
3790 QualType Type;
3791 } ArgumentTypes[] = {
3792 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3793 { 2, Context.getSizeType() },
3794 };
3795
3796 for (const auto &AT : ArgumentTypes) {
3797 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3798 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3799 continue;
3800 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3801 << Arg->getType() << AT.Type << 1 /* different class */
3802 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3803 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3804 }
3805
3806 return false;
3807}
3808
Chris Lattner2da14fb2007-12-20 00:26:33 +00003809/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3810/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003811bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3812 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003813 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003814 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003815 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003816 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003817 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003818 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003819 << SourceRange(TheCall->getArg(2)->getLocStart(),
3820 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003821
John Wiegley01296292011-04-08 18:41:53 +00003822 ExprResult OrigArg0 = TheCall->getArg(0);
3823 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003824
Chris Lattner2da14fb2007-12-20 00:26:33 +00003825 // Do standard promotions between the two arguments, returning their common
3826 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003827 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003828 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3829 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003830
3831 // Make sure any conversions are pushed back into the call; this is
3832 // type safe since unordered compare builtins are declared as "_Bool
3833 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003834 TheCall->setArg(0, OrigArg0.get());
3835 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003836
John Wiegley01296292011-04-08 18:41:53 +00003837 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003838 return false;
3839
Chris Lattner2da14fb2007-12-20 00:26:33 +00003840 // If the common type isn't a real floating type, then the arguments were
3841 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003842 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00003843 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003844 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00003845 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3846 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003847
Chris Lattner2da14fb2007-12-20 00:26:33 +00003848 return false;
3849}
3850
Benjamin Kramer634fc102010-02-15 22:42:31 +00003851/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3852/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00003853/// to check everything. We expect the last argument to be a floating point
3854/// value.
3855bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3856 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00003857 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003858 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00003859 if (TheCall->getNumArgs() > NumArgs)
3860 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003861 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003862 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00003863 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003864 (*(TheCall->arg_end()-1))->getLocEnd());
3865
Benjamin Kramer64aae502010-02-16 10:07:31 +00003866 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00003867
Eli Friedman7e4faac2009-08-31 20:06:00 +00003868 if (OrigArg->isTypeDependent())
3869 return false;
3870
Chris Lattner68784ef2010-05-06 05:50:07 +00003871 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00003872 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00003873 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003874 diag::err_typecheck_call_invalid_unary_fp)
3875 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003876
Neil Hickey88c0fac2016-12-13 16:22:50 +00003877 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00003878 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00003879 // Only remove standard FloatCasts, leaving other casts inplace
3880 if (Cast->getCastKind() == CK_FloatingCast) {
3881 Expr *CastArg = Cast->getSubExpr();
3882 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3883 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
3884 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
3885 "promotion from float to either float or double is the only expected cast here");
3886 Cast->setSubExpr(nullptr);
3887 TheCall->setArg(NumArgs-1, CastArg);
3888 }
Chris Lattner68784ef2010-05-06 05:50:07 +00003889 }
3890 }
3891
Eli Friedman7e4faac2009-08-31 20:06:00 +00003892 return false;
3893}
3894
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003895/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3896// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00003897ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00003898 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003899 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00003900 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00003901 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3902 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003903
Nate Begemana0110022010-06-08 00:16:34 +00003904 // Determine which of the following types of shufflevector we're checking:
3905 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00003906 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00003907 QualType resType = TheCall->getArg(0)->getType();
3908 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00003909
Douglas Gregorc25f7662009-05-19 22:10:17 +00003910 if (!TheCall->getArg(0)->isTypeDependent() &&
3911 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00003912 QualType LHSType = TheCall->getArg(0)->getType();
3913 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00003914
Craig Topperbaca3892013-07-29 06:47:04 +00003915 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3916 return ExprError(Diag(TheCall->getLocStart(),
3917 diag::err_shufflevector_non_vector)
3918 << SourceRange(TheCall->getArg(0)->getLocStart(),
3919 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003920
Nate Begemana0110022010-06-08 00:16:34 +00003921 numElements = LHSType->getAs<VectorType>()->getNumElements();
3922 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00003923
Nate Begemana0110022010-06-08 00:16:34 +00003924 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3925 // with mask. If so, verify that RHS is an integer vector type with the
3926 // same number of elts as lhs.
3927 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00003928 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00003929 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00003930 return ExprError(Diag(TheCall->getLocStart(),
3931 diag::err_shufflevector_incompatible_vector)
3932 << SourceRange(TheCall->getArg(1)->getLocStart(),
3933 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003934 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00003935 return ExprError(Diag(TheCall->getLocStart(),
3936 diag::err_shufflevector_incompatible_vector)
3937 << SourceRange(TheCall->getArg(0)->getLocStart(),
3938 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00003939 } else if (numElements != numResElements) {
3940 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00003941 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003942 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003943 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003944 }
3945
3946 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00003947 if (TheCall->getArg(i)->isTypeDependent() ||
3948 TheCall->getArg(i)->isValueDependent())
3949 continue;
3950
Nate Begemana0110022010-06-08 00:16:34 +00003951 llvm::APSInt Result(32);
3952 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3953 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003954 diag::err_shufflevector_nonconstant_argument)
3955 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003956
Craig Topper50ad5b72013-08-03 17:40:38 +00003957 // Allow -1 which will be translated to undef in the IR.
3958 if (Result.isSigned() && Result.isAllOnesValue())
3959 continue;
3960
Chris Lattner7ab824e2008-08-10 02:05:13 +00003961 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003962 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003963 diag::err_shufflevector_argument_too_large)
3964 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003965 }
3966
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003967 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003968
Chris Lattner7ab824e2008-08-10 02:05:13 +00003969 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003970 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00003971 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003972 }
3973
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003974 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3975 TheCall->getCallee()->getLocStart(),
3976 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003977}
Chris Lattner43be2e62007-12-19 23:59:04 +00003978
Hal Finkelc4d7c822013-09-18 03:29:45 +00003979/// SemaConvertVectorExpr - Handle __builtin_convertvector
3980ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3981 SourceLocation BuiltinLoc,
3982 SourceLocation RParenLoc) {
3983 ExprValueKind VK = VK_RValue;
3984 ExprObjectKind OK = OK_Ordinary;
3985 QualType DstTy = TInfo->getType();
3986 QualType SrcTy = E->getType();
3987
3988 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3989 return ExprError(Diag(BuiltinLoc,
3990 diag::err_convertvector_non_vector)
3991 << E->getSourceRange());
3992 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3993 return ExprError(Diag(BuiltinLoc,
3994 diag::err_convertvector_non_vector_type));
3995
3996 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3997 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3998 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3999 if (SrcElts != DstElts)
4000 return ExprError(Diag(BuiltinLoc,
4001 diag::err_convertvector_incompatible_vector)
4002 << E->getSourceRange());
4003 }
4004
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004005 return new (Context)
4006 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00004007}
4008
Daniel Dunbarb7257262008-07-21 22:59:13 +00004009/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4010// This is declared to take (const void*, ...) and can take two
4011// optional constant int args.
4012bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00004013 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004014
Chris Lattner3b054132008-11-19 05:08:23 +00004015 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004016 return Diag(TheCall->getLocEnd(),
4017 diag::err_typecheck_call_too_many_args_at_most)
4018 << 0 /*function call*/ << 3 << NumArgs
4019 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004020
4021 // Argument 0 is checked for us and the remaining arguments must be
4022 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00004023 for (unsigned i = 1; i != NumArgs; ++i)
4024 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004025 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004026
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004027 return false;
4028}
4029
Hal Finkelf0417332014-07-17 14:25:55 +00004030/// SemaBuiltinAssume - Handle __assume (MS Extension).
4031// __assume does not evaluate its arguments, and should warn if its argument
4032// has side effects.
4033bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4034 Expr *Arg = TheCall->getArg(0);
4035 if (Arg->isInstantiationDependent()) return false;
4036
4037 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00004038 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00004039 << Arg->getSourceRange()
4040 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4041
4042 return false;
4043}
4044
David Majnemer86b1bfa2016-10-31 18:07:57 +00004045/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00004046/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4047/// than 8.
4048bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4049 // The alignment must be a constant integer.
4050 Expr *Arg = TheCall->getArg(1);
4051
4052 // We can't check the value of a dependent argument.
4053 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00004054 if (const auto *UE =
4055 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4056 if (UE->getKind() == UETT_AlignOf)
4057 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4058 << Arg->getSourceRange();
4059
David Majnemer51169932016-10-31 05:37:48 +00004060 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4061
4062 if (!Result.isPowerOf2())
4063 return Diag(TheCall->getLocStart(),
4064 diag::err_alignment_not_power_of_two)
4065 << Arg->getSourceRange();
4066
4067 if (Result < Context.getCharWidth())
4068 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4069 << (unsigned)Context.getCharWidth()
4070 << Arg->getSourceRange();
4071
4072 if (Result > INT32_MAX)
4073 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4074 << INT32_MAX
4075 << Arg->getSourceRange();
4076 }
4077
4078 return false;
4079}
4080
4081/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00004082/// as (const void*, size_t, ...) and can take one optional constant int arg.
4083bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4084 unsigned NumArgs = TheCall->getNumArgs();
4085
4086 if (NumArgs > 3)
4087 return Diag(TheCall->getLocEnd(),
4088 diag::err_typecheck_call_too_many_args_at_most)
4089 << 0 /*function call*/ << 3 << NumArgs
4090 << TheCall->getSourceRange();
4091
4092 // The alignment must be a constant integer.
4093 Expr *Arg = TheCall->getArg(1);
4094
4095 // We can't check the value of a dependent argument.
4096 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4097 llvm::APSInt Result;
4098 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4099 return true;
4100
4101 if (!Result.isPowerOf2())
4102 return Diag(TheCall->getLocStart(),
4103 diag::err_alignment_not_power_of_two)
4104 << Arg->getSourceRange();
4105 }
4106
4107 if (NumArgs > 2) {
4108 ExprResult Arg(TheCall->getArg(2));
4109 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4110 Context.getSizeType(), false);
4111 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4112 if (Arg.isInvalid()) return true;
4113 TheCall->setArg(2, Arg.get());
4114 }
Hal Finkelf0417332014-07-17 14:25:55 +00004115
4116 return false;
4117}
4118
Mehdi Amini06d367c2016-10-24 20:39:34 +00004119bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4120 unsigned BuiltinID =
4121 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4122 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4123
4124 unsigned NumArgs = TheCall->getNumArgs();
4125 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4126 if (NumArgs < NumRequiredArgs) {
4127 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4128 << 0 /* function call */ << NumRequiredArgs << NumArgs
4129 << TheCall->getSourceRange();
4130 }
4131 if (NumArgs >= NumRequiredArgs + 0x100) {
4132 return Diag(TheCall->getLocEnd(),
4133 diag::err_typecheck_call_too_many_args_at_most)
4134 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4135 << TheCall->getSourceRange();
4136 }
4137 unsigned i = 0;
4138
4139 // For formatting call, check buffer arg.
4140 if (!IsSizeCall) {
4141 ExprResult Arg(TheCall->getArg(i));
4142 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4143 Context, Context.VoidPtrTy, false);
4144 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4145 if (Arg.isInvalid())
4146 return true;
4147 TheCall->setArg(i, Arg.get());
4148 i++;
4149 }
4150
4151 // Check string literal arg.
4152 unsigned FormatIdx = i;
4153 {
4154 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4155 if (Arg.isInvalid())
4156 return true;
4157 TheCall->setArg(i, Arg.get());
4158 i++;
4159 }
4160
4161 // Make sure variadic args are scalar.
4162 unsigned FirstDataArg = i;
4163 while (i < NumArgs) {
4164 ExprResult Arg = DefaultVariadicArgumentPromotion(
4165 TheCall->getArg(i), VariadicFunction, nullptr);
4166 if (Arg.isInvalid())
4167 return true;
4168 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4169 if (ArgSize.getQuantity() >= 0x100) {
4170 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4171 << i << (int)ArgSize.getQuantity() << 0xff
4172 << TheCall->getSourceRange();
4173 }
4174 TheCall->setArg(i, Arg.get());
4175 i++;
4176 }
4177
4178 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4179 // call to avoid duplicate diagnostics.
4180 if (!IsSizeCall) {
4181 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4182 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4183 bool Success = CheckFormatArguments(
4184 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4185 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4186 CheckedVarArgs);
4187 if (!Success)
4188 return true;
4189 }
4190
4191 if (IsSizeCall) {
4192 TheCall->setType(Context.getSizeType());
4193 } else {
4194 TheCall->setType(Context.VoidPtrTy);
4195 }
4196 return false;
4197}
4198
Eric Christopher8d0c6212010-04-17 02:26:23 +00004199/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4200/// TheCall is a constant expression.
4201bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4202 llvm::APSInt &Result) {
4203 Expr *Arg = TheCall->getArg(ArgNum);
4204 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4205 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4206
4207 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4208
4209 if (!Arg->isIntegerConstantExpr(Result, Context))
4210 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004211 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004212
Chris Lattnerd545ad12009-09-23 06:06:36 +00004213 return false;
4214}
4215
Richard Sandiford28940af2014-04-16 08:47:51 +00004216/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4217/// TheCall is a constant expression in the range [Low, High].
4218bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4219 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004220 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004221
4222 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004223 Expr *Arg = TheCall->getArg(ArgNum);
4224 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004225 return false;
4226
Eric Christopher8d0c6212010-04-17 02:26:23 +00004227 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004228 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004229 return true;
4230
Richard Sandiford28940af2014-04-16 08:47:51 +00004231 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004232 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004233 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004234
4235 return false;
4236}
4237
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004238/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4239/// TheCall is a constant expression is a multiple of Num..
4240bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4241 unsigned Num) {
4242 llvm::APSInt Result;
4243
4244 // We can't check the value of a dependent argument.
4245 Expr *Arg = TheCall->getArg(ArgNum);
4246 if (Arg->isTypeDependent() || Arg->isValueDependent())
4247 return false;
4248
4249 // Check constant-ness first.
4250 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4251 return true;
4252
4253 if (Result.getSExtValue() % Num != 0)
4254 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4255 << Num << Arg->getSourceRange();
4256
4257 return false;
4258}
4259
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004260/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4261/// TheCall is an ARM/AArch64 special register string literal.
4262bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4263 int ArgNum, unsigned ExpectedFieldNum,
4264 bool AllowName) {
4265 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4266 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4267 BuiltinID == ARM::BI__builtin_arm_rsr ||
4268 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4269 BuiltinID == ARM::BI__builtin_arm_wsr ||
4270 BuiltinID == ARM::BI__builtin_arm_wsrp;
4271 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4272 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4273 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4274 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4275 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4276 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4277 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4278
4279 // We can't check the value of a dependent argument.
4280 Expr *Arg = TheCall->getArg(ArgNum);
4281 if (Arg->isTypeDependent() || Arg->isValueDependent())
4282 return false;
4283
4284 // Check if the argument is a string literal.
4285 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4286 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4287 << Arg->getSourceRange();
4288
4289 // Check the type of special register given.
4290 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4291 SmallVector<StringRef, 6> Fields;
4292 Reg.split(Fields, ":");
4293
4294 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4295 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4296 << Arg->getSourceRange();
4297
4298 // If the string is the name of a register then we cannot check that it is
4299 // valid here but if the string is of one the forms described in ACLE then we
4300 // can check that the supplied fields are integers and within the valid
4301 // ranges.
4302 if (Fields.size() > 1) {
4303 bool FiveFields = Fields.size() == 5;
4304
4305 bool ValidString = true;
4306 if (IsARMBuiltin) {
4307 ValidString &= Fields[0].startswith_lower("cp") ||
4308 Fields[0].startswith_lower("p");
4309 if (ValidString)
4310 Fields[0] =
4311 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4312
4313 ValidString &= Fields[2].startswith_lower("c");
4314 if (ValidString)
4315 Fields[2] = Fields[2].drop_front(1);
4316
4317 if (FiveFields) {
4318 ValidString &= Fields[3].startswith_lower("c");
4319 if (ValidString)
4320 Fields[3] = Fields[3].drop_front(1);
4321 }
4322 }
4323
4324 SmallVector<int, 5> Ranges;
4325 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00004326 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004327 else
4328 Ranges.append({15, 7, 15});
4329
4330 for (unsigned i=0; i<Fields.size(); ++i) {
4331 int IntField;
4332 ValidString &= !Fields[i].getAsInteger(10, IntField);
4333 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4334 }
4335
4336 if (!ValidString)
4337 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4338 << Arg->getSourceRange();
4339
4340 } else if (IsAArch64Builtin && Fields.size() == 1) {
4341 // If the register name is one of those that appear in the condition below
4342 // and the special register builtin being used is one of the write builtins,
4343 // then we require that the argument provided for writing to the register
4344 // is an integer constant expression. This is because it will be lowered to
4345 // an MSR (immediate) instruction, so we need to know the immediate at
4346 // compile time.
4347 if (TheCall->getNumArgs() != 2)
4348 return false;
4349
4350 std::string RegLower = Reg.lower();
4351 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4352 RegLower != "pan" && RegLower != "uao")
4353 return false;
4354
4355 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4356 }
4357
4358 return false;
4359}
4360
Eli Friedmanc97d0142009-05-03 06:04:26 +00004361/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004362/// This checks that the target supports __builtin_longjmp and
4363/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004364bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004365 if (!Context.getTargetInfo().hasSjLjLowering())
4366 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4367 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4368
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004369 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004370 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004371
Eric Christopher8d0c6212010-04-17 02:26:23 +00004372 // TODO: This is less than ideal. Overload this to take a value.
4373 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4374 return true;
4375
4376 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004377 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4378 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4379
4380 return false;
4381}
4382
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004383/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4384/// This checks that the target supports __builtin_setjmp.
4385bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4386 if (!Context.getTargetInfo().hasSjLjLowering())
4387 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4388 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4389 return false;
4390}
4391
Richard Smithd7293d72013-08-05 18:49:43 +00004392namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004393class UncoveredArgHandler {
4394 enum { Unknown = -1, AllCovered = -2 };
4395 signed FirstUncoveredArg;
4396 SmallVector<const Expr *, 4> DiagnosticExprs;
4397
4398public:
4399 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4400
4401 bool hasUncoveredArg() const {
4402 return (FirstUncoveredArg >= 0);
4403 }
4404
4405 unsigned getUncoveredArg() const {
4406 assert(hasUncoveredArg() && "no uncovered argument");
4407 return FirstUncoveredArg;
4408 }
4409
4410 void setAllCovered() {
4411 // A string has been found with all arguments covered, so clear out
4412 // the diagnostics.
4413 DiagnosticExprs.clear();
4414 FirstUncoveredArg = AllCovered;
4415 }
4416
4417 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4418 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4419
4420 // Don't update if a previous string covers all arguments.
4421 if (FirstUncoveredArg == AllCovered)
4422 return;
4423
4424 // UncoveredArgHandler tracks the highest uncovered argument index
4425 // and with it all the strings that match this index.
4426 if (NewFirstUncoveredArg == FirstUncoveredArg)
4427 DiagnosticExprs.push_back(StrExpr);
4428 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4429 DiagnosticExprs.clear();
4430 DiagnosticExprs.push_back(StrExpr);
4431 FirstUncoveredArg = NewFirstUncoveredArg;
4432 }
4433 }
4434
4435 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4436};
4437
Richard Smithd7293d72013-08-05 18:49:43 +00004438enum StringLiteralCheckType {
4439 SLCT_NotALiteral,
4440 SLCT_UncheckedLiteral,
4441 SLCT_CheckedLiteral
4442};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004443} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00004444
Stephen Hines648c3692016-09-16 01:07:04 +00004445static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4446 BinaryOperatorKind BinOpKind,
4447 bool AddendIsRight) {
4448 unsigned BitWidth = Offset.getBitWidth();
4449 unsigned AddendBitWidth = Addend.getBitWidth();
4450 // There might be negative interim results.
4451 if (Addend.isUnsigned()) {
4452 Addend = Addend.zext(++AddendBitWidth);
4453 Addend.setIsSigned(true);
4454 }
4455 // Adjust the bit width of the APSInts.
4456 if (AddendBitWidth > BitWidth) {
4457 Offset = Offset.sext(AddendBitWidth);
4458 BitWidth = AddendBitWidth;
4459 } else if (BitWidth > AddendBitWidth) {
4460 Addend = Addend.sext(BitWidth);
4461 }
4462
4463 bool Ov = false;
4464 llvm::APSInt ResOffset = Offset;
4465 if (BinOpKind == BO_Add)
4466 ResOffset = Offset.sadd_ov(Addend, Ov);
4467 else {
4468 assert(AddendIsRight && BinOpKind == BO_Sub &&
4469 "operator must be add or sub with addend on the right");
4470 ResOffset = Offset.ssub_ov(Addend, Ov);
4471 }
4472
4473 // We add an offset to a pointer here so we should support an offset as big as
4474 // possible.
4475 if (Ov) {
4476 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00004477 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00004478 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4479 return;
4480 }
4481
4482 Offset = ResOffset;
4483}
4484
4485namespace {
4486// This is a wrapper class around StringLiteral to support offsetted string
4487// literals as format strings. It takes the offset into account when returning
4488// the string and its length or the source locations to display notes correctly.
4489class FormatStringLiteral {
4490 const StringLiteral *FExpr;
4491 int64_t Offset;
4492
4493 public:
4494 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4495 : FExpr(fexpr), Offset(Offset) {}
4496
4497 StringRef getString() const {
4498 return FExpr->getString().drop_front(Offset);
4499 }
4500
4501 unsigned getByteLength() const {
4502 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4503 }
4504 unsigned getLength() const { return FExpr->getLength() - Offset; }
4505 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4506
4507 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4508
4509 QualType getType() const { return FExpr->getType(); }
4510
4511 bool isAscii() const { return FExpr->isAscii(); }
4512 bool isWide() const { return FExpr->isWide(); }
4513 bool isUTF8() const { return FExpr->isUTF8(); }
4514 bool isUTF16() const { return FExpr->isUTF16(); }
4515 bool isUTF32() const { return FExpr->isUTF32(); }
4516 bool isPascal() const { return FExpr->isPascal(); }
4517
4518 SourceLocation getLocationOfByte(
4519 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4520 const TargetInfo &Target, unsigned *StartToken = nullptr,
4521 unsigned *StartTokenByteOffset = nullptr) const {
4522 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4523 StartToken, StartTokenByteOffset);
4524 }
4525
4526 SourceLocation getLocStart() const LLVM_READONLY {
4527 return FExpr->getLocStart().getLocWithOffset(Offset);
4528 }
4529 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4530};
4531} // end anonymous namespace
4532
4533static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004534 const Expr *OrigFormatExpr,
4535 ArrayRef<const Expr *> Args,
4536 bool HasVAListArg, unsigned format_idx,
4537 unsigned firstDataArg,
4538 Sema::FormatStringType Type,
4539 bool inFunctionCall,
4540 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004541 llvm::SmallBitVector &CheckedVarArgs,
4542 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004543
Richard Smith55ce3522012-06-25 20:30:08 +00004544// Determine if an expression is a string literal or constant string.
4545// If this function returns false on the arguments to a function expecting a
4546// format string, we will usually need to emit a warning.
4547// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00004548static StringLiteralCheckType
4549checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4550 bool HasVAListArg, unsigned format_idx,
4551 unsigned firstDataArg, Sema::FormatStringType Type,
4552 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004553 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004554 UncoveredArgHandler &UncoveredArg,
4555 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00004556 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00004557 assert(Offset.isSigned() && "invalid offset");
4558
Douglas Gregorc25f7662009-05-19 22:10:17 +00004559 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00004560 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004561
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004562 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00004563
Richard Smithd7293d72013-08-05 18:49:43 +00004564 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00004565 // Technically -Wformat-nonliteral does not warn about this case.
4566 // The behavior of printf and friends in this case is implementation
4567 // dependent. Ideally if the format string cannot be null then
4568 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00004569 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00004570
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004571 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00004572 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004573 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00004574 // The expression is a literal if both sub-expressions were, and it was
4575 // completely checked only if both sub-expressions were checked.
4576 const AbstractConditionalOperator *C =
4577 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004578
4579 // Determine whether it is necessary to check both sub-expressions, for
4580 // example, because the condition expression is a constant that can be
4581 // evaluated at compile time.
4582 bool CheckLeft = true, CheckRight = true;
4583
4584 bool Cond;
4585 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4586 if (Cond)
4587 CheckRight = false;
4588 else
4589 CheckLeft = false;
4590 }
4591
Stephen Hines648c3692016-09-16 01:07:04 +00004592 // We need to maintain the offsets for the right and the left hand side
4593 // separately to check if every possible indexed expression is a valid
4594 // string literal. They might have different offsets for different string
4595 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004596 StringLiteralCheckType Left;
4597 if (!CheckLeft)
4598 Left = SLCT_UncheckedLiteral;
4599 else {
4600 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4601 HasVAListArg, format_idx, firstDataArg,
4602 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004603 CheckedVarArgs, UncoveredArg, Offset);
4604 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004605 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004606 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004607 }
4608
Richard Smith55ce3522012-06-25 20:30:08 +00004609 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004610 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004611 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004612 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004613 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004614
4615 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004616 }
4617
4618 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00004619 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4620 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004621 }
4622
John McCallc07a0c72011-02-17 10:25:35 +00004623 case Stmt::OpaqueValueExprClass:
4624 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4625 E = src;
4626 goto tryAgain;
4627 }
Richard Smith55ce3522012-06-25 20:30:08 +00004628 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004629
Ted Kremeneka8890832011-02-24 23:03:04 +00004630 case Stmt::PredefinedExprClass:
4631 // While __func__, etc., are technically not string literals, they
4632 // cannot contain format specifiers and thus are not a security
4633 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004634 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004635
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004636 case Stmt::DeclRefExprClass: {
4637 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004638
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004639 // As an exception, do not flag errors for variables binding to
4640 // const string literals.
4641 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4642 bool isConstant = false;
4643 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004644
Richard Smithd7293d72013-08-05 18:49:43 +00004645 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4646 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004647 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004648 isConstant = T.isConstant(S.Context) &&
4649 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004650 } else if (T->isObjCObjectPointerType()) {
4651 // In ObjC, there is usually no "const ObjectPointer" type,
4652 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004653 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004654 }
Mike Stump11289f42009-09-09 15:08:12 +00004655
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004656 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004657 if (const Expr *Init = VD->getAnyInitializer()) {
4658 // Look through initializers like const char c[] = { "foo" }
4659 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4660 if (InitList->isStringLiteralInit())
4661 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4662 }
Richard Smithd7293d72013-08-05 18:49:43 +00004663 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004664 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004665 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004666 /*InFunctionCall*/ false, CheckedVarArgs,
4667 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004668 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004669 }
Mike Stump11289f42009-09-09 15:08:12 +00004670
Anders Carlssonb012ca92009-06-28 19:55:58 +00004671 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4672 // special check to see if the format string is a function parameter
4673 // of the function calling the printf function. If the function
4674 // has an attribute indicating it is a printf-like function, then we
4675 // should suppress warnings concerning non-literals being used in a call
4676 // to a vprintf function. For example:
4677 //
4678 // void
4679 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4680 // va_list ap;
4681 // va_start(ap, fmt);
4682 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4683 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00004684 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004685 if (HasVAListArg) {
4686 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4687 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4688 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004689 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004690 // adjust for implicit parameter
4691 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4692 if (MD->isInstance())
4693 ++PVIndex;
4694 // We also check if the formats are compatible.
4695 // We can't pass a 'scanf' string to a 'printf' function.
4696 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00004697 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00004698 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004699 }
4700 }
4701 }
4702 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004703 }
Mike Stump11289f42009-09-09 15:08:12 +00004704
Richard Smith55ce3522012-06-25 20:30:08 +00004705 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004706 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004707
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004708 case Stmt::CallExprClass:
4709 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004710 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004711 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4712 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4713 unsigned ArgIndex = FA->getFormatIdx();
4714 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4715 if (MD->isInstance())
4716 --ArgIndex;
4717 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00004718
Richard Smithd7293d72013-08-05 18:49:43 +00004719 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004720 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00004721 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004722 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004723 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4724 unsigned BuiltinID = FD->getBuiltinID();
4725 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4726 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4727 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00004728 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004729 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004730 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004731 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004732 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004733 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004734 }
4735 }
Mike Stump11289f42009-09-09 15:08:12 +00004736
Richard Smith55ce3522012-06-25 20:30:08 +00004737 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004738 }
Alex Lorenzd9007142016-10-24 09:42:34 +00004739 case Stmt::ObjCMessageExprClass: {
4740 const auto *ME = cast<ObjCMessageExpr>(E);
4741 if (const auto *ND = ME->getMethodDecl()) {
4742 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4743 unsigned ArgIndex = FA->getFormatIdx();
4744 const Expr *Arg = ME->getArg(ArgIndex - 1);
4745 return checkFormatStringExpr(
4746 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4747 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4748 }
4749 }
4750
4751 return SLCT_NotALiteral;
4752 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004753 case Stmt::ObjCStringLiteralClass:
4754 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00004755 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004756
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004757 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004758 StrE = ObjCFExpr->getString();
4759 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004760 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004761
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004762 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00004763 if (Offset.isNegative() || Offset > StrE->getLength()) {
4764 // TODO: It would be better to have an explicit warning for out of
4765 // bounds literals.
4766 return SLCT_NotALiteral;
4767 }
4768 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4769 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004770 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004771 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00004772 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004773 }
Mike Stump11289f42009-09-09 15:08:12 +00004774
Richard Smith55ce3522012-06-25 20:30:08 +00004775 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004776 }
Stephen Hines648c3692016-09-16 01:07:04 +00004777 case Stmt::BinaryOperatorClass: {
4778 llvm::APSInt LResult;
4779 llvm::APSInt RResult;
4780
4781 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4782
4783 // A string literal + an int offset is still a string literal.
4784 if (BinOp->isAdditiveOp()) {
4785 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4786 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4787
4788 if (LIsInt != RIsInt) {
4789 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4790
4791 if (LIsInt) {
4792 if (BinOpKind == BO_Add) {
4793 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4794 E = BinOp->getRHS();
4795 goto tryAgain;
4796 }
4797 } else {
4798 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4799 E = BinOp->getLHS();
4800 goto tryAgain;
4801 }
4802 }
Stephen Hines648c3692016-09-16 01:07:04 +00004803 }
George Burgess IVd273aab2016-09-22 00:00:26 +00004804
4805 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00004806 }
4807 case Stmt::UnaryOperatorClass: {
4808 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4809 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4810 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4811 llvm::APSInt IndexResult;
4812 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4813 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4814 E = ASE->getBase();
4815 goto tryAgain;
4816 }
4817 }
4818
4819 return SLCT_NotALiteral;
4820 }
Mike Stump11289f42009-09-09 15:08:12 +00004821
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004822 default:
Richard Smith55ce3522012-06-25 20:30:08 +00004823 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004824 }
4825}
4826
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004827Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00004828 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00004829 .Case("scanf", FST_Scanf)
4830 .Cases("printf", "printf0", FST_Printf)
4831 .Cases("NSString", "CFString", FST_NSString)
4832 .Case("strftime", FST_Strftime)
4833 .Case("strfmon", FST_Strfmon)
4834 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4835 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4836 .Case("os_trace", FST_OSLog)
4837 .Case("os_log", FST_OSLog)
4838 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004839}
4840
Jordan Rose3e0ec582012-07-19 18:10:23 +00004841/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00004842/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00004843/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004844bool Sema::CheckFormatArguments(const FormatAttr *Format,
4845 ArrayRef<const Expr *> Args,
4846 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004847 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004848 SourceLocation Loc, SourceRange Range,
4849 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00004850 FormatStringInfo FSI;
4851 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004852 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00004853 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00004854 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00004855 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004856}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00004857
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004858bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004859 bool HasVAListArg, unsigned format_idx,
4860 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004861 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004862 SourceLocation Loc, SourceRange Range,
4863 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004864 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004865 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004866 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00004867 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004868 }
Mike Stump11289f42009-09-09 15:08:12 +00004869
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004870 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004871
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004872 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00004873 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004874 // Dynamically generated format strings are difficult to
4875 // automatically vet at compile time. Requiring that format strings
4876 // are string literals: (1) permits the checking of format strings by
4877 // the compiler and thereby (2) can practically remove the source of
4878 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00004879
Mike Stump11289f42009-09-09 15:08:12 +00004880 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00004881 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00004882 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00004883 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004884 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00004885 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00004886 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4887 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004888 /*IsFunctionCall*/ true, CheckedVarArgs,
4889 UncoveredArg,
4890 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004891
4892 // Generate a diagnostic where an uncovered argument is detected.
4893 if (UncoveredArg.hasUncoveredArg()) {
4894 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4895 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4896 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4897 }
4898
Richard Smith55ce3522012-06-25 20:30:08 +00004899 if (CT != SLCT_NotALiteral)
4900 // Literal format string found, check done!
4901 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00004902
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004903 // Strftime is particular as it always uses a single 'time' argument,
4904 // so it is safe to pass a non-literal string.
4905 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00004906 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004907
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004908 // Do not emit diag when the string param is a macro expansion and the
4909 // format is either NSString or CFString. This is a hack to prevent
4910 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4911 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004912 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4913 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00004914 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004915
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004916 // If there are no arguments specified, warn with -Wformat-security, otherwise
4917 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004918 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00004919 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4920 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004921 switch (Type) {
4922 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004923 break;
4924 case FST_Kprintf:
4925 case FST_FreeBSDKPrintf:
4926 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00004927 Diag(FormatLoc, diag::note_format_security_fixit)
4928 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004929 break;
4930 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00004931 Diag(FormatLoc, diag::note_format_security_fixit)
4932 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004933 break;
4934 }
4935 } else {
4936 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004937 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004938 }
Richard Smith55ce3522012-06-25 20:30:08 +00004939 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004940}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004941
Ted Kremenekab278de2010-01-28 23:39:18 +00004942namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00004943class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4944protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00004945 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00004946 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00004947 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00004948 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00004949 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00004950 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00004951 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00004952 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004953 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00004954 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00004955 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00004956 bool usesPositionalArgs;
4957 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004958 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00004959 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00004960 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004961 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004962
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004963public:
Stephen Hines648c3692016-09-16 01:07:04 +00004964 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00004965 const Expr *origFormatExpr,
4966 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004967 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00004968 ArrayRef<const Expr *> Args, unsigned formatIdx,
4969 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004970 llvm::SmallBitVector &CheckedVarArgs,
4971 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00004972 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
4973 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
4974 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
4975 usesPositionalArgs(false), atFirstArg(true),
4976 inFunctionCall(inFunctionCall), CallType(callType),
4977 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00004978 CoveredArgs.resize(numDataArgs);
4979 CoveredArgs.reset();
4980 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004981
Ted Kremenek019d2242010-01-29 01:50:07 +00004982 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004983
Ted Kremenek02087932010-07-16 02:11:22 +00004984 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004985 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004986
Jordan Rose92303592012-09-08 04:00:03 +00004987 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004988 const analyze_format_string::FormatSpecifier &FS,
4989 const analyze_format_string::ConversionSpecifier &CS,
4990 const char *startSpecifier, unsigned specifierLen,
4991 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00004992
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004993 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004994 const analyze_format_string::FormatSpecifier &FS,
4995 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004996
4997 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004998 const analyze_format_string::ConversionSpecifier &CS,
4999 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005000
Craig Toppere14c0f82014-03-12 04:55:44 +00005001 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005002
Craig Toppere14c0f82014-03-12 04:55:44 +00005003 void HandleInvalidPosition(const char *startSpecifier,
5004 unsigned specifierLen,
5005 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005006
Craig Toppere14c0f82014-03-12 04:55:44 +00005007 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005008
Craig Toppere14c0f82014-03-12 04:55:44 +00005009 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005010
Richard Trieu03cf7b72011-10-28 00:41:25 +00005011 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00005012 static void
5013 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5014 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5015 bool IsStringLocation, Range StringRange,
5016 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005017
Ted Kremenek02087932010-07-16 02:11:22 +00005018protected:
Ted Kremenekce815422010-07-19 21:25:57 +00005019 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5020 const char *startSpec,
5021 unsigned specifierLen,
5022 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005023
5024 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5025 const char *startSpec,
5026 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00005027
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005028 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00005029 CharSourceRange getSpecifierRange(const char *startSpecifier,
5030 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00005031 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005032
Ted Kremenek5739de72010-01-29 01:06:55 +00005033 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005034
5035 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5036 const analyze_format_string::ConversionSpecifier &CS,
5037 const char *startSpecifier, unsigned specifierLen,
5038 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005039
5040 template <typename Range>
5041 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5042 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005043 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00005044};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005045} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005046
Ted Kremenek02087932010-07-16 02:11:22 +00005047SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00005048 return OrigFormatExpr->getSourceRange();
5049}
5050
Ted Kremenek02087932010-07-16 02:11:22 +00005051CharSourceRange CheckFormatHandler::
5052getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00005053 SourceLocation Start = getLocationOfByte(startSpecifier);
5054 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5055
5056 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00005057 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00005058
5059 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005060}
5061
Ted Kremenek02087932010-07-16 02:11:22 +00005062SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00005063 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5064 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00005065}
5066
Ted Kremenek02087932010-07-16 02:11:22 +00005067void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5068 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00005069 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5070 getLocationOfByte(startSpecifier),
5071 /*IsStringLocation*/true,
5072 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00005073}
5074
Jordan Rose92303592012-09-08 04:00:03 +00005075void CheckFormatHandler::HandleInvalidLengthModifier(
5076 const analyze_format_string::FormatSpecifier &FS,
5077 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00005078 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00005079 using namespace analyze_format_string;
5080
5081 const LengthModifier &LM = FS.getLengthModifier();
5082 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5083
5084 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005085 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00005086 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005087 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005088 getLocationOfByte(LM.getStart()),
5089 /*IsStringLocation*/true,
5090 getSpecifierRange(startSpecifier, specifierLen));
5091
5092 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5093 << FixedLM->toString()
5094 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5095
5096 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005097 FixItHint Hint;
5098 if (DiagID == diag::warn_format_nonsensical_length)
5099 Hint = FixItHint::CreateRemoval(LMRange);
5100
5101 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005102 getLocationOfByte(LM.getStart()),
5103 /*IsStringLocation*/true,
5104 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00005105 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00005106 }
5107}
5108
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005109void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005110 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005111 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005112 using namespace analyze_format_string;
5113
5114 const LengthModifier &LM = FS.getLengthModifier();
5115 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5116
5117 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005118 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005119 if (FixedLM) {
5120 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5121 << LM.toString() << 0,
5122 getLocationOfByte(LM.getStart()),
5123 /*IsStringLocation*/true,
5124 getSpecifierRange(startSpecifier, specifierLen));
5125
5126 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5127 << FixedLM->toString()
5128 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5129
5130 } else {
5131 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5132 << LM.toString() << 0,
5133 getLocationOfByte(LM.getStart()),
5134 /*IsStringLocation*/true,
5135 getSpecifierRange(startSpecifier, specifierLen));
5136 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005137}
5138
5139void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5140 const analyze_format_string::ConversionSpecifier &CS,
5141 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005142 using namespace analyze_format_string;
5143
5144 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005145 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005146 if (FixedCS) {
5147 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5148 << CS.toString() << /*conversion specifier*/1,
5149 getLocationOfByte(CS.getStart()),
5150 /*IsStringLocation*/true,
5151 getSpecifierRange(startSpecifier, specifierLen));
5152
5153 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5154 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5155 << FixedCS->toString()
5156 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5157 } else {
5158 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5159 << CS.toString() << /*conversion specifier*/1,
5160 getLocationOfByte(CS.getStart()),
5161 /*IsStringLocation*/true,
5162 getSpecifierRange(startSpecifier, specifierLen));
5163 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005164}
5165
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005166void CheckFormatHandler::HandlePosition(const char *startPos,
5167 unsigned posLen) {
5168 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5169 getLocationOfByte(startPos),
5170 /*IsStringLocation*/true,
5171 getSpecifierRange(startPos, posLen));
5172}
5173
Ted Kremenekd1668192010-02-27 01:41:03 +00005174void
Ted Kremenek02087932010-07-16 02:11:22 +00005175CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5176 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005177 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5178 << (unsigned) p,
5179 getLocationOfByte(startPos), /*IsStringLocation*/true,
5180 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005181}
5182
Ted Kremenek02087932010-07-16 02:11:22 +00005183void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005184 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005185 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5186 getLocationOfByte(startPos),
5187 /*IsStringLocation*/true,
5188 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005189}
5190
Ted Kremenek02087932010-07-16 02:11:22 +00005191void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005192 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005193 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005194 EmitFormatDiagnostic(
5195 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5196 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5197 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005198 }
Ted Kremenek02087932010-07-16 02:11:22 +00005199}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005200
Jordan Rose58bbe422012-07-19 18:10:08 +00005201// Note that this may return NULL if there was an error parsing or building
5202// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005203const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005204 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005205}
5206
5207void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005208 // Does the number of data arguments exceed the number of
5209 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005210 if (!HasVAListArg) {
5211 // Find any arguments that weren't covered.
5212 CoveredArgs.flip();
5213 signed notCoveredArg = CoveredArgs.find_first();
5214 if (notCoveredArg >= 0) {
5215 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005216 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5217 } else {
5218 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005219 }
5220 }
5221}
5222
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005223void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5224 const Expr *ArgExpr) {
5225 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5226 "Invalid state");
5227
5228 if (!ArgExpr)
5229 return;
5230
5231 SourceLocation Loc = ArgExpr->getLocStart();
5232
5233 if (S.getSourceManager().isInSystemMacro(Loc))
5234 return;
5235
5236 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5237 for (auto E : DiagnosticExprs)
5238 PDiag << E->getSourceRange();
5239
5240 CheckFormatHandler::EmitFormatDiagnostic(
5241 S, IsFunctionCall, DiagnosticExprs[0],
5242 PDiag, Loc, /*IsStringLocation*/false,
5243 DiagnosticExprs[0]->getSourceRange());
5244}
5245
Ted Kremenekce815422010-07-19 21:25:57 +00005246bool
5247CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5248 SourceLocation Loc,
5249 const char *startSpec,
5250 unsigned specifierLen,
5251 const char *csStart,
5252 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005253 bool keepGoing = true;
5254 if (argIndex < NumDataArgs) {
5255 // Consider the argument coverered, even though the specifier doesn't
5256 // make sense.
5257 CoveredArgs.set(argIndex);
5258 }
5259 else {
5260 // If argIndex exceeds the number of data arguments we
5261 // don't issue a warning because that is just a cascade of warnings (and
5262 // they may have intended '%%' anyway). We don't want to continue processing
5263 // the format string after this point, however, as we will like just get
5264 // gibberish when trying to match arguments.
5265 keepGoing = false;
5266 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005267
5268 StringRef Specifier(csStart, csLen);
5269
5270 // If the specifier in non-printable, it could be the first byte of a UTF-8
5271 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5272 // hex value.
5273 std::string CodePointStr;
5274 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005275 llvm::UTF32 CodePoint;
5276 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5277 const llvm::UTF8 *E =
5278 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5279 llvm::ConversionResult Result =
5280 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005281
Justin Lebar90910552016-09-30 00:38:45 +00005282 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005283 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005284 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005285 }
5286
5287 llvm::raw_string_ostream OS(CodePointStr);
5288 if (CodePoint < 256)
5289 OS << "\\x" << llvm::format("%02x", CodePoint);
5290 else if (CodePoint <= 0xFFFF)
5291 OS << "\\u" << llvm::format("%04x", CodePoint);
5292 else
5293 OS << "\\U" << llvm::format("%08x", CodePoint);
5294 OS.flush();
5295 Specifier = CodePointStr;
5296 }
5297
5298 EmitFormatDiagnostic(
5299 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5300 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5301
Ted Kremenekce815422010-07-19 21:25:57 +00005302 return keepGoing;
5303}
5304
Richard Trieu03cf7b72011-10-28 00:41:25 +00005305void
5306CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5307 const char *startSpec,
5308 unsigned specifierLen) {
5309 EmitFormatDiagnostic(
5310 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5311 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5312}
5313
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005314bool
5315CheckFormatHandler::CheckNumArgs(
5316 const analyze_format_string::FormatSpecifier &FS,
5317 const analyze_format_string::ConversionSpecifier &CS,
5318 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5319
5320 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005321 PartialDiagnostic PDiag = FS.usesPositionalArg()
5322 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5323 << (argIndex+1) << NumDataArgs)
5324 : S.PDiag(diag::warn_printf_insufficient_data_args);
5325 EmitFormatDiagnostic(
5326 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5327 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005328
5329 // Since more arguments than conversion tokens are given, by extension
5330 // all arguments are covered, so mark this as so.
5331 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005332 return false;
5333 }
5334 return true;
5335}
5336
Richard Trieu03cf7b72011-10-28 00:41:25 +00005337template<typename Range>
5338void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5339 SourceLocation Loc,
5340 bool IsStringLocation,
5341 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005342 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005343 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005344 Loc, IsStringLocation, StringRange, FixIt);
5345}
5346
5347/// \brief If the format string is not within the funcion call, emit a note
5348/// so that the function call and string are in diagnostic messages.
5349///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005350/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005351/// call and only one diagnostic message will be produced. Otherwise, an
5352/// extra note will be emitted pointing to location of the format string.
5353///
5354/// \param ArgumentExpr the expression that is passed as the format string
5355/// argument in the function call. Used for getting locations when two
5356/// diagnostics are emitted.
5357///
5358/// \param PDiag the callee should already have provided any strings for the
5359/// diagnostic message. This function only adds locations and fixits
5360/// to diagnostics.
5361///
5362/// \param Loc primary location for diagnostic. If two diagnostics are
5363/// required, one will be at Loc and a new SourceLocation will be created for
5364/// the other one.
5365///
5366/// \param IsStringLocation if true, Loc points to the format string should be
5367/// used for the note. Otherwise, Loc points to the argument list and will
5368/// be used with PDiag.
5369///
5370/// \param StringRange some or all of the string to highlight. This is
5371/// templated so it can accept either a CharSourceRange or a SourceRange.
5372///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005373/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005374template <typename Range>
5375void CheckFormatHandler::EmitFormatDiagnostic(
5376 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5377 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5378 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005379 if (InFunctionCall) {
5380 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5381 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005382 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00005383 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005384 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5385 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00005386
5387 const Sema::SemaDiagnosticBuilder &Note =
5388 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5389 diag::note_format_string_defined);
5390
5391 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005392 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005393 }
5394}
5395
Ted Kremenek02087932010-07-16 02:11:22 +00005396//===--- CHECK: Printf format string checking ------------------------------===//
5397
5398namespace {
5399class CheckPrintfHandler : public CheckFormatHandler {
5400public:
Stephen Hines648c3692016-09-16 01:07:04 +00005401 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005402 const Expr *origFormatExpr,
5403 const Sema::FormatStringType type, unsigned firstDataArg,
5404 unsigned numDataArgs, bool isObjC, const char *beg,
5405 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005406 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005407 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005408 llvm::SmallBitVector &CheckedVarArgs,
5409 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005410 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5411 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5412 inFunctionCall, CallType, CheckedVarArgs,
5413 UncoveredArg) {}
5414
5415 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5416
5417 /// Returns true if '%@' specifiers are allowed in the format string.
5418 bool allowsObjCArg() const {
5419 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5420 FSType == Sema::FST_OSTrace;
5421 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00005422
Ted Kremenek02087932010-07-16 02:11:22 +00005423 bool HandleInvalidPrintfConversionSpecifier(
5424 const analyze_printf::PrintfSpecifier &FS,
5425 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005426 unsigned specifierLen) override;
5427
Ted Kremenek02087932010-07-16 02:11:22 +00005428 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5429 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005430 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005431 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5432 const char *StartSpecifier,
5433 unsigned SpecifierLen,
5434 const Expr *E);
5435
Ted Kremenek02087932010-07-16 02:11:22 +00005436 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5437 const char *startSpecifier, unsigned specifierLen);
5438 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5439 const analyze_printf::OptionalAmount &Amt,
5440 unsigned type,
5441 const char *startSpecifier, unsigned specifierLen);
5442 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5443 const analyze_printf::OptionalFlag &flag,
5444 const char *startSpecifier, unsigned specifierLen);
5445 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5446 const analyze_printf::OptionalFlag &ignoredFlag,
5447 const analyze_printf::OptionalFlag &flag,
5448 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005449 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00005450 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00005451
5452 void HandleEmptyObjCModifierFlag(const char *startFlag,
5453 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005454
Ted Kremenek2b417712015-07-02 05:39:16 +00005455 void HandleInvalidObjCModifierFlag(const char *startFlag,
5456 unsigned flagLen) override;
5457
5458 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5459 const char *flagsEnd,
5460 const char *conversionPosition)
5461 override;
5462};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005463} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00005464
5465bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5466 const analyze_printf::PrintfSpecifier &FS,
5467 const char *startSpecifier,
5468 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005469 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005470 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005471
Ted Kremenekce815422010-07-19 21:25:57 +00005472 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5473 getLocationOfByte(CS.getStart()),
5474 startSpecifier, specifierLen,
5475 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00005476}
5477
Ted Kremenek02087932010-07-16 02:11:22 +00005478bool CheckPrintfHandler::HandleAmount(
5479 const analyze_format_string::OptionalAmount &Amt,
5480 unsigned k, const char *startSpecifier,
5481 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005482 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005483 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00005484 unsigned argIndex = Amt.getArgIndex();
5485 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005486 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5487 << k,
5488 getLocationOfByte(Amt.getStart()),
5489 /*IsStringLocation*/true,
5490 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005491 // Don't do any more checking. We will just emit
5492 // spurious errors.
5493 return false;
5494 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005495
Ted Kremenek5739de72010-01-29 01:06:55 +00005496 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00005497 // Although not in conformance with C99, we also allow the argument to be
5498 // an 'unsigned int' as that is a reasonably safe case. GCC also
5499 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00005500 CoveredArgs.set(argIndex);
5501 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005502 if (!Arg)
5503 return false;
5504
Ted Kremenek5739de72010-01-29 01:06:55 +00005505 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005506
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005507 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5508 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005509
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005510 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005511 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005512 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00005513 << T << Arg->getSourceRange(),
5514 getLocationOfByte(Amt.getStart()),
5515 /*IsStringLocation*/true,
5516 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005517 // Don't do any more checking. We will just emit
5518 // spurious errors.
5519 return false;
5520 }
5521 }
5522 }
5523 return true;
5524}
Ted Kremenek5739de72010-01-29 01:06:55 +00005525
Tom Careb49ec692010-06-17 19:00:27 +00005526void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00005527 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005528 const analyze_printf::OptionalAmount &Amt,
5529 unsigned type,
5530 const char *startSpecifier,
5531 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005532 const analyze_printf::PrintfConversionSpecifier &CS =
5533 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00005534
Richard Trieu03cf7b72011-10-28 00:41:25 +00005535 FixItHint fixit =
5536 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5537 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5538 Amt.getConstantLength()))
5539 : FixItHint();
5540
5541 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5542 << type << CS.toString(),
5543 getLocationOfByte(Amt.getStart()),
5544 /*IsStringLocation*/true,
5545 getSpecifierRange(startSpecifier, specifierLen),
5546 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00005547}
5548
Ted Kremenek02087932010-07-16 02:11:22 +00005549void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005550 const analyze_printf::OptionalFlag &flag,
5551 const char *startSpecifier,
5552 unsigned specifierLen) {
5553 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005554 const analyze_printf::PrintfConversionSpecifier &CS =
5555 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00005556 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5557 << flag.toString() << CS.toString(),
5558 getLocationOfByte(flag.getPosition()),
5559 /*IsStringLocation*/true,
5560 getSpecifierRange(startSpecifier, specifierLen),
5561 FixItHint::CreateRemoval(
5562 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005563}
5564
5565void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00005566 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005567 const analyze_printf::OptionalFlag &ignoredFlag,
5568 const analyze_printf::OptionalFlag &flag,
5569 const char *startSpecifier,
5570 unsigned specifierLen) {
5571 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005572 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5573 << ignoredFlag.toString() << flag.toString(),
5574 getLocationOfByte(ignoredFlag.getPosition()),
5575 /*IsStringLocation*/true,
5576 getSpecifierRange(startSpecifier, specifierLen),
5577 FixItHint::CreateRemoval(
5578 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005579}
5580
Ted Kremenek2b417712015-07-02 05:39:16 +00005581// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5582// bool IsStringLocation, Range StringRange,
5583// ArrayRef<FixItHint> Fixit = None);
5584
5585void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5586 unsigned flagLen) {
5587 // Warn about an empty flag.
5588 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5589 getLocationOfByte(startFlag),
5590 /*IsStringLocation*/true,
5591 getSpecifierRange(startFlag, flagLen));
5592}
5593
5594void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5595 unsigned flagLen) {
5596 // Warn about an invalid flag.
5597 auto Range = getSpecifierRange(startFlag, flagLen);
5598 StringRef flag(startFlag, flagLen);
5599 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5600 getLocationOfByte(startFlag),
5601 /*IsStringLocation*/true,
5602 Range, FixItHint::CreateRemoval(Range));
5603}
5604
5605void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5606 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5607 // Warn about using '[...]' without a '@' conversion.
5608 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5609 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5610 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5611 getLocationOfByte(conversionPosition),
5612 /*IsStringLocation*/true,
5613 Range, FixItHint::CreateRemoval(Range));
5614}
5615
Richard Smith55ce3522012-06-25 20:30:08 +00005616// Determines if the specified is a C++ class or struct containing
5617// a member with the specified name and kind (e.g. a CXXMethodDecl named
5618// "c_str()").
5619template<typename MemberKind>
5620static llvm::SmallPtrSet<MemberKind*, 1>
5621CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5622 const RecordType *RT = Ty->getAs<RecordType>();
5623 llvm::SmallPtrSet<MemberKind*, 1> Results;
5624
5625 if (!RT)
5626 return Results;
5627 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005628 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005629 return Results;
5630
Alp Tokerb6cc5922014-05-03 03:45:55 +00005631 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005632 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005633 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005634
5635 // We just need to include all members of the right kind turned up by the
5636 // filter, at this point.
5637 if (S.LookupQualifiedName(R, RT->getDecl()))
5638 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5639 NamedDecl *decl = (*I)->getUnderlyingDecl();
5640 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5641 Results.insert(FK);
5642 }
5643 return Results;
5644}
5645
Richard Smith2868a732014-02-28 01:36:39 +00005646/// Check if we could call '.c_str()' on an object.
5647///
5648/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5649/// allow the call, or if it would be ambiguous).
5650bool Sema::hasCStrMethod(const Expr *E) {
5651 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5652 MethodSet Results =
5653 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5654 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5655 MI != ME; ++MI)
5656 if ((*MI)->getMinRequiredArguments() == 0)
5657 return true;
5658 return false;
5659}
5660
Richard Smith55ce3522012-06-25 20:30:08 +00005661// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005662// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00005663// Returns true when a c_str() conversion method is found.
5664bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00005665 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00005666 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5667
5668 MethodSet Results =
5669 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5670
5671 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5672 MI != ME; ++MI) {
5673 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00005674 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00005675 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00005676 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00005677 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00005678 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5679 << "c_str()"
5680 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5681 return true;
5682 }
5683 }
5684
5685 return false;
5686}
5687
Ted Kremenekab278de2010-01-28 23:39:18 +00005688bool
Ted Kremenek02087932010-07-16 02:11:22 +00005689CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00005690 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00005691 const char *startSpecifier,
5692 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005693 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00005694 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005695 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00005696
Ted Kremenek6cd69422010-07-19 22:01:06 +00005697 if (FS.consumesDataArgument()) {
5698 if (atFirstArg) {
5699 atFirstArg = false;
5700 usesPositionalArgs = FS.usesPositionalArg();
5701 }
5702 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005703 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5704 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005705 return false;
5706 }
Ted Kremenek5739de72010-01-29 01:06:55 +00005707 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005708
Ted Kremenekd1668192010-02-27 01:41:03 +00005709 // First check if the field width, precision, and conversion specifier
5710 // have matching data arguments.
5711 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5712 startSpecifier, specifierLen)) {
5713 return false;
5714 }
5715
5716 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5717 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005718 return false;
5719 }
5720
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005721 if (!CS.consumesDataArgument()) {
5722 // FIXME: Technically specifying a precision or field width here
5723 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00005724 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005725 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005726
Ted Kremenek4a49d982010-02-26 19:18:41 +00005727 // Consume the argument.
5728 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00005729 if (argIndex < NumDataArgs) {
5730 // The check to see if the argIndex is valid will come later.
5731 // We set the bit here because we may exit early from this
5732 // function if we encounter some other error.
5733 CoveredArgs.set(argIndex);
5734 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00005735
Dimitry Andric6b5ed342015-02-19 22:32:33 +00005736 // FreeBSD kernel extensions.
5737 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5738 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5739 // We need at least two arguments.
5740 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5741 return false;
5742
5743 // Claim the second argument.
5744 CoveredArgs.set(argIndex + 1);
5745
5746 // Type check the first argument (int for %b, pointer for %D)
5747 const Expr *Ex = getDataArg(argIndex);
5748 const analyze_printf::ArgType &AT =
5749 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5750 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5751 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5752 EmitFormatDiagnostic(
5753 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5754 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5755 << false << Ex->getSourceRange(),
5756 Ex->getLocStart(), /*IsStringLocation*/false,
5757 getSpecifierRange(startSpecifier, specifierLen));
5758
5759 // Type check the second argument (char * for both %b and %D)
5760 Ex = getDataArg(argIndex + 1);
5761 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5762 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5763 EmitFormatDiagnostic(
5764 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5765 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5766 << false << Ex->getSourceRange(),
5767 Ex->getLocStart(), /*IsStringLocation*/false,
5768 getSpecifierRange(startSpecifier, specifierLen));
5769
5770 return true;
5771 }
5772
Ted Kremenek4a49d982010-02-26 19:18:41 +00005773 // Check for using an Objective-C specific conversion specifier
5774 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00005775 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00005776 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5777 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00005778 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005779
Mehdi Amini06d367c2016-10-24 20:39:34 +00005780 // %P can only be used with os_log.
5781 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
5782 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5783 specifierLen);
5784 }
5785
5786 // %n is not allowed with os_log.
5787 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
5788 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
5789 getLocationOfByte(CS.getStart()),
5790 /*IsStringLocation*/ false,
5791 getSpecifierRange(startSpecifier, specifierLen));
5792
5793 return true;
5794 }
5795
5796 // Only scalars are allowed for os_trace.
5797 if (FSType == Sema::FST_OSTrace &&
5798 (CS.getKind() == ConversionSpecifier::PArg ||
5799 CS.getKind() == ConversionSpecifier::sArg ||
5800 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
5801 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5802 specifierLen);
5803 }
5804
5805 // Check for use of public/private annotation outside of os_log().
5806 if (FSType != Sema::FST_OSLog) {
5807 if (FS.isPublic().isSet()) {
5808 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5809 << "public",
5810 getLocationOfByte(FS.isPublic().getPosition()),
5811 /*IsStringLocation*/ false,
5812 getSpecifierRange(startSpecifier, specifierLen));
5813 }
5814 if (FS.isPrivate().isSet()) {
5815 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5816 << "private",
5817 getLocationOfByte(FS.isPrivate().getPosition()),
5818 /*IsStringLocation*/ false,
5819 getSpecifierRange(startSpecifier, specifierLen));
5820 }
5821 }
5822
Tom Careb49ec692010-06-17 19:00:27 +00005823 // Check for invalid use of field width
5824 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00005825 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00005826 startSpecifier, specifierLen);
5827 }
5828
5829 // Check for invalid use of precision
5830 if (!FS.hasValidPrecision()) {
5831 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5832 startSpecifier, specifierLen);
5833 }
5834
Mehdi Amini06d367c2016-10-24 20:39:34 +00005835 // Precision is mandatory for %P specifier.
5836 if (CS.getKind() == ConversionSpecifier::PArg &&
5837 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
5838 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
5839 getLocationOfByte(startSpecifier),
5840 /*IsStringLocation*/ false,
5841 getSpecifierRange(startSpecifier, specifierLen));
5842 }
5843
Tom Careb49ec692010-06-17 19:00:27 +00005844 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00005845 if (!FS.hasValidThousandsGroupingPrefix())
5846 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005847 if (!FS.hasValidLeadingZeros())
5848 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5849 if (!FS.hasValidPlusPrefix())
5850 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00005851 if (!FS.hasValidSpacePrefix())
5852 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005853 if (!FS.hasValidAlternativeForm())
5854 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5855 if (!FS.hasValidLeftJustified())
5856 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5857
5858 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00005859 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5860 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5861 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005862 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5863 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5864 startSpecifier, specifierLen);
5865
5866 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005867 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005868 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5869 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005870 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005871 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005872 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005873 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5874 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00005875
Jordan Rose92303592012-09-08 04:00:03 +00005876 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5877 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5878
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005879 // The remaining checks depend on the data arguments.
5880 if (HasVAListArg)
5881 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005882
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005883 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005884 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005885
Jordan Rose58bbe422012-07-19 18:10:08 +00005886 const Expr *Arg = getDataArg(argIndex);
5887 if (!Arg)
5888 return true;
5889
5890 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00005891}
5892
Jordan Roseaee34382012-09-05 22:56:26 +00005893static bool requiresParensToAddCast(const Expr *E) {
5894 // FIXME: We should have a general way to reason about operator
5895 // precedence and whether parens are actually needed here.
5896 // Take care of a few common cases where they aren't.
5897 const Expr *Inside = E->IgnoreImpCasts();
5898 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5899 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5900
5901 switch (Inside->getStmtClass()) {
5902 case Stmt::ArraySubscriptExprClass:
5903 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005904 case Stmt::CharacterLiteralClass:
5905 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005906 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005907 case Stmt::FloatingLiteralClass:
5908 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005909 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005910 case Stmt::ObjCArrayLiteralClass:
5911 case Stmt::ObjCBoolLiteralExprClass:
5912 case Stmt::ObjCBoxedExprClass:
5913 case Stmt::ObjCDictionaryLiteralClass:
5914 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005915 case Stmt::ObjCIvarRefExprClass:
5916 case Stmt::ObjCMessageExprClass:
5917 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005918 case Stmt::ObjCStringLiteralClass:
5919 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005920 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005921 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005922 case Stmt::UnaryOperatorClass:
5923 return false;
5924 default:
5925 return true;
5926 }
5927}
5928
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005929static std::pair<QualType, StringRef>
5930shouldNotPrintDirectly(const ASTContext &Context,
5931 QualType IntendedTy,
5932 const Expr *E) {
5933 // Use a 'while' to peel off layers of typedefs.
5934 QualType TyTy = IntendedTy;
5935 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5936 StringRef Name = UserTy->getDecl()->getName();
5937 QualType CastTy = llvm::StringSwitch<QualType>(Name)
5938 .Case("NSInteger", Context.LongTy)
5939 .Case("NSUInteger", Context.UnsignedLongTy)
5940 .Case("SInt32", Context.IntTy)
5941 .Case("UInt32", Context.UnsignedIntTy)
5942 .Default(QualType());
5943
5944 if (!CastTy.isNull())
5945 return std::make_pair(CastTy, Name);
5946
5947 TyTy = UserTy->desugar();
5948 }
5949
5950 // Strip parens if necessary.
5951 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5952 return shouldNotPrintDirectly(Context,
5953 PE->getSubExpr()->getType(),
5954 PE->getSubExpr());
5955
5956 // If this is a conditional expression, then its result type is constructed
5957 // via usual arithmetic conversions and thus there might be no necessary
5958 // typedef sugar there. Recurse to operands to check for NSInteger &
5959 // Co. usage condition.
5960 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5961 QualType TrueTy, FalseTy;
5962 StringRef TrueName, FalseName;
5963
5964 std::tie(TrueTy, TrueName) =
5965 shouldNotPrintDirectly(Context,
5966 CO->getTrueExpr()->getType(),
5967 CO->getTrueExpr());
5968 std::tie(FalseTy, FalseName) =
5969 shouldNotPrintDirectly(Context,
5970 CO->getFalseExpr()->getType(),
5971 CO->getFalseExpr());
5972
5973 if (TrueTy == FalseTy)
5974 return std::make_pair(TrueTy, TrueName);
5975 else if (TrueTy.isNull())
5976 return std::make_pair(FalseTy, FalseName);
5977 else if (FalseTy.isNull())
5978 return std::make_pair(TrueTy, TrueName);
5979 }
5980
5981 return std::make_pair(QualType(), StringRef());
5982}
5983
Richard Smith55ce3522012-06-25 20:30:08 +00005984bool
5985CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5986 const char *StartSpecifier,
5987 unsigned SpecifierLen,
5988 const Expr *E) {
5989 using namespace analyze_format_string;
5990 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005991 // Now type check the data expression that matches the
5992 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00005993 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00005994 if (!AT.isValid())
5995 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00005996
Jordan Rose598ec092012-12-05 18:44:40 +00005997 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00005998 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5999 ExprTy = TET->getUnderlyingExpr()->getType();
6000 }
6001
Seth Cantrellb4802962015-03-04 03:12:10 +00006002 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6003
6004 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00006005 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006006 }
Jordan Rose98709982012-06-04 22:48:57 +00006007
Jordan Rose22b74712012-09-05 22:56:19 +00006008 // Look through argument promotions for our error message's reported type.
6009 // This includes the integral and floating promotions, but excludes array
6010 // and function pointer decay; seeing that an argument intended to be a
6011 // string has type 'char [6]' is probably more confusing than 'char *'.
6012 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6013 if (ICE->getCastKind() == CK_IntegralCast ||
6014 ICE->getCastKind() == CK_FloatingCast) {
6015 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006016 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006017
6018 // Check if we didn't match because of an implicit cast from a 'char'
6019 // or 'short' to an 'int'. This is done because printf is a varargs
6020 // function.
6021 if (ICE->getType() == S.Context.IntTy ||
6022 ICE->getType() == S.Context.UnsignedIntTy) {
6023 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006024 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006025 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006026 }
Jordan Rose98709982012-06-04 22:48:57 +00006027 }
Jordan Rose598ec092012-12-05 18:44:40 +00006028 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6029 // Special case for 'a', which has type 'int' in C.
6030 // Note, however, that we do /not/ want to treat multibyte constants like
6031 // 'MooV' as characters! This form is deprecated but still exists.
6032 if (ExprTy == S.Context.IntTy)
6033 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6034 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006035 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006036
Jordan Rosebc53ed12014-05-31 04:12:14 +00006037 // Look through enums to their underlying type.
6038 bool IsEnum = false;
6039 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6040 ExprTy = EnumTy->getDecl()->getIntegerType();
6041 IsEnum = true;
6042 }
6043
Jordan Rose0e5badd2012-12-05 18:44:49 +00006044 // %C in an Objective-C context prints a unichar, not a wchar_t.
6045 // If the argument is an integer of some kind, believe the %C and suggest
6046 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006047 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006048 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006049 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6050 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6051 !ExprTy->isCharType()) {
6052 // 'unichar' is defined as a typedef of unsigned short, but we should
6053 // prefer using the typedef if it is visible.
6054 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006055
6056 // While we are here, check if the value is an IntegerLiteral that happens
6057 // to be within the valid range.
6058 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6059 const llvm::APInt &V = IL->getValue();
6060 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6061 return true;
6062 }
6063
Jordan Rose0e5badd2012-12-05 18:44:49 +00006064 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6065 Sema::LookupOrdinaryName);
6066 if (S.LookupName(Result, S.getCurScope())) {
6067 NamedDecl *ND = Result.getFoundDecl();
6068 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6069 if (TD->getUnderlyingType() == IntendedTy)
6070 IntendedTy = S.Context.getTypedefType(TD);
6071 }
6072 }
6073 }
6074
6075 // Special-case some of Darwin's platform-independence types by suggesting
6076 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006077 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006078 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006079 QualType CastTy;
6080 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6081 if (!CastTy.isNull()) {
6082 IntendedTy = CastTy;
6083 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006084 }
6085 }
6086
Jordan Rose22b74712012-09-05 22:56:19 +00006087 // We may be able to offer a FixItHint if it is a supported type.
6088 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006089 bool success =
6090 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006091
Jordan Rose22b74712012-09-05 22:56:19 +00006092 if (success) {
6093 // Get the fix string from the fixed format specifier
6094 SmallString<16> buf;
6095 llvm::raw_svector_ostream os(buf);
6096 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006097
Jordan Roseaee34382012-09-05 22:56:26 +00006098 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6099
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006100 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00006101 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6102 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6103 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6104 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00006105 // In this case, the specifier is wrong and should be changed to match
6106 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006107 EmitFormatDiagnostic(S.PDiag(diag)
6108 << AT.getRepresentativeTypeName(S.Context)
6109 << IntendedTy << IsEnum << E->getSourceRange(),
6110 E->getLocStart(),
6111 /*IsStringLocation*/ false, SpecRange,
6112 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006113 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006114 // The canonical type for formatting this value is different from the
6115 // actual type of the expression. (This occurs, for example, with Darwin's
6116 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6117 // should be printed as 'long' for 64-bit compatibility.)
6118 // Rather than emitting a normal format/argument mismatch, we want to
6119 // add a cast to the recommended type (and correct the format string
6120 // if necessary).
6121 SmallString<16> CastBuf;
6122 llvm::raw_svector_ostream CastFix(CastBuf);
6123 CastFix << "(";
6124 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6125 CastFix << ")";
6126
6127 SmallVector<FixItHint,4> Hints;
6128 if (!AT.matchesType(S.Context, IntendedTy))
6129 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6130
6131 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6132 // If there's already a cast present, just replace it.
6133 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6134 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6135
6136 } else if (!requiresParensToAddCast(E)) {
6137 // If the expression has high enough precedence,
6138 // just write the C-style cast.
6139 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6140 CastFix.str()));
6141 } else {
6142 // Otherwise, add parens around the expression as well as the cast.
6143 CastFix << "(";
6144 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6145 CastFix.str()));
6146
Alp Tokerb6cc5922014-05-03 03:45:55 +00006147 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006148 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6149 }
6150
Jordan Rose0e5badd2012-12-05 18:44:49 +00006151 if (ShouldNotPrintDirectly) {
6152 // The expression has a type that should not be printed directly.
6153 // We extract the name from the typedef because we don't want to show
6154 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006155 StringRef Name;
6156 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6157 Name = TypedefTy->getDecl()->getName();
6158 else
6159 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006160 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006161 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006162 << E->getSourceRange(),
6163 E->getLocStart(), /*IsStringLocation=*/false,
6164 SpecRange, Hints);
6165 } else {
6166 // In this case, the expression could be printed using a different
6167 // specifier, but we've decided that the specifier is probably correct
6168 // and we should cast instead. Just use the normal warning message.
6169 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006170 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6171 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006172 << E->getSourceRange(),
6173 E->getLocStart(), /*IsStringLocation*/false,
6174 SpecRange, Hints);
6175 }
Jordan Roseaee34382012-09-05 22:56:26 +00006176 }
Jordan Rose22b74712012-09-05 22:56:19 +00006177 } else {
6178 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6179 SpecifierLen);
6180 // Since the warning for passing non-POD types to variadic functions
6181 // was deferred until now, we emit a warning for non-POD
6182 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006183 switch (S.isValidVarArgType(ExprTy)) {
6184 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006185 case Sema::VAK_ValidInCXX11: {
6186 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6187 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6188 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6189 }
Richard Smithd7293d72013-08-05 18:49:43 +00006190
Seth Cantrellb4802962015-03-04 03:12:10 +00006191 EmitFormatDiagnostic(
6192 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6193 << IsEnum << CSR << E->getSourceRange(),
6194 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6195 break;
6196 }
Richard Smithd7293d72013-08-05 18:49:43 +00006197 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006198 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006199 EmitFormatDiagnostic(
6200 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006201 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006202 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006203 << CallType
6204 << AT.getRepresentativeTypeName(S.Context)
6205 << CSR
6206 << E->getSourceRange(),
6207 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006208 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006209 break;
6210
6211 case Sema::VAK_Invalid:
6212 if (ExprTy->isObjCObjectType())
6213 EmitFormatDiagnostic(
6214 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6215 << S.getLangOpts().CPlusPlus11
6216 << ExprTy
6217 << CallType
6218 << AT.getRepresentativeTypeName(S.Context)
6219 << CSR
6220 << E->getSourceRange(),
6221 E->getLocStart(), /*IsStringLocation*/false, CSR);
6222 else
6223 // FIXME: If this is an initializer list, suggest removing the braces
6224 // or inserting a cast to the target type.
6225 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6226 << isa<InitListExpr>(E) << ExprTy << CallType
6227 << AT.getRepresentativeTypeName(S.Context)
6228 << E->getSourceRange();
6229 break;
6230 }
6231
6232 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6233 "format string specifier index out of range");
6234 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006235 }
6236
Ted Kremenekab278de2010-01-28 23:39:18 +00006237 return true;
6238}
6239
Ted Kremenek02087932010-07-16 02:11:22 +00006240//===--- CHECK: Scanf format string checking ------------------------------===//
6241
6242namespace {
6243class CheckScanfHandler : public CheckFormatHandler {
6244public:
Stephen Hines648c3692016-09-16 01:07:04 +00006245 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006246 const Expr *origFormatExpr, Sema::FormatStringType type,
6247 unsigned firstDataArg, unsigned numDataArgs,
6248 const char *beg, bool hasVAListArg,
6249 ArrayRef<const Expr *> Args, unsigned formatIdx,
6250 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006251 llvm::SmallBitVector &CheckedVarArgs,
6252 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006253 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6254 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6255 inFunctionCall, CallType, CheckedVarArgs,
6256 UncoveredArg) {}
6257
Ted Kremenek02087932010-07-16 02:11:22 +00006258 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6259 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006260 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006261
6262 bool HandleInvalidScanfConversionSpecifier(
6263 const analyze_scanf::ScanfSpecifier &FS,
6264 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006265 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006266
Craig Toppere14c0f82014-03-12 04:55:44 +00006267 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006268};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006269} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006270
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006271void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6272 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006273 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6274 getLocationOfByte(end), /*IsStringLocation*/true,
6275 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006276}
6277
Ted Kremenekce815422010-07-19 21:25:57 +00006278bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6279 const analyze_scanf::ScanfSpecifier &FS,
6280 const char *startSpecifier,
6281 unsigned specifierLen) {
6282
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006283 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006284 FS.getConversionSpecifier();
6285
6286 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6287 getLocationOfByte(CS.getStart()),
6288 startSpecifier, specifierLen,
6289 CS.getStart(), CS.getLength());
6290}
6291
Ted Kremenek02087932010-07-16 02:11:22 +00006292bool CheckScanfHandler::HandleScanfSpecifier(
6293 const analyze_scanf::ScanfSpecifier &FS,
6294 const char *startSpecifier,
6295 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006296 using namespace analyze_scanf;
6297 using namespace analyze_format_string;
6298
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006299 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006300
Ted Kremenek6cd69422010-07-19 22:01:06 +00006301 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6302 // be used to decide if we are using positional arguments consistently.
6303 if (FS.consumesDataArgument()) {
6304 if (atFirstArg) {
6305 atFirstArg = false;
6306 usesPositionalArgs = FS.usesPositionalArg();
6307 }
6308 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006309 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6310 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006311 return false;
6312 }
Ted Kremenek02087932010-07-16 02:11:22 +00006313 }
6314
6315 // Check if the field with is non-zero.
6316 const OptionalAmount &Amt = FS.getFieldWidth();
6317 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6318 if (Amt.getConstantAmount() == 0) {
6319 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6320 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006321 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6322 getLocationOfByte(Amt.getStart()),
6323 /*IsStringLocation*/true, R,
6324 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006325 }
6326 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006327
Ted Kremenek02087932010-07-16 02:11:22 +00006328 if (!FS.consumesDataArgument()) {
6329 // FIXME: Technically specifying a precision or field width here
6330 // makes no sense. Worth issuing a warning at some point.
6331 return true;
6332 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006333
Ted Kremenek02087932010-07-16 02:11:22 +00006334 // Consume the argument.
6335 unsigned argIndex = FS.getArgIndex();
6336 if (argIndex < NumDataArgs) {
6337 // The check to see if the argIndex is valid will come later.
6338 // We set the bit here because we may exit early from this
6339 // function if we encounter some other error.
6340 CoveredArgs.set(argIndex);
6341 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006342
Ted Kremenek4407ea42010-07-20 20:04:47 +00006343 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006344 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006345 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6346 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006347 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006348 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006349 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006350 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6351 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006352
Jordan Rose92303592012-09-08 04:00:03 +00006353 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6354 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6355
Ted Kremenek02087932010-07-16 02:11:22 +00006356 // The remaining checks depend on the data arguments.
6357 if (HasVAListArg)
6358 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006359
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006360 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006361 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006362
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006363 // Check that the argument type matches the format specifier.
6364 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006365 if (!Ex)
6366 return true;
6367
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006368 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006369
6370 if (!AT.isValid()) {
6371 return true;
6372 }
6373
Seth Cantrellb4802962015-03-04 03:12:10 +00006374 analyze_format_string::ArgType::MatchKind match =
6375 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006376 if (match == analyze_format_string::ArgType::Match) {
6377 return true;
6378 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006379
Seth Cantrell79340072015-03-04 05:58:08 +00006380 ScanfSpecifier fixedFS = FS;
6381 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6382 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006383
Seth Cantrell79340072015-03-04 05:58:08 +00006384 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6385 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6386 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6387 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006388
Seth Cantrell79340072015-03-04 05:58:08 +00006389 if (success) {
6390 // Get the fix string from the fixed format specifier.
6391 SmallString<128> buf;
6392 llvm::raw_svector_ostream os(buf);
6393 fixedFS.toString(os);
6394
6395 EmitFormatDiagnostic(
6396 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6397 << Ex->getType() << false << Ex->getSourceRange(),
6398 Ex->getLocStart(),
6399 /*IsStringLocation*/ false,
6400 getSpecifierRange(startSpecifier, specifierLen),
6401 FixItHint::CreateReplacement(
6402 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6403 } else {
6404 EmitFormatDiagnostic(S.PDiag(diag)
6405 << AT.getRepresentativeTypeName(S.Context)
6406 << Ex->getType() << false << Ex->getSourceRange(),
6407 Ex->getLocStart(),
6408 /*IsStringLocation*/ false,
6409 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006410 }
6411
Ted Kremenek02087932010-07-16 02:11:22 +00006412 return true;
6413}
6414
Stephen Hines648c3692016-09-16 01:07:04 +00006415static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006416 const Expr *OrigFormatExpr,
6417 ArrayRef<const Expr *> Args,
6418 bool HasVAListArg, unsigned format_idx,
6419 unsigned firstDataArg,
6420 Sema::FormatStringType Type,
6421 bool inFunctionCall,
6422 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006423 llvm::SmallBitVector &CheckedVarArgs,
6424 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00006425 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00006426 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006427 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006428 S, inFunctionCall, Args[format_idx],
6429 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006430 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006431 return;
6432 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006433
Ted Kremenekab278de2010-01-28 23:39:18 +00006434 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006435 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00006436 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006437 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006438 const ConstantArrayType *T =
6439 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006440 assert(T && "String literal not of constant array type!");
6441 size_t TypeSize = T->getSize().getZExtValue();
6442 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006443 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006444
6445 // Emit a warning if the string literal is truncated and does not contain an
6446 // embedded null character.
6447 if (TypeSize <= StrRef.size() &&
6448 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6449 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006450 S, inFunctionCall, Args[format_idx],
6451 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006452 FExpr->getLocStart(),
6453 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6454 return;
6455 }
6456
Ted Kremenekab278de2010-01-28 23:39:18 +00006457 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006458 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006459 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006460 S, inFunctionCall, Args[format_idx],
6461 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006462 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006463 return;
6464 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006465
6466 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00006467 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6468 Type == Sema::FST_OSTrace) {
6469 CheckPrintfHandler H(
6470 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6471 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6472 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6473 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006474
Hans Wennborg23926bd2011-12-15 10:25:47 +00006475 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006476 S.getLangOpts(),
6477 S.Context.getTargetInfo(),
6478 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006479 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006480 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00006481 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6482 numDataArgs, Str, HasVAListArg, Args, format_idx,
6483 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006484
Hans Wennborg23926bd2011-12-15 10:25:47 +00006485 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006486 S.getLangOpts(),
6487 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006488 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006489 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006490}
6491
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006492bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6493 // Str - The format string. NOTE: this is NOT null-terminated!
6494 StringRef StrRef = FExpr->getString();
6495 const char *Str = StrRef.data();
6496 // Account for cases where the string literal is truncated in a declaration.
6497 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6498 assert(T && "String literal not of constant array type!");
6499 size_t TypeSize = T->getSize().getZExtValue();
6500 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6501 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6502 getLangOpts(),
6503 Context.getTargetInfo());
6504}
6505
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006506//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6507
6508// Returns the related absolute value function that is larger, of 0 if one
6509// does not exist.
6510static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6511 switch (AbsFunction) {
6512 default:
6513 return 0;
6514
6515 case Builtin::BI__builtin_abs:
6516 return Builtin::BI__builtin_labs;
6517 case Builtin::BI__builtin_labs:
6518 return Builtin::BI__builtin_llabs;
6519 case Builtin::BI__builtin_llabs:
6520 return 0;
6521
6522 case Builtin::BI__builtin_fabsf:
6523 return Builtin::BI__builtin_fabs;
6524 case Builtin::BI__builtin_fabs:
6525 return Builtin::BI__builtin_fabsl;
6526 case Builtin::BI__builtin_fabsl:
6527 return 0;
6528
6529 case Builtin::BI__builtin_cabsf:
6530 return Builtin::BI__builtin_cabs;
6531 case Builtin::BI__builtin_cabs:
6532 return Builtin::BI__builtin_cabsl;
6533 case Builtin::BI__builtin_cabsl:
6534 return 0;
6535
6536 case Builtin::BIabs:
6537 return Builtin::BIlabs;
6538 case Builtin::BIlabs:
6539 return Builtin::BIllabs;
6540 case Builtin::BIllabs:
6541 return 0;
6542
6543 case Builtin::BIfabsf:
6544 return Builtin::BIfabs;
6545 case Builtin::BIfabs:
6546 return Builtin::BIfabsl;
6547 case Builtin::BIfabsl:
6548 return 0;
6549
6550 case Builtin::BIcabsf:
6551 return Builtin::BIcabs;
6552 case Builtin::BIcabs:
6553 return Builtin::BIcabsl;
6554 case Builtin::BIcabsl:
6555 return 0;
6556 }
6557}
6558
6559// Returns the argument type of the absolute value function.
6560static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6561 unsigned AbsType) {
6562 if (AbsType == 0)
6563 return QualType();
6564
6565 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6566 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6567 if (Error != ASTContext::GE_None)
6568 return QualType();
6569
6570 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6571 if (!FT)
6572 return QualType();
6573
6574 if (FT->getNumParams() != 1)
6575 return QualType();
6576
6577 return FT->getParamType(0);
6578}
6579
6580// Returns the best absolute value function, or zero, based on type and
6581// current absolute value function.
6582static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6583 unsigned AbsFunctionKind) {
6584 unsigned BestKind = 0;
6585 uint64_t ArgSize = Context.getTypeSize(ArgType);
6586 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6587 Kind = getLargerAbsoluteValueFunction(Kind)) {
6588 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6589 if (Context.getTypeSize(ParamType) >= ArgSize) {
6590 if (BestKind == 0)
6591 BestKind = Kind;
6592 else if (Context.hasSameType(ParamType, ArgType)) {
6593 BestKind = Kind;
6594 break;
6595 }
6596 }
6597 }
6598 return BestKind;
6599}
6600
6601enum AbsoluteValueKind {
6602 AVK_Integer,
6603 AVK_Floating,
6604 AVK_Complex
6605};
6606
6607static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6608 if (T->isIntegralOrEnumerationType())
6609 return AVK_Integer;
6610 if (T->isRealFloatingType())
6611 return AVK_Floating;
6612 if (T->isAnyComplexType())
6613 return AVK_Complex;
6614
6615 llvm_unreachable("Type not integer, floating, or complex");
6616}
6617
6618// Changes the absolute value function to a different type. Preserves whether
6619// the function is a builtin.
6620static unsigned changeAbsFunction(unsigned AbsKind,
6621 AbsoluteValueKind ValueKind) {
6622 switch (ValueKind) {
6623 case AVK_Integer:
6624 switch (AbsKind) {
6625 default:
6626 return 0;
6627 case Builtin::BI__builtin_fabsf:
6628 case Builtin::BI__builtin_fabs:
6629 case Builtin::BI__builtin_fabsl:
6630 case Builtin::BI__builtin_cabsf:
6631 case Builtin::BI__builtin_cabs:
6632 case Builtin::BI__builtin_cabsl:
6633 return Builtin::BI__builtin_abs;
6634 case Builtin::BIfabsf:
6635 case Builtin::BIfabs:
6636 case Builtin::BIfabsl:
6637 case Builtin::BIcabsf:
6638 case Builtin::BIcabs:
6639 case Builtin::BIcabsl:
6640 return Builtin::BIabs;
6641 }
6642 case AVK_Floating:
6643 switch (AbsKind) {
6644 default:
6645 return 0;
6646 case Builtin::BI__builtin_abs:
6647 case Builtin::BI__builtin_labs:
6648 case Builtin::BI__builtin_llabs:
6649 case Builtin::BI__builtin_cabsf:
6650 case Builtin::BI__builtin_cabs:
6651 case Builtin::BI__builtin_cabsl:
6652 return Builtin::BI__builtin_fabsf;
6653 case Builtin::BIabs:
6654 case Builtin::BIlabs:
6655 case Builtin::BIllabs:
6656 case Builtin::BIcabsf:
6657 case Builtin::BIcabs:
6658 case Builtin::BIcabsl:
6659 return Builtin::BIfabsf;
6660 }
6661 case AVK_Complex:
6662 switch (AbsKind) {
6663 default:
6664 return 0;
6665 case Builtin::BI__builtin_abs:
6666 case Builtin::BI__builtin_labs:
6667 case Builtin::BI__builtin_llabs:
6668 case Builtin::BI__builtin_fabsf:
6669 case Builtin::BI__builtin_fabs:
6670 case Builtin::BI__builtin_fabsl:
6671 return Builtin::BI__builtin_cabsf;
6672 case Builtin::BIabs:
6673 case Builtin::BIlabs:
6674 case Builtin::BIllabs:
6675 case Builtin::BIfabsf:
6676 case Builtin::BIfabs:
6677 case Builtin::BIfabsl:
6678 return Builtin::BIcabsf;
6679 }
6680 }
6681 llvm_unreachable("Unable to convert function");
6682}
6683
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006684static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006685 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6686 if (!FnInfo)
6687 return 0;
6688
6689 switch (FDecl->getBuiltinID()) {
6690 default:
6691 return 0;
6692 case Builtin::BI__builtin_abs:
6693 case Builtin::BI__builtin_fabs:
6694 case Builtin::BI__builtin_fabsf:
6695 case Builtin::BI__builtin_fabsl:
6696 case Builtin::BI__builtin_labs:
6697 case Builtin::BI__builtin_llabs:
6698 case Builtin::BI__builtin_cabs:
6699 case Builtin::BI__builtin_cabsf:
6700 case Builtin::BI__builtin_cabsl:
6701 case Builtin::BIabs:
6702 case Builtin::BIlabs:
6703 case Builtin::BIllabs:
6704 case Builtin::BIfabs:
6705 case Builtin::BIfabsf:
6706 case Builtin::BIfabsl:
6707 case Builtin::BIcabs:
6708 case Builtin::BIcabsf:
6709 case Builtin::BIcabsl:
6710 return FDecl->getBuiltinID();
6711 }
6712 llvm_unreachable("Unknown Builtin type");
6713}
6714
6715// If the replacement is valid, emit a note with replacement function.
6716// Additionally, suggest including the proper header if not already included.
6717static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00006718 unsigned AbsKind, QualType ArgType) {
6719 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006720 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00006721 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006722 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6723 FunctionName = "std::abs";
6724 if (ArgType->isIntegralOrEnumerationType()) {
6725 HeaderName = "cstdlib";
6726 } else if (ArgType->isRealFloatingType()) {
6727 HeaderName = "cmath";
6728 } else {
6729 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006730 }
Richard Trieubeffb832014-04-15 23:47:53 +00006731
6732 // Lookup all std::abs
6733 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00006734 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00006735 R.suppressDiagnostics();
6736 S.LookupQualifiedName(R, Std);
6737
6738 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006739 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006740 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6741 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6742 } else {
6743 FDecl = dyn_cast<FunctionDecl>(I);
6744 }
6745 if (!FDecl)
6746 continue;
6747
6748 // Found std::abs(), check that they are the right ones.
6749 if (FDecl->getNumParams() != 1)
6750 continue;
6751
6752 // Check that the parameter type can handle the argument.
6753 QualType ParamType = FDecl->getParamDecl(0)->getType();
6754 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6755 S.Context.getTypeSize(ArgType) <=
6756 S.Context.getTypeSize(ParamType)) {
6757 // Found a function, don't need the header hint.
6758 EmitHeaderHint = false;
6759 break;
6760 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006761 }
Richard Trieubeffb832014-04-15 23:47:53 +00006762 }
6763 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00006764 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00006765 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6766
6767 if (HeaderName) {
6768 DeclarationName DN(&S.Context.Idents.get(FunctionName));
6769 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6770 R.suppressDiagnostics();
6771 S.LookupName(R, S.getCurScope());
6772
6773 if (R.isSingleResult()) {
6774 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6775 if (FD && FD->getBuiltinID() == AbsKind) {
6776 EmitHeaderHint = false;
6777 } else {
6778 return;
6779 }
6780 } else if (!R.empty()) {
6781 return;
6782 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006783 }
6784 }
6785
6786 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00006787 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006788
Richard Trieubeffb832014-04-15 23:47:53 +00006789 if (!HeaderName)
6790 return;
6791
6792 if (!EmitHeaderHint)
6793 return;
6794
Alp Toker5d96e0a2014-07-11 20:53:51 +00006795 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6796 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00006797}
6798
Richard Trieua7f30b12016-12-06 01:42:28 +00006799template <std::size_t StrLen>
6800static bool IsStdFunction(const FunctionDecl *FDecl,
6801 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00006802 if (!FDecl)
6803 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00006804 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00006805 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00006806 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00006807 return false;
6808
6809 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006810}
6811
6812// Warn when using the wrong abs() function.
6813void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00006814 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006815 if (Call->getNumArgs() != 1)
6816 return;
6817
6818 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00006819 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00006820 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006821 return;
6822
6823 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6824 QualType ParamType = Call->getArg(0)->getType();
6825
Alp Toker5d96e0a2014-07-11 20:53:51 +00006826 // Unsigned types cannot be negative. Suggest removing the absolute value
6827 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006828 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00006829 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00006830 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006831 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6832 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00006833 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006834 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6835 return;
6836 }
6837
David Majnemer7f77eb92015-11-15 03:04:34 +00006838 // Taking the absolute value of a pointer is very suspicious, they probably
6839 // wanted to index into an array, dereference a pointer, call a function, etc.
6840 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6841 unsigned DiagType = 0;
6842 if (ArgType->isFunctionType())
6843 DiagType = 1;
6844 else if (ArgType->isArrayType())
6845 DiagType = 2;
6846
6847 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6848 return;
6849 }
6850
Richard Trieubeffb832014-04-15 23:47:53 +00006851 // std::abs has overloads which prevent most of the absolute value problems
6852 // from occurring.
6853 if (IsStdAbs)
6854 return;
6855
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006856 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6857 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6858
6859 // The argument and parameter are the same kind. Check if they are the right
6860 // size.
6861 if (ArgValueKind == ParamValueKind) {
6862 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6863 return;
6864
6865 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6866 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6867 << FDecl << ArgType << ParamType;
6868
6869 if (NewAbsKind == 0)
6870 return;
6871
6872 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006873 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006874 return;
6875 }
6876
6877 // ArgValueKind != ParamValueKind
6878 // The wrong type of absolute value function was used. Attempt to find the
6879 // proper one.
6880 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6881 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6882 if (NewAbsKind == 0)
6883 return;
6884
6885 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6886 << FDecl << ParamValueKind << ArgValueKind;
6887
6888 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006889 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006890}
6891
Richard Trieu67c00712016-12-05 23:41:46 +00006892//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00006893void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
6894 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00006895 if (!Call || !FDecl) return;
6896
6897 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00006898 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00006899 if (Call->getExprLoc().isMacroID()) return;
6900
6901 // Only care about the one template argument, two function parameter std::max
6902 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00006903 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00006904 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
6905 if (!ArgList) return;
6906 if (ArgList->size() != 1) return;
6907
6908 // Check that template type argument is unsigned integer.
6909 const auto& TA = ArgList->get(0);
6910 if (TA.getKind() != TemplateArgument::Type) return;
6911 QualType ArgType = TA.getAsType();
6912 if (!ArgType->isUnsignedIntegerType()) return;
6913
6914 // See if either argument is a literal zero.
6915 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
6916 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
6917 if (!MTE) return false;
6918 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
6919 if (!Num) return false;
6920 if (Num->getValue() != 0) return false;
6921 return true;
6922 };
6923
6924 const Expr *FirstArg = Call->getArg(0);
6925 const Expr *SecondArg = Call->getArg(1);
6926 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
6927 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
6928
6929 // Only warn when exactly one argument is zero.
6930 if (IsFirstArgZero == IsSecondArgZero) return;
6931
6932 SourceRange FirstRange = FirstArg->getSourceRange();
6933 SourceRange SecondRange = SecondArg->getSourceRange();
6934
6935 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
6936
6937 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
6938 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
6939
6940 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
6941 SourceRange RemovalRange;
6942 if (IsFirstArgZero) {
6943 RemovalRange = SourceRange(FirstRange.getBegin(),
6944 SecondRange.getBegin().getLocWithOffset(-1));
6945 } else {
6946 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
6947 SecondRange.getEnd());
6948 }
6949
6950 Diag(Call->getExprLoc(), diag::note_remove_max_call)
6951 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
6952 << FixItHint::CreateRemoval(RemovalRange);
6953}
6954
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006955//===--- CHECK: Standard memory functions ---------------------------------===//
6956
Nico Weber0e6daef2013-12-26 23:38:39 +00006957/// \brief Takes the expression passed to the size_t parameter of functions
6958/// such as memcmp, strncat, etc and warns if it's a comparison.
6959///
6960/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6961static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6962 IdentifierInfo *FnName,
6963 SourceLocation FnLoc,
6964 SourceLocation RParenLoc) {
6965 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6966 if (!Size)
6967 return false;
6968
6969 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6970 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6971 return false;
6972
Nico Weber0e6daef2013-12-26 23:38:39 +00006973 SourceRange SizeRange = Size->getSourceRange();
6974 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6975 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00006976 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006977 << FnName << FixItHint::CreateInsertion(
6978 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00006979 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00006980 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00006981 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00006982 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6983 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00006984
6985 return true;
6986}
6987
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006988/// \brief Determine whether the given type is or contains a dynamic class type
6989/// (e.g., whether it has a vtable).
6990static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6991 bool &IsContained) {
6992 // Look through array types while ignoring qualifiers.
6993 const Type *Ty = T->getBaseElementTypeUnsafe();
6994 IsContained = false;
6995
6996 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6997 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00006998 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006999 return nullptr;
7000
7001 if (RD->isDynamicClass())
7002 return RD;
7003
7004 // Check all the fields. If any bases were dynamic, the class is dynamic.
7005 // It's impossible for a class to transitively contain itself by value, so
7006 // infinite recursion is impossible.
7007 for (auto *FD : RD->fields()) {
7008 bool SubContained;
7009 if (const CXXRecordDecl *ContainedRD =
7010 getContainedDynamicClass(FD->getType(), SubContained)) {
7011 IsContained = true;
7012 return ContainedRD;
7013 }
7014 }
7015
7016 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007017}
7018
Chandler Carruth889ed862011-06-21 23:04:20 +00007019/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007020/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007021static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007022 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007023 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7024 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
7025 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007026
Craig Topperc3ec1492014-05-26 06:22:03 +00007027 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007028}
7029
Chandler Carruth889ed862011-06-21 23:04:20 +00007030/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007031static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007032 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7033 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7034 if (SizeOf->getKind() == clang::UETT_SizeOf)
7035 return SizeOf->getTypeOfArgument();
7036
7037 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007038}
7039
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007040/// \brief Check for dangerous or invalid arguments to memset().
7041///
Chandler Carruthac687262011-06-03 06:23:57 +00007042/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007043/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7044/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007045///
7046/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007047void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007048 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007049 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007050 assert(BId != 0);
7051
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007052 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007053 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007054 unsigned ExpectedNumArgs =
7055 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007056 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007057 return;
7058
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007059 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007060 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007061 unsigned LenArg =
7062 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007063 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007064
Nico Weber0e6daef2013-12-26 23:38:39 +00007065 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7066 Call->getLocStart(), Call->getRParenLoc()))
7067 return;
7068
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007069 // We have special checking when the length is a sizeof expression.
7070 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7071 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7072 llvm::FoldingSetNodeID SizeOfArgID;
7073
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007074 // Although widely used, 'bzero' is not a standard function. Be more strict
7075 // with the argument types before allowing diagnostics and only allow the
7076 // form bzero(ptr, sizeof(...)).
7077 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7078 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7079 return;
7080
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007081 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7082 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007083 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007084
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007085 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007086 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007087 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007088 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007089
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007090 // Never warn about void type pointers. This can be used to suppress
7091 // false positives.
7092 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007093 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007094
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007095 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7096 // actually comparing the expressions for equality. Because computing the
7097 // expression IDs can be expensive, we only do this if the diagnostic is
7098 // enabled.
7099 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007100 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7101 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007102 // We only compute IDs for expressions if the warning is enabled, and
7103 // cache the sizeof arg's ID.
7104 if (SizeOfArgID == llvm::FoldingSetNodeID())
7105 SizeOfArg->Profile(SizeOfArgID, Context, true);
7106 llvm::FoldingSetNodeID DestID;
7107 Dest->Profile(DestID, Context, true);
7108 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007109 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7110 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007111 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007112 StringRef ReadableName = FnName->getName();
7113
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007114 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007115 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007116 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007117 if (!PointeeTy->isIncompleteType() &&
7118 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007119 ActionIdx = 2; // If the pointee's size is sizeof(char),
7120 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007121
7122 // If the function is defined as a builtin macro, do not show macro
7123 // expansion.
7124 SourceLocation SL = SizeOfArg->getExprLoc();
7125 SourceRange DSR = Dest->getSourceRange();
7126 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007127 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007128
7129 if (SM.isMacroArgExpansion(SL)) {
7130 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7131 SL = SM.getSpellingLoc(SL);
7132 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7133 SM.getSpellingLoc(DSR.getEnd()));
7134 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7135 SM.getSpellingLoc(SSR.getEnd()));
7136 }
7137
Anna Zaksd08d9152012-05-30 23:14:52 +00007138 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007139 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007140 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007141 << PointeeTy
7142 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007143 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007144 << SSR);
7145 DiagRuntimeBehavior(SL, SizeOfArg,
7146 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7147 << ActionIdx
7148 << SSR);
7149
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007150 break;
7151 }
7152 }
7153
7154 // Also check for cases where the sizeof argument is the exact same
7155 // type as the memory argument, and where it points to a user-defined
7156 // record type.
7157 if (SizeOfArgTy != QualType()) {
7158 if (PointeeTy->isRecordType() &&
7159 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7160 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7161 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7162 << FnName << SizeOfArgTy << ArgIdx
7163 << PointeeTy << Dest->getSourceRange()
7164 << LenExpr->getSourceRange());
7165 break;
7166 }
Nico Weberc5e73862011-06-14 16:14:58 +00007167 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00007168 } else if (DestTy->isArrayType()) {
7169 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00007170 }
Nico Weberc5e73862011-06-14 16:14:58 +00007171
Nico Weberc44b35e2015-03-21 17:37:46 +00007172 if (PointeeTy == QualType())
7173 continue;
Anna Zaks22122702012-01-17 00:37:07 +00007174
Nico Weberc44b35e2015-03-21 17:37:46 +00007175 // Always complain about dynamic classes.
7176 bool IsContained;
7177 if (const CXXRecordDecl *ContainedRD =
7178 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00007179
Nico Weberc44b35e2015-03-21 17:37:46 +00007180 unsigned OperationType = 0;
7181 // "overwritten" if we're warning about the destination for any call
7182 // but memcmp; otherwise a verb appropriate to the call.
7183 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7184 if (BId == Builtin::BImemcpy)
7185 OperationType = 1;
7186 else if(BId == Builtin::BImemmove)
7187 OperationType = 2;
7188 else if (BId == Builtin::BImemcmp)
7189 OperationType = 3;
7190 }
7191
John McCall31168b02011-06-15 23:02:42 +00007192 DiagRuntimeBehavior(
7193 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007194 PDiag(diag::warn_dyn_class_memaccess)
7195 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7196 << FnName << IsContained << ContainedRD << OperationType
7197 << Call->getCallee()->getSourceRange());
7198 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7199 BId != Builtin::BImemset)
7200 DiagRuntimeBehavior(
7201 Dest->getExprLoc(), Dest,
7202 PDiag(diag::warn_arc_object_memaccess)
7203 << ArgIdx << FnName << PointeeTy
7204 << Call->getCallee()->getSourceRange());
7205 else
7206 continue;
7207
7208 DiagRuntimeBehavior(
7209 Dest->getExprLoc(), Dest,
7210 PDiag(diag::note_bad_memaccess_silence)
7211 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7212 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007213 }
7214}
7215
Ted Kremenek6865f772011-08-18 20:55:45 +00007216// A little helper routine: ignore addition and subtraction of integer literals.
7217// This intentionally does not ignore all integer constant expressions because
7218// we don't want to remove sizeof().
7219static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7220 Ex = Ex->IgnoreParenCasts();
7221
7222 for (;;) {
7223 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7224 if (!BO || !BO->isAdditiveOp())
7225 break;
7226
7227 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7228 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7229
7230 if (isa<IntegerLiteral>(RHS))
7231 Ex = LHS;
7232 else if (isa<IntegerLiteral>(LHS))
7233 Ex = RHS;
7234 else
7235 break;
7236 }
7237
7238 return Ex;
7239}
7240
Anna Zaks13b08572012-08-08 21:42:23 +00007241static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7242 ASTContext &Context) {
7243 // Only handle constant-sized or VLAs, but not flexible members.
7244 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7245 // Only issue the FIXIT for arrays of size > 1.
7246 if (CAT->getSize().getSExtValue() <= 1)
7247 return false;
7248 } else if (!Ty->isVariableArrayType()) {
7249 return false;
7250 }
7251 return true;
7252}
7253
Ted Kremenek6865f772011-08-18 20:55:45 +00007254// Warn if the user has made the 'size' argument to strlcpy or strlcat
7255// be the size of the source, instead of the destination.
7256void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7257 IdentifierInfo *FnName) {
7258
7259 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007260 unsigned NumArgs = Call->getNumArgs();
7261 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007262 return;
7263
7264 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7265 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007266 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007267
7268 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7269 Call->getLocStart(), Call->getRParenLoc()))
7270 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00007271
7272 // Look for 'strlcpy(dst, x, sizeof(x))'
7273 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7274 CompareWithSrc = Ex;
7275 else {
7276 // Look for 'strlcpy(dst, x, strlen(x))'
7277 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00007278 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7279 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00007280 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7281 }
7282 }
7283
7284 if (!CompareWithSrc)
7285 return;
7286
7287 // Determine if the argument to sizeof/strlen is equal to the source
7288 // argument. In principle there's all kinds of things you could do
7289 // here, for instance creating an == expression and evaluating it with
7290 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7291 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7292 if (!SrcArgDRE)
7293 return;
7294
7295 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7296 if (!CompareWithSrcDRE ||
7297 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7298 return;
7299
7300 const Expr *OriginalSizeArg = Call->getArg(2);
7301 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7302 << OriginalSizeArg->getSourceRange() << FnName;
7303
7304 // Output a FIXIT hint if the destination is an array (rather than a
7305 // pointer to an array). This could be enhanced to handle some
7306 // pointers if we know the actual size, like if DstArg is 'array+2'
7307 // we could say 'sizeof(array)-2'.
7308 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00007309 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00007310 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007311
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007312 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007313 llvm::raw_svector_ostream OS(sizeString);
7314 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007315 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00007316 OS << ")";
7317
7318 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7319 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7320 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00007321}
7322
Anna Zaks314cd092012-02-01 19:08:57 +00007323/// Check if two expressions refer to the same declaration.
7324static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7325 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7326 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7327 return D1->getDecl() == D2->getDecl();
7328 return false;
7329}
7330
7331static const Expr *getStrlenExprArg(const Expr *E) {
7332 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7333 const FunctionDecl *FD = CE->getDirectCallee();
7334 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00007335 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007336 return CE->getArg(0)->IgnoreParenCasts();
7337 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007338 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007339}
7340
7341// Warn on anti-patterns as the 'size' argument to strncat.
7342// The correct size argument should look like following:
7343// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7344void Sema::CheckStrncatArguments(const CallExpr *CE,
7345 IdentifierInfo *FnName) {
7346 // Don't crash if the user has the wrong number of arguments.
7347 if (CE->getNumArgs() < 3)
7348 return;
7349 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7350 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7351 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7352
Nico Weber0e6daef2013-12-26 23:38:39 +00007353 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7354 CE->getRParenLoc()))
7355 return;
7356
Anna Zaks314cd092012-02-01 19:08:57 +00007357 // Identify common expressions, which are wrongly used as the size argument
7358 // to strncat and may lead to buffer overflows.
7359 unsigned PatternType = 0;
7360 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7361 // - sizeof(dst)
7362 if (referToTheSameDecl(SizeOfArg, DstArg))
7363 PatternType = 1;
7364 // - sizeof(src)
7365 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7366 PatternType = 2;
7367 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7368 if (BE->getOpcode() == BO_Sub) {
7369 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7370 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7371 // - sizeof(dst) - strlen(dst)
7372 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7373 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7374 PatternType = 1;
7375 // - sizeof(src) - (anything)
7376 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7377 PatternType = 2;
7378 }
7379 }
7380
7381 if (PatternType == 0)
7382 return;
7383
Anna Zaks5069aa32012-02-03 01:27:37 +00007384 // Generate the diagnostic.
7385 SourceLocation SL = LenArg->getLocStart();
7386 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007387 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00007388
7389 // If the function is defined as a builtin macro, do not show macro expansion.
7390 if (SM.isMacroArgExpansion(SL)) {
7391 SL = SM.getSpellingLoc(SL);
7392 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7393 SM.getSpellingLoc(SR.getEnd()));
7394 }
7395
Anna Zaks13b08572012-08-08 21:42:23 +00007396 // Check if the destination is an array (rather than a pointer to an array).
7397 QualType DstTy = DstArg->getType();
7398 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7399 Context);
7400 if (!isKnownSizeArray) {
7401 if (PatternType == 1)
7402 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7403 else
7404 Diag(SL, diag::warn_strncat_src_size) << SR;
7405 return;
7406 }
7407
Anna Zaks314cd092012-02-01 19:08:57 +00007408 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00007409 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007410 else
Anna Zaks5069aa32012-02-03 01:27:37 +00007411 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007412
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007413 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00007414 llvm::raw_svector_ostream OS(sizeString);
7415 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007416 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007417 OS << ") - ";
7418 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007419 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007420 OS << ") - 1";
7421
Anna Zaks5069aa32012-02-03 01:27:37 +00007422 Diag(SL, diag::note_strncat_wrong_size)
7423 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00007424}
7425
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007426//===--- CHECK: Return Address of Stack Variable --------------------------===//
7427
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007428static const Expr *EvalVal(const Expr *E,
7429 SmallVectorImpl<const DeclRefExpr *> &refVars,
7430 const Decl *ParentDecl);
7431static const Expr *EvalAddr(const Expr *E,
7432 SmallVectorImpl<const DeclRefExpr *> &refVars,
7433 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007434
7435/// CheckReturnStackAddr - Check if a return statement returns the address
7436/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007437static void
7438CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7439 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00007440
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007441 const Expr *stackE = nullptr;
7442 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007443
7444 // Perform checking for returned stack addresses, local blocks,
7445 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00007446 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007447 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007448 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00007449 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007450 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007451 }
7452
Craig Topperc3ec1492014-05-26 06:22:03 +00007453 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007454 return; // Nothing suspicious was found.
7455
Richard Trieu81b6c562016-08-05 23:24:47 +00007456 // Parameters are initalized in the calling scope, so taking the address
7457 // of a parameter reference doesn't need a warning.
7458 for (auto *DRE : refVars)
7459 if (isa<ParmVarDecl>(DRE->getDecl()))
7460 return;
7461
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007462 SourceLocation diagLoc;
7463 SourceRange diagRange;
7464 if (refVars.empty()) {
7465 diagLoc = stackE->getLocStart();
7466 diagRange = stackE->getSourceRange();
7467 } else {
7468 // We followed through a reference variable. 'stackE' contains the
7469 // problematic expression but we will warn at the return statement pointing
7470 // at the reference variable. We will later display the "trail" of
7471 // reference variables using notes.
7472 diagLoc = refVars[0]->getLocStart();
7473 diagRange = refVars[0]->getSourceRange();
7474 }
7475
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007476 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7477 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00007478 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007479 << DR->getDecl()->getDeclName() << diagRange;
7480 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007481 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007482 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007483 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007484 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00007485 // If there is an LValue->RValue conversion, then the value of the
7486 // reference type is used, not the reference.
7487 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7488 if (ICE->getCastKind() == CK_LValueToRValue) {
7489 return;
7490 }
7491 }
Craig Topperda7b27f2015-11-17 05:40:09 +00007492 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7493 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007494 }
7495
7496 // Display the "trail" of reference variables that we followed until we
7497 // found the problematic expression using notes.
7498 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007499 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007500 // If this var binds to another reference var, show the range of the next
7501 // var, otherwise the var binds to the problematic expression, in which case
7502 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007503 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7504 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007505 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7506 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007507 }
7508}
7509
7510/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7511/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007512/// to a location on the stack, a local block, an address of a label, or a
7513/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007514/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007515/// encounter a subexpression that (1) clearly does not lead to one of the
7516/// above problematic expressions (2) is something we cannot determine leads to
7517/// a problematic expression based on such local checking.
7518///
7519/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7520/// the expression that they point to. Such variables are added to the
7521/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007522///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007523/// EvalAddr processes expressions that are pointers that are used as
7524/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007525/// At the base case of the recursion is a check for the above problematic
7526/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007527///
7528/// This implementation handles:
7529///
7530/// * pointer-to-pointer casts
7531/// * implicit conversions from array references to pointers
7532/// * taking the address of fields
7533/// * arbitrary interplay between "&" and "*" operators
7534/// * pointer arithmetic from an address of a stack variable
7535/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007536static const Expr *EvalAddr(const Expr *E,
7537 SmallVectorImpl<const DeclRefExpr *> &refVars,
7538 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007539 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00007540 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007541
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007542 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00007543 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00007544 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007545 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00007546 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00007547
Peter Collingbourne91147592011-04-15 00:35:48 +00007548 E = E->IgnoreParens();
7549
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007550 // Our "symbolic interpreter" is just a dispatch off the currently
7551 // viewed AST node. We then recursively traverse the AST by calling
7552 // EvalAddr and EvalVal appropriately.
7553 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007554 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007555 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007556
Richard Smith40f08eb2014-01-30 22:05:38 +00007557 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00007558 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00007559 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00007560
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007561 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007562 // If this is a reference variable, follow through to the expression that
7563 // it points to.
7564 if (V->hasLocalStorage() &&
7565 V->getType()->isReferenceType() && V->hasInit()) {
7566 // Add the reference variable to the "trail".
7567 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007568 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007569 }
7570
Craig Topperc3ec1492014-05-26 06:22:03 +00007571 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007572 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007573
Chris Lattner934edb22007-12-28 05:31:15 +00007574 case Stmt::UnaryOperatorClass: {
7575 // The only unary operator that make sense to handle here
7576 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007577 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007578
John McCalle3027922010-08-25 11:45:40 +00007579 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007580 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007581 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007582 }
Mike Stump11289f42009-09-09 15:08:12 +00007583
Chris Lattner934edb22007-12-28 05:31:15 +00007584 case Stmt::BinaryOperatorClass: {
7585 // Handle pointer arithmetic. All other binary operators are not valid
7586 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007587 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00007588 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00007589
John McCalle3027922010-08-25 11:45:40 +00007590 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00007591 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007592
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007593 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00007594
7595 // Determine which argument is the real pointer base. It could be
7596 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007597 if (!Base->getType()->isPointerType())
7598 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00007599
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007600 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007601 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007602 }
Steve Naroff2752a172008-09-10 19:17:48 +00007603
Chris Lattner934edb22007-12-28 05:31:15 +00007604 // For conditional operators we need to see if either the LHS or RHS are
7605 // valid DeclRefExpr*s. If one of them is valid, we return it.
7606 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007607 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007608
Chris Lattner934edb22007-12-28 05:31:15 +00007609 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007610 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007611 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007612 // In C++, we can have a throw-expression, which has 'void' type.
7613 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007614 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007615 return LHS;
7616 }
Chris Lattner934edb22007-12-28 05:31:15 +00007617
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007618 // In C++, we can have a throw-expression, which has 'void' type.
7619 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00007620 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007621
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007622 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007623 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007624
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007625 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00007626 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007627 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00007628 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007629
7630 case Stmt::AddrLabelExprClass:
7631 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00007632
John McCall28fc7092011-11-10 05:35:25 +00007633 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007634 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7635 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00007636
Ted Kremenekc3b4c522008-08-07 00:49:01 +00007637 // For casts, we need to handle conversions from arrays to
7638 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00007639 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00007640 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007641 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00007642 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00007643 case Stmt::CXXStaticCastExprClass:
7644 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00007645 case Stmt::CXXConstCastExprClass:
7646 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007647 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00007648 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00007649 case CK_LValueToRValue:
7650 case CK_NoOp:
7651 case CK_BaseToDerived:
7652 case CK_DerivedToBase:
7653 case CK_UncheckedDerivedToBase:
7654 case CK_Dynamic:
7655 case CK_CPointerToObjCPointerCast:
7656 case CK_BlockPointerToObjCPointerCast:
7657 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007658 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007659
7660 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007661 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007662
Richard Trieudadefde2014-07-02 04:39:38 +00007663 case CK_BitCast:
7664 if (SubExpr->getType()->isAnyPointerType() ||
7665 SubExpr->getType()->isBlockPointerType() ||
7666 SubExpr->getType()->isObjCQualifiedIdType())
7667 return EvalAddr(SubExpr, refVars, ParentDecl);
7668 else
7669 return nullptr;
7670
Eli Friedman8195ad72012-02-23 23:04:32 +00007671 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007672 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00007673 }
Chris Lattner934edb22007-12-28 05:31:15 +00007674 }
Mike Stump11289f42009-09-09 15:08:12 +00007675
Douglas Gregorfe314812011-06-21 17:03:29 +00007676 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007677 if (const Expr *Result =
7678 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7679 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00007680 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00007681 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007682
Chris Lattner934edb22007-12-28 05:31:15 +00007683 // Everything else: we simply don't reason about them.
7684 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007685 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00007686 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007687}
Mike Stump11289f42009-09-09 15:08:12 +00007688
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007689/// EvalVal - This function is complements EvalAddr in the mutual recursion.
7690/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007691static const Expr *EvalVal(const Expr *E,
7692 SmallVectorImpl<const DeclRefExpr *> &refVars,
7693 const Decl *ParentDecl) {
7694 do {
7695 // We should only be called for evaluating non-pointer expressions, or
7696 // expressions with a pointer type that are not used as references but
7697 // instead
7698 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00007699
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007700 // Our "symbolic interpreter" is just a dispatch off the currently
7701 // viewed AST node. We then recursively traverse the AST by calling
7702 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00007703
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007704 E = E->IgnoreParens();
7705 switch (E->getStmtClass()) {
7706 case Stmt::ImplicitCastExprClass: {
7707 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7708 if (IE->getValueKind() == VK_LValue) {
7709 E = IE->getSubExpr();
7710 continue;
7711 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007712 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007713 }
Richard Smith40f08eb2014-01-30 22:05:38 +00007714
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007715 case Stmt::ExprWithCleanupsClass:
7716 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7717 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007718
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007719 case Stmt::DeclRefExprClass: {
7720 // When we hit a DeclRefExpr we are looking at code that refers to a
7721 // variable's name. If it's not a reference variable we check if it has
7722 // local storage within the function, and if so, return the expression.
7723 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7724
7725 // If we leave the immediate function, the lifetime isn't about to end.
7726 if (DR->refersToEnclosingVariableOrCapture())
7727 return nullptr;
7728
7729 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7730 // Check if it refers to itself, e.g. "int& i = i;".
7731 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007732 return DR;
7733
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007734 if (V->hasLocalStorage()) {
7735 if (!V->getType()->isReferenceType())
7736 return DR;
7737
7738 // Reference variable, follow through to the expression that
7739 // it points to.
7740 if (V->hasInit()) {
7741 // Add the reference variable to the "trail".
7742 refVars.push_back(DR);
7743 return EvalVal(V->getInit(), refVars, V);
7744 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007745 }
7746 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007747
7748 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007749 }
Mike Stump11289f42009-09-09 15:08:12 +00007750
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007751 case Stmt::UnaryOperatorClass: {
7752 // The only unary operator that make sense to handle here
7753 // is Deref. All others don't resolve to a "name." This includes
7754 // handling all sorts of rvalues passed to a unary operator.
7755 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007756
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007757 if (U->getOpcode() == UO_Deref)
7758 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007759
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007760 return nullptr;
7761 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007762
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007763 case Stmt::ArraySubscriptExprClass: {
7764 // Array subscripts are potential references to data on the stack. We
7765 // retrieve the DeclRefExpr* for the array variable if it indeed
7766 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00007767 const auto *ASE = cast<ArraySubscriptExpr>(E);
7768 if (ASE->isTypeDependent())
7769 return nullptr;
7770 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007771 }
Mike Stump11289f42009-09-09 15:08:12 +00007772
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007773 case Stmt::OMPArraySectionExprClass: {
7774 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7775 ParentDecl);
7776 }
Mike Stump11289f42009-09-09 15:08:12 +00007777
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007778 case Stmt::ConditionalOperatorClass: {
7779 // For conditional operators we need to see if either the LHS or RHS are
7780 // non-NULL Expr's. If one is non-NULL, we return it.
7781 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007782
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007783 // Handle the GNU extension for missing LHS.
7784 if (const Expr *LHSExpr = C->getLHS()) {
7785 // In C++, we can have a throw-expression, which has 'void' type.
7786 if (!LHSExpr->getType()->isVoidType())
7787 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7788 return LHS;
7789 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007790
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007791 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007792 if (C->getRHS()->getType()->isVoidType())
7793 return nullptr;
7794
7795 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007796 }
7797
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007798 // Accesses to members are potential references to data on the stack.
7799 case Stmt::MemberExprClass: {
7800 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00007801
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007802 // Check for indirect access. We only want direct field accesses.
7803 if (M->isArrow())
7804 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007805
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007806 // Check whether the member type is itself a reference, in which case
7807 // we're not going to refer to the member, but to what the member refers
7808 // to.
7809 if (M->getMemberDecl()->getType()->isReferenceType())
7810 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007811
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007812 return EvalVal(M->getBase(), refVars, ParentDecl);
7813 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00007814
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007815 case Stmt::MaterializeTemporaryExprClass:
7816 if (const Expr *Result =
7817 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7818 refVars, ParentDecl))
7819 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007820 return E;
7821
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007822 default:
7823 // Check that we don't return or take the address of a reference to a
7824 // temporary. This is only useful in C++.
7825 if (!E->isTypeDependent() && E->isRValue())
7826 return E;
7827
7828 // Everything else: we simply don't reason about them.
7829 return nullptr;
7830 }
7831 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007832}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007833
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007834void
7835Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7836 SourceLocation ReturnLoc,
7837 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00007838 const AttrVec *Attrs,
7839 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007840 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7841
7842 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00007843 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7844 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00007845 CheckNonNullExpr(*this, RetValExp))
7846 Diag(ReturnLoc, diag::warn_null_ret)
7847 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00007848
7849 // C++11 [basic.stc.dynamic.allocation]p4:
7850 // If an allocation function declared with a non-throwing
7851 // exception-specification fails to allocate storage, it shall return
7852 // a null pointer. Any other allocation function that fails to allocate
7853 // storage shall indicate failure only by throwing an exception [...]
7854 if (FD) {
7855 OverloadedOperatorKind Op = FD->getOverloadedOperator();
7856 if (Op == OO_New || Op == OO_Array_New) {
7857 const FunctionProtoType *Proto
7858 = FD->getType()->castAs<FunctionProtoType>();
7859 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7860 CheckNonNullExpr(*this, RetValExp))
7861 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7862 << FD << getLangOpts().CPlusPlus11;
7863 }
7864 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007865}
7866
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007867//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7868
7869/// Check for comparisons of floating point operands using != and ==.
7870/// Issue a warning if these are no self-comparisons, as they are not likely
7871/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00007872void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00007873 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7874 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007875
7876 // Special case: check for x == x (which is OK).
7877 // Do not emit warnings for such cases.
7878 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7879 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7880 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00007881 return;
Mike Stump11289f42009-09-09 15:08:12 +00007882
Ted Kremenekeda40e22007-11-29 00:59:04 +00007883 // Special case: check for comparisons against literals that can be exactly
7884 // represented by APFloat. In such cases, do not emit a warning. This
7885 // is a heuristic: often comparison against such literals are used to
7886 // detect if a value in a variable has not changed. This clearly can
7887 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00007888 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7889 if (FLL->isExact())
7890 return;
7891 } else
7892 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7893 if (FLR->isExact())
7894 return;
Mike Stump11289f42009-09-09 15:08:12 +00007895
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007896 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00007897 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007898 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007899 return;
Mike Stump11289f42009-09-09 15:08:12 +00007900
David Blaikie1f4ff152012-07-16 20:47:22 +00007901 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007902 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007903 return;
Mike Stump11289f42009-09-09 15:08:12 +00007904
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007905 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00007906 Diag(Loc, diag::warn_floatingpoint_eq)
7907 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007908}
John McCallca01b222010-01-04 23:21:16 +00007909
John McCall70aa5392010-01-06 05:24:50 +00007910//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7911//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00007912
John McCall70aa5392010-01-06 05:24:50 +00007913namespace {
John McCallca01b222010-01-04 23:21:16 +00007914
John McCall70aa5392010-01-06 05:24:50 +00007915/// Structure recording the 'active' range of an integer-valued
7916/// expression.
7917struct IntRange {
7918 /// The number of bits active in the int.
7919 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00007920
John McCall70aa5392010-01-06 05:24:50 +00007921 /// True if the int is known not to have negative values.
7922 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00007923
John McCall70aa5392010-01-06 05:24:50 +00007924 IntRange(unsigned Width, bool NonNegative)
7925 : Width(Width), NonNegative(NonNegative)
7926 {}
John McCallca01b222010-01-04 23:21:16 +00007927
John McCall817d4af2010-11-10 23:38:19 +00007928 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00007929 static IntRange forBoolType() {
7930 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00007931 }
7932
John McCall817d4af2010-11-10 23:38:19 +00007933 /// Returns the range of an opaque value of the given integral type.
7934 static IntRange forValueOfType(ASTContext &C, QualType T) {
7935 return forValueOfCanonicalType(C,
7936 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00007937 }
7938
John McCall817d4af2010-11-10 23:38:19 +00007939 /// Returns the range of an opaque value of a canonical integral type.
7940 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00007941 assert(T->isCanonicalUnqualified());
7942
7943 if (const VectorType *VT = dyn_cast<VectorType>(T))
7944 T = VT->getElementType().getTypePtr();
7945 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7946 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007947 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7948 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00007949
David Majnemer6a426652013-06-07 22:07:20 +00007950 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00007951 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00007952 EnumDecl *Enum = ET->getDecl();
7953 if (!Enum->isCompleteDefinition())
7954 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00007955
David Majnemer6a426652013-06-07 22:07:20 +00007956 unsigned NumPositive = Enum->getNumPositiveBits();
7957 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00007958
David Majnemer6a426652013-06-07 22:07:20 +00007959 if (NumNegative == 0)
7960 return IntRange(NumPositive, true/*NonNegative*/);
7961 else
7962 return IntRange(std::max(NumPositive + 1, NumNegative),
7963 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00007964 }
John McCall70aa5392010-01-06 05:24:50 +00007965
7966 const BuiltinType *BT = cast<BuiltinType>(T);
7967 assert(BT->isInteger());
7968
7969 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7970 }
7971
John McCall817d4af2010-11-10 23:38:19 +00007972 /// Returns the "target" range of a canonical integral type, i.e.
7973 /// the range of values expressible in the type.
7974 ///
7975 /// This matches forValueOfCanonicalType except that enums have the
7976 /// full range of their type, not the range of their enumerators.
7977 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7978 assert(T->isCanonicalUnqualified());
7979
7980 if (const VectorType *VT = dyn_cast<VectorType>(T))
7981 T = VT->getElementType().getTypePtr();
7982 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7983 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007984 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7985 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007986 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00007987 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007988
7989 const BuiltinType *BT = cast<BuiltinType>(T);
7990 assert(BT->isInteger());
7991
7992 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7993 }
7994
7995 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00007996 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00007997 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00007998 L.NonNegative && R.NonNegative);
7999 }
8000
John McCall817d4af2010-11-10 23:38:19 +00008001 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008002 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008003 return IntRange(std::min(L.Width, R.Width),
8004 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008005 }
8006};
8007
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008008IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008009 if (value.isSigned() && value.isNegative())
8010 return IntRange(value.getMinSignedBits(), false);
8011
8012 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008013 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008014
8015 // isNonNegative() just checks the sign bit without considering
8016 // signedness.
8017 return IntRange(value.getActiveBits(), true);
8018}
8019
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008020IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8021 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008022 if (result.isInt())
8023 return GetValueRange(C, result.getInt(), MaxWidth);
8024
8025 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008026 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8027 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8028 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8029 R = IntRange::join(R, El);
8030 }
John McCall70aa5392010-01-06 05:24:50 +00008031 return R;
8032 }
8033
8034 if (result.isComplexInt()) {
8035 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8036 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8037 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008038 }
8039
8040 // This can happen with lossless casts to intptr_t of "based" lvalues.
8041 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008042 // FIXME: The only reason we need to pass the type in here is to get
8043 // the sign right on this one case. It would be nice if APValue
8044 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008045 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008046 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008047}
John McCall70aa5392010-01-06 05:24:50 +00008048
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008049QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008050 QualType Ty = E->getType();
8051 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8052 Ty = AtomicRHS->getValueType();
8053 return Ty;
8054}
8055
John McCall70aa5392010-01-06 05:24:50 +00008056/// Pseudo-evaluate the given integer expression, estimating the
8057/// range of values it might take.
8058///
8059/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008060IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008061 E = E->IgnoreParens();
8062
8063 // Try a full evaluation first.
8064 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008065 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008066 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008067
8068 // I think we only want to look through implicit casts here; if the
8069 // user has an explicit widening cast, we should treat the value as
8070 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008071 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00008072 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00008073 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8074
Eli Friedmane6d33952013-07-08 20:20:06 +00008075 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00008076
George Burgess IVdf1ed002016-01-13 01:52:39 +00008077 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8078 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00008079
John McCall70aa5392010-01-06 05:24:50 +00008080 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00008081 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00008082 return OutputTypeRange;
8083
8084 IntRange SubRange
8085 = GetExprRange(C, CE->getSubExpr(),
8086 std::min(MaxWidth, OutputTypeRange.Width));
8087
8088 // Bail out if the subexpr's range is as wide as the cast type.
8089 if (SubRange.Width >= OutputTypeRange.Width)
8090 return OutputTypeRange;
8091
8092 // Otherwise, we take the smaller width, and we're non-negative if
8093 // either the output type or the subexpr is.
8094 return IntRange(SubRange.Width,
8095 SubRange.NonNegative || OutputTypeRange.NonNegative);
8096 }
8097
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008098 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008099 // If we can fold the condition, just take that operand.
8100 bool CondResult;
8101 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8102 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8103 : CO->getFalseExpr(),
8104 MaxWidth);
8105
8106 // Otherwise, conservatively merge.
8107 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8108 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8109 return IntRange::join(L, R);
8110 }
8111
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008112 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008113 switch (BO->getOpcode()) {
8114
8115 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00008116 case BO_LAnd:
8117 case BO_LOr:
8118 case BO_LT:
8119 case BO_GT:
8120 case BO_LE:
8121 case BO_GE:
8122 case BO_EQ:
8123 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00008124 return IntRange::forBoolType();
8125
John McCallc3688382011-07-13 06:35:24 +00008126 // The type of the assignments is the type of the LHS, so the RHS
8127 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00008128 case BO_MulAssign:
8129 case BO_DivAssign:
8130 case BO_RemAssign:
8131 case BO_AddAssign:
8132 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00008133 case BO_XorAssign:
8134 case BO_OrAssign:
8135 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00008136 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00008137
John McCallc3688382011-07-13 06:35:24 +00008138 // Simple assignments just pass through the RHS, which will have
8139 // been coerced to the LHS type.
8140 case BO_Assign:
8141 // TODO: bitfields?
8142 return GetExprRange(C, BO->getRHS(), MaxWidth);
8143
John McCall70aa5392010-01-06 05:24:50 +00008144 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008145 case BO_PtrMemD:
8146 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00008147 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008148
John McCall2ce81ad2010-01-06 22:07:33 +00008149 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00008150 case BO_And:
8151 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00008152 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8153 GetExprRange(C, BO->getRHS(), MaxWidth));
8154
John McCall70aa5392010-01-06 05:24:50 +00008155 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00008156 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00008157 // ...except that we want to treat '1 << (blah)' as logically
8158 // positive. It's an important idiom.
8159 if (IntegerLiteral *I
8160 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8161 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008162 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00008163 return IntRange(R.Width, /*NonNegative*/ true);
8164 }
8165 }
8166 // fallthrough
8167
John McCalle3027922010-08-25 11:45:40 +00008168 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00008169 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008170
John McCall2ce81ad2010-01-06 22:07:33 +00008171 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00008172 case BO_Shr:
8173 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00008174 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8175
8176 // If the shift amount is a positive constant, drop the width by
8177 // that much.
8178 llvm::APSInt shift;
8179 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8180 shift.isNonNegative()) {
8181 unsigned zext = shift.getZExtValue();
8182 if (zext >= L.Width)
8183 L.Width = (L.NonNegative ? 0 : 1);
8184 else
8185 L.Width -= zext;
8186 }
8187
8188 return L;
8189 }
8190
8191 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008192 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008193 return GetExprRange(C, BO->getRHS(), MaxWidth);
8194
John McCall2ce81ad2010-01-06 22:07:33 +00008195 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008196 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008197 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008198 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008199 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008200
John McCall51431812011-07-14 22:39:48 +00008201 // The width of a division result is mostly determined by the size
8202 // of the LHS.
8203 case BO_Div: {
8204 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008205 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008206 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8207
8208 // If the divisor is constant, use that.
8209 llvm::APSInt divisor;
8210 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8211 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8212 if (log2 >= L.Width)
8213 L.Width = (L.NonNegative ? 0 : 1);
8214 else
8215 L.Width = std::min(L.Width - log2, MaxWidth);
8216 return L;
8217 }
8218
8219 // Otherwise, just use the LHS's width.
8220 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8221 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8222 }
8223
8224 // The result of a remainder can't be larger than the result of
8225 // either side.
8226 case BO_Rem: {
8227 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008228 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008229 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8230 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8231
8232 IntRange meet = IntRange::meet(L, R);
8233 meet.Width = std::min(meet.Width, MaxWidth);
8234 return meet;
8235 }
8236
8237 // The default behavior is okay for these.
8238 case BO_Mul:
8239 case BO_Add:
8240 case BO_Xor:
8241 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008242 break;
8243 }
8244
John McCall51431812011-07-14 22:39:48 +00008245 // The default case is to treat the operation as if it were closed
8246 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008247 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8248 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8249 return IntRange::join(L, R);
8250 }
8251
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008252 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008253 switch (UO->getOpcode()) {
8254 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008255 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008256 return IntRange::forBoolType();
8257
8258 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008259 case UO_Deref:
8260 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00008261 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008262
8263 default:
8264 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8265 }
8266 }
8267
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008268 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00008269 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8270
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008271 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00008272 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00008273 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00008274
Eli Friedmane6d33952013-07-08 20:20:06 +00008275 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008276}
John McCall263a48b2010-01-04 23:31:57 +00008277
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008278IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008279 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00008280}
8281
John McCall263a48b2010-01-04 23:31:57 +00008282/// Checks whether the given value, which currently has the given
8283/// source semantics, has the same value when coerced through the
8284/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008285bool IsSameFloatAfterCast(const llvm::APFloat &value,
8286 const llvm::fltSemantics &Src,
8287 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008288 llvm::APFloat truncated = value;
8289
8290 bool ignored;
8291 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8292 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8293
8294 return truncated.bitwiseIsEqual(value);
8295}
8296
8297/// Checks whether the given value, which currently has the given
8298/// source semantics, has the same value when coerced through the
8299/// target semantics.
8300///
8301/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008302bool IsSameFloatAfterCast(const APValue &value,
8303 const llvm::fltSemantics &Src,
8304 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008305 if (value.isFloat())
8306 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8307
8308 if (value.isVector()) {
8309 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8310 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8311 return false;
8312 return true;
8313 }
8314
8315 assert(value.isComplexFloat());
8316 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8317 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8318}
8319
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008320void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008321
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008322bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00008323 // Suppress cases where we are comparing against an enum constant.
8324 if (const DeclRefExpr *DR =
8325 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8326 if (isa<EnumConstantDecl>(DR->getDecl()))
8327 return false;
8328
8329 // Suppress cases where the '0' value is expanded from a macro.
8330 if (E->getLocStart().isMacroID())
8331 return false;
8332
John McCallcc7e5bf2010-05-06 08:58:33 +00008333 llvm::APSInt Value;
8334 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8335}
8336
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008337bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00008338 // Strip off implicit integral promotions.
8339 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008340 if (ICE->getCastKind() != CK_IntegralCast &&
8341 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00008342 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008343 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00008344 }
8345
8346 return E->getType()->isEnumeralType();
8347}
8348
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008349void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00008350 // Disable warning in template instantiations.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008351 if (S.inTemplateInstantiation())
Richard Trieu36594562013-11-01 21:47:19 +00008352 return;
8353
John McCalle3027922010-08-25 11:45:40 +00008354 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00008355 if (E->isValueDependent())
8356 return;
8357
John McCalle3027922010-08-25 11:45:40 +00008358 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008359 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008360 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008361 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008362 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008363 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008364 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008365 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008366 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008367 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008368 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008369 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008370 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008371 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008372 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008373 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8374 }
8375}
8376
Benjamin Kramer7320b992016-06-15 14:20:56 +00008377void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8378 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008379 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00008380 // Disable warning in template instantiations.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008381 if (S.inTemplateInstantiation())
Richard Trieudd51d742013-11-01 21:19:43 +00008382 return;
8383
Richard Trieu0f097742014-04-04 04:13:47 +00008384 // TODO: Investigate using GetExprRange() to get tighter bounds
8385 // on the bit ranges.
8386 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00008387 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00008388 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00008389 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8390 unsigned OtherWidth = OtherRange.Width;
8391
8392 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8393
Richard Trieu560910c2012-11-14 22:50:24 +00008394 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00008395 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00008396 return;
8397
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008398 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00008399 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008400
Richard Trieu0f097742014-04-04 04:13:47 +00008401 // Used for diagnostic printout.
8402 enum {
8403 LiteralConstant = 0,
8404 CXXBoolLiteralTrue,
8405 CXXBoolLiteralFalse
8406 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008407
Richard Trieu0f097742014-04-04 04:13:47 +00008408 if (!OtherIsBooleanType) {
8409 QualType ConstantT = Constant->getType();
8410 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00008411
Richard Trieu0f097742014-04-04 04:13:47 +00008412 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8413 return;
8414 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8415 "comparison with non-integer type");
8416
8417 bool ConstantSigned = ConstantT->isSignedIntegerType();
8418 bool CommonSigned = CommonT->isSignedIntegerType();
8419
8420 bool EqualityOnly = false;
8421
8422 if (CommonSigned) {
8423 // The common type is signed, therefore no signed to unsigned conversion.
8424 if (!OtherRange.NonNegative) {
8425 // Check that the constant is representable in type OtherT.
8426 if (ConstantSigned) {
8427 if (OtherWidth >= Value.getMinSignedBits())
8428 return;
8429 } else { // !ConstantSigned
8430 if (OtherWidth >= Value.getActiveBits() + 1)
8431 return;
8432 }
8433 } else { // !OtherSigned
8434 // Check that the constant is representable in type OtherT.
8435 // Negative values are out of range.
8436 if (ConstantSigned) {
8437 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8438 return;
8439 } else { // !ConstantSigned
8440 if (OtherWidth >= Value.getActiveBits())
8441 return;
8442 }
Richard Trieu560910c2012-11-14 22:50:24 +00008443 }
Richard Trieu0f097742014-04-04 04:13:47 +00008444 } else { // !CommonSigned
8445 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00008446 if (OtherWidth >= Value.getActiveBits())
8447 return;
Craig Toppercf360162014-06-18 05:13:11 +00008448 } else { // OtherSigned
8449 assert(!ConstantSigned &&
8450 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00008451 // Check to see if the constant is representable in OtherT.
8452 if (OtherWidth > Value.getActiveBits())
8453 return;
8454 // Check to see if the constant is equivalent to a negative value
8455 // cast to CommonT.
8456 if (S.Context.getIntWidth(ConstantT) ==
8457 S.Context.getIntWidth(CommonT) &&
8458 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8459 return;
8460 // The constant value rests between values that OtherT can represent
8461 // after conversion. Relational comparison still works, but equality
8462 // comparisons will be tautological.
8463 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008464 }
8465 }
Richard Trieu0f097742014-04-04 04:13:47 +00008466
8467 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8468
8469 if (op == BO_EQ || op == BO_NE) {
8470 IsTrue = op == BO_NE;
8471 } else if (EqualityOnly) {
8472 return;
8473 } else if (RhsConstant) {
8474 if (op == BO_GT || op == BO_GE)
8475 IsTrue = !PositiveConstant;
8476 else // op == BO_LT || op == BO_LE
8477 IsTrue = PositiveConstant;
8478 } else {
8479 if (op == BO_LT || op == BO_LE)
8480 IsTrue = !PositiveConstant;
8481 else // op == BO_GT || op == BO_GE
8482 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008483 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008484 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00008485 // Other isKnownToHaveBooleanValue
8486 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8487 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8488 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8489
8490 static const struct LinkedConditions {
8491 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8492 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8493 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8494 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8495 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8496 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8497
8498 } TruthTable = {
8499 // Constant on LHS. | Constant on RHS. |
8500 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
8501 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8502 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8503 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8504 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8505 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8506 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8507 };
8508
8509 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8510
8511 enum ConstantValue ConstVal = Zero;
8512 if (Value.isUnsigned() || Value.isNonNegative()) {
8513 if (Value == 0) {
8514 LiteralOrBoolConstant =
8515 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8516 ConstVal = Zero;
8517 } else if (Value == 1) {
8518 LiteralOrBoolConstant =
8519 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8520 ConstVal = One;
8521 } else {
8522 LiteralOrBoolConstant = LiteralConstant;
8523 ConstVal = GT_One;
8524 }
8525 } else {
8526 ConstVal = LT_Zero;
8527 }
8528
8529 CompareBoolWithConstantResult CmpRes;
8530
8531 switch (op) {
8532 case BO_LT:
8533 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8534 break;
8535 case BO_GT:
8536 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8537 break;
8538 case BO_LE:
8539 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8540 break;
8541 case BO_GE:
8542 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8543 break;
8544 case BO_EQ:
8545 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8546 break;
8547 case BO_NE:
8548 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8549 break;
8550 default:
8551 CmpRes = Unkwn;
8552 break;
8553 }
8554
8555 if (CmpRes == AFals) {
8556 IsTrue = false;
8557 } else if (CmpRes == ATrue) {
8558 IsTrue = true;
8559 } else {
8560 return;
8561 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008562 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008563
8564 // If this is a comparison to an enum constant, include that
8565 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00008566 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008567 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8568 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8569
8570 SmallString<64> PrettySourceValue;
8571 llvm::raw_svector_ostream OS(PrettySourceValue);
8572 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00008573 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008574 else
8575 OS << Value;
8576
Richard Trieu0f097742014-04-04 04:13:47 +00008577 S.DiagRuntimeBehavior(
8578 E->getOperatorLoc(), E,
8579 S.PDiag(diag::warn_out_of_range_compare)
8580 << OS.str() << LiteralOrBoolConstant
8581 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8582 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008583}
8584
John McCallcc7e5bf2010-05-06 08:58:33 +00008585/// Analyze the operands of the given comparison. Implements the
8586/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008587void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00008588 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8589 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008590}
John McCall263a48b2010-01-04 23:31:57 +00008591
John McCallca01b222010-01-04 23:21:16 +00008592/// \brief Implements -Wsign-compare.
8593///
Richard Trieu82402a02011-09-15 21:56:47 +00008594/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008595void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008596 // The type the comparison is being performed in.
8597 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00008598
8599 // Only analyze comparison operators where both sides have been converted to
8600 // the same type.
8601 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8602 return AnalyzeImpConvsInComparison(S, E);
8603
8604 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00008605 if (E->isValueDependent())
8606 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008607
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008608 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8609 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008610
8611 bool IsComparisonConstant = false;
8612
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008613 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008614 // of 'true' or 'false'.
8615 if (T->isIntegralType(S.Context)) {
8616 llvm::APSInt RHSValue;
8617 bool IsRHSIntegralLiteral =
8618 RHS->isIntegerConstantExpr(RHSValue, S.Context);
8619 llvm::APSInt LHSValue;
8620 bool IsLHSIntegralLiteral =
8621 LHS->isIntegerConstantExpr(LHSValue, S.Context);
8622 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8623 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8624 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8625 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8626 else
8627 IsComparisonConstant =
8628 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008629 } else if (!T->hasUnsignedIntegerRepresentation())
8630 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008631
John McCallcc7e5bf2010-05-06 08:58:33 +00008632 // We don't do anything special if this isn't an unsigned integral
8633 // comparison: we're only interested in integral comparisons, and
8634 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00008635 //
8636 // We also don't care about value-dependent expressions or expressions
8637 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008638 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00008639 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008640
John McCallcc7e5bf2010-05-06 08:58:33 +00008641 // Check to see if one of the (unmodified) operands is of different
8642 // signedness.
8643 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00008644 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8645 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00008646 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00008647 signedOperand = LHS;
8648 unsignedOperand = RHS;
8649 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8650 signedOperand = RHS;
8651 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00008652 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00008653 CheckTrivialUnsignedComparison(S, E);
8654 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008655 }
8656
John McCallcc7e5bf2010-05-06 08:58:33 +00008657 // Otherwise, calculate the effective range of the signed operand.
8658 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00008659
John McCallcc7e5bf2010-05-06 08:58:33 +00008660 // Go ahead and analyze implicit conversions in the operands. Note
8661 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00008662 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8663 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00008664
John McCallcc7e5bf2010-05-06 08:58:33 +00008665 // If the signed range is non-negative, -Wsign-compare won't fire,
8666 // but we should still check for comparisons which are always true
8667 // or false.
8668 if (signedRange.NonNegative)
8669 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008670
8671 // For (in)equality comparisons, if the unsigned operand is a
8672 // constant which cannot collide with a overflowed signed operand,
8673 // then reinterpreting the signed operand as unsigned will not
8674 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00008675 if (E->isEqualityOp()) {
8676 unsigned comparisonWidth = S.Context.getIntWidth(T);
8677 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00008678
John McCallcc7e5bf2010-05-06 08:58:33 +00008679 // We should never be unable to prove that the unsigned operand is
8680 // non-negative.
8681 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8682
8683 if (unsignedRange.Width < comparisonWidth)
8684 return;
8685 }
8686
Douglas Gregorbfb4a212012-05-01 01:53:49 +00008687 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8688 S.PDiag(diag::warn_mixed_sign_comparison)
8689 << LHS->getType() << RHS->getType()
8690 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00008691}
8692
John McCall1f425642010-11-11 03:21:53 +00008693/// Analyzes an attempt to assign the given value to a bitfield.
8694///
8695/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008696bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8697 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00008698 assert(Bitfield->isBitField());
8699 if (Bitfield->isInvalidDecl())
8700 return false;
8701
John McCalldeebbcf2010-11-11 05:33:51 +00008702 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00008703 QualType BitfieldType = Bitfield->getType();
8704 if (BitfieldType->isBooleanType())
8705 return false;
8706
8707 if (BitfieldType->isEnumeralType()) {
8708 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
8709 // If the underlying enum type was not explicitly specified as an unsigned
8710 // type and the enum contain only positive values, MSVC++ will cause an
8711 // inconsistency by storing this as a signed type.
8712 if (S.getLangOpts().CPlusPlus11 &&
8713 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
8714 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
8715 BitfieldEnumDecl->getNumNegativeBits() == 0) {
8716 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
8717 << BitfieldEnumDecl->getNameAsString();
8718 }
8719 }
8720
John McCalldeebbcf2010-11-11 05:33:51 +00008721 if (Bitfield->getType()->isBooleanType())
8722 return false;
8723
Douglas Gregor789adec2011-02-04 13:09:01 +00008724 // Ignore value- or type-dependent expressions.
8725 if (Bitfield->getBitWidth()->isValueDependent() ||
8726 Bitfield->getBitWidth()->isTypeDependent() ||
8727 Init->isValueDependent() ||
8728 Init->isTypeDependent())
8729 return false;
8730
John McCall1f425642010-11-11 03:21:53 +00008731 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00008732 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00008733
Richard Smith5fab0c92011-12-28 19:48:30 +00008734 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00008735 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
8736 Expr::SE_AllowSideEffects)) {
8737 // The RHS is not constant. If the RHS has an enum type, make sure the
8738 // bitfield is wide enough to hold all the values of the enum without
8739 // truncation.
8740 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
8741 EnumDecl *ED = EnumTy->getDecl();
8742 bool SignedBitfield = BitfieldType->isSignedIntegerType();
8743
8744 // Enum types are implicitly signed on Windows, so check if there are any
8745 // negative enumerators to see if the enum was intended to be signed or
8746 // not.
8747 bool SignedEnum = ED->getNumNegativeBits() > 0;
8748
8749 // Check for surprising sign changes when assigning enum values to a
8750 // bitfield of different signedness. If the bitfield is signed and we
8751 // have exactly the right number of bits to store this unsigned enum,
8752 // suggest changing the enum to an unsigned type. This typically happens
8753 // on Windows where unfixed enums always use an underlying type of 'int'.
8754 unsigned DiagID = 0;
8755 if (SignedEnum && !SignedBitfield) {
8756 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
8757 } else if (SignedBitfield && !SignedEnum &&
8758 ED->getNumPositiveBits() == FieldWidth) {
8759 DiagID = diag::warn_signed_bitfield_enum_conversion;
8760 }
8761
8762 if (DiagID) {
8763 S.Diag(InitLoc, DiagID) << Bitfield << ED;
8764 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
8765 SourceRange TypeRange =
8766 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
8767 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
8768 << SignedEnum << TypeRange;
8769 }
8770
8771 // Compute the required bitwidth. If the enum has negative values, we need
8772 // one more bit than the normal number of positive bits to represent the
8773 // sign bit.
8774 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
8775 ED->getNumNegativeBits())
8776 : ED->getNumPositiveBits();
8777
8778 // Check the bitwidth.
8779 if (BitsNeeded > FieldWidth) {
8780 Expr *WidthExpr = Bitfield->getBitWidth();
8781 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
8782 << Bitfield << ED;
8783 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
8784 << BitsNeeded << ED << WidthExpr->getSourceRange();
8785 }
8786 }
8787
John McCall1f425642010-11-11 03:21:53 +00008788 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00008789 }
John McCall1f425642010-11-11 03:21:53 +00008790
John McCall1f425642010-11-11 03:21:53 +00008791 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00008792
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008793 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00008794 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008795 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8796 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00008797
John McCall1f425642010-11-11 03:21:53 +00008798 if (OriginalWidth <= FieldWidth)
8799 return false;
8800
Eli Friedmanc267a322012-01-26 23:11:39 +00008801 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00008802 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00008803 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00008804
Eli Friedmanc267a322012-01-26 23:11:39 +00008805 // Check whether the stored value is equal to the original value.
8806 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00008807 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00008808 return false;
8809
Eli Friedmanc267a322012-01-26 23:11:39 +00008810 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00008811 // therefore don't strictly fit into a signed bitfield of width 1.
8812 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00008813 return false;
8814
John McCall1f425642010-11-11 03:21:53 +00008815 std::string PrettyValue = Value.toString(10);
8816 std::string PrettyTrunc = TruncatedValue.toString(10);
8817
8818 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8819 << PrettyValue << PrettyTrunc << OriginalInit->getType()
8820 << Init->getSourceRange();
8821
8822 return true;
8823}
8824
John McCalld2a53122010-11-09 23:24:47 +00008825/// Analyze the given simple or compound assignment for warning-worthy
8826/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008827void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00008828 // Just recurse on the LHS.
8829 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8830
8831 // We want to recurse on the RHS as normal unless we're assigning to
8832 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00008833 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008834 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00008835 E->getOperatorLoc())) {
8836 // Recurse, ignoring any implicit conversions on the RHS.
8837 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8838 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00008839 }
8840 }
8841
8842 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8843}
8844
John McCall263a48b2010-01-04 23:31:57 +00008845/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008846void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8847 SourceLocation CContext, unsigned diag,
8848 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008849 if (pruneControlFlow) {
8850 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8851 S.PDiag(diag)
8852 << SourceType << T << E->getSourceRange()
8853 << SourceRange(CContext));
8854 return;
8855 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00008856 S.Diag(E->getExprLoc(), diag)
8857 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8858}
8859
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008860/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008861void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8862 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008863 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008864}
8865
Richard Trieube234c32016-04-21 21:04:55 +00008866
8867/// Diagnose an implicit cast from a floating point value to an integer value.
8868void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8869
8870 SourceLocation CContext) {
8871 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00008872 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00008873
8874 Expr *InnerE = E->IgnoreParenImpCasts();
8875 // We also want to warn on, e.g., "int i = -1.234"
8876 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8877 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8878 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8879
8880 const bool IsLiteral =
8881 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8882
8883 llvm::APFloat Value(0.0);
8884 bool IsConstant =
8885 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8886 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00008887 return DiagnoseImpCast(S, E, T, CContext,
8888 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00008889 }
8890
Chandler Carruth016ef402011-04-10 08:36:24 +00008891 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00008892
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00008893 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8894 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00008895 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8896 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00008897 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00008898 if (IsLiteral) return;
8899 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8900 PruneWarnings);
8901 }
8902
8903 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00008904 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00008905 // Warn on floating point literal to integer.
8906 DiagID = diag::warn_impcast_literal_float_to_integer;
8907 } else if (IntegerValue == 0) {
8908 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
8909 return DiagnoseImpCast(S, E, T, CContext,
8910 diag::warn_impcast_float_integer, PruneWarnings);
8911 }
8912 // Warn on non-zero to zero conversion.
8913 DiagID = diag::warn_impcast_float_to_integer_zero;
8914 } else {
8915 if (IntegerValue.isUnsigned()) {
8916 if (!IntegerValue.isMaxValue()) {
8917 return DiagnoseImpCast(S, E, T, CContext,
8918 diag::warn_impcast_float_integer, PruneWarnings);
8919 }
8920 } else { // IntegerValue.isSigned()
8921 if (!IntegerValue.isMaxSignedValue() &&
8922 !IntegerValue.isMinSignedValue()) {
8923 return DiagnoseImpCast(S, E, T, CContext,
8924 diag::warn_impcast_float_integer, PruneWarnings);
8925 }
8926 }
8927 // Warn on evaluatable floating point expression to integer conversion.
8928 DiagID = diag::warn_impcast_float_to_integer;
8929 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008930
Eli Friedman07185912013-08-29 23:44:43 +00008931 // FIXME: Force the precision of the source value down so we don't print
8932 // digits which are usually useless (we don't really care here if we
8933 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
8934 // would automatically print the shortest representation, but it's a bit
8935 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00008936 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00008937 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
8938 precision = (precision * 59 + 195) / 196;
8939 Value.toString(PrettySourceValue, precision);
8940
David Blaikie9b88cc02012-05-15 17:18:27 +00008941 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00008942 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00008943 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00008944 else
David Blaikie9b88cc02012-05-15 17:18:27 +00008945 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00008946
Richard Trieube234c32016-04-21 21:04:55 +00008947 if (PruneWarnings) {
8948 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8949 S.PDiag(DiagID)
8950 << E->getType() << T.getUnqualifiedType()
8951 << PrettySourceValue << PrettyTargetValue
8952 << E->getSourceRange() << SourceRange(CContext));
8953 } else {
8954 S.Diag(E->getExprLoc(), DiagID)
8955 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8956 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8957 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008958}
8959
John McCall18a2c2c2010-11-09 22:22:12 +00008960std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8961 if (!Range.Width) return "0";
8962
8963 llvm::APSInt ValueInRange = Value;
8964 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00008965 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00008966 return ValueInRange.toString(10);
8967}
8968
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008969bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008970 if (!isa<ImplicitCastExpr>(Ex))
8971 return false;
8972
8973 Expr *InnerE = Ex->IgnoreParenImpCasts();
8974 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8975 const Type *Source =
8976 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8977 if (Target->isDependentType())
8978 return false;
8979
8980 const BuiltinType *FloatCandidateBT =
8981 dyn_cast<BuiltinType>(ToBool ? Source : Target);
8982 const Type *BoolCandidateType = ToBool ? Target : Source;
8983
8984 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8985 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8986}
8987
8988void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8989 SourceLocation CC) {
8990 unsigned NumArgs = TheCall->getNumArgs();
8991 for (unsigned i = 0; i < NumArgs; ++i) {
8992 Expr *CurrA = TheCall->getArg(i);
8993 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8994 continue;
8995
8996 bool IsSwapped = ((i > 0) &&
8997 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8998 IsSwapped |= ((i < (NumArgs - 1)) &&
8999 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9000 if (IsSwapped) {
9001 // Warn on this floating-point to bool conversion.
9002 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9003 CurrA->getType(), CC,
9004 diag::warn_impcast_floating_point_to_bool);
9005 }
9006 }
9007}
9008
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009009void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009010 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9011 E->getExprLoc()))
9012 return;
9013
Richard Trieu09d6b802016-01-08 23:35:06 +00009014 // Don't warn on functions which have return type nullptr_t.
9015 if (isa<CallExpr>(E))
9016 return;
9017
Richard Trieu5b993502014-10-15 03:42:06 +00009018 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9019 const Expr::NullPointerConstantKind NullKind =
9020 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9021 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9022 return;
9023
9024 // Return if target type is a safe conversion.
9025 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9026 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9027 return;
9028
9029 SourceLocation Loc = E->getSourceRange().getBegin();
9030
Richard Trieu0a5e1662016-02-13 00:58:53 +00009031 // Venture through the macro stacks to get to the source of macro arguments.
9032 // The new location is a better location than the complete location that was
9033 // passed in.
9034 while (S.SourceMgr.isMacroArgExpansion(Loc))
9035 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
9036
9037 while (S.SourceMgr.isMacroArgExpansion(CC))
9038 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
9039
Richard Trieu5b993502014-10-15 03:42:06 +00009040 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00009041 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9042 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9043 Loc, S.SourceMgr, S.getLangOpts());
9044 if (MacroName == "NULL")
9045 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00009046 }
9047
9048 // Only warn if the null and context location are in the same macro expansion.
9049 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9050 return;
9051
9052 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9053 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
9054 << FixItHint::CreateReplacement(Loc,
9055 S.getFixItZeroLiteralForType(T, Loc));
9056}
9057
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009058void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9059 ObjCArrayLiteral *ArrayLiteral);
9060void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9061 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00009062
9063/// Check a single element within a collection literal against the
9064/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009065void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
9066 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009067 // Skip a bitcast to 'id' or qualified 'id'.
9068 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9069 if (ICE->getCastKind() == CK_BitCast &&
9070 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9071 Element = ICE->getSubExpr();
9072 }
9073
9074 QualType ElementType = Element->getType();
9075 ExprResult ElementResult(Element);
9076 if (ElementType->getAs<ObjCObjectPointerType>() &&
9077 S.CheckSingleAssignmentConstraints(TargetElementType,
9078 ElementResult,
9079 false, false)
9080 != Sema::Compatible) {
9081 S.Diag(Element->getLocStart(),
9082 diag::warn_objc_collection_literal_element)
9083 << ElementType << ElementKind << TargetElementType
9084 << Element->getSourceRange();
9085 }
9086
9087 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9088 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9089 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9090 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9091}
9092
9093/// Check an Objective-C array literal being converted to the given
9094/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009095void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9096 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009097 if (!S.NSArrayDecl)
9098 return;
9099
9100 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9101 if (!TargetObjCPtr)
9102 return;
9103
9104 if (TargetObjCPtr->isUnspecialized() ||
9105 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9106 != S.NSArrayDecl->getCanonicalDecl())
9107 return;
9108
9109 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9110 if (TypeArgs.size() != 1)
9111 return;
9112
9113 QualType TargetElementType = TypeArgs[0];
9114 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9115 checkObjCCollectionLiteralElement(S, TargetElementType,
9116 ArrayLiteral->getElement(I),
9117 0);
9118 }
9119}
9120
9121/// Check an Objective-C dictionary literal being converted to the given
9122/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009123void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9124 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009125 if (!S.NSDictionaryDecl)
9126 return;
9127
9128 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9129 if (!TargetObjCPtr)
9130 return;
9131
9132 if (TargetObjCPtr->isUnspecialized() ||
9133 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9134 != S.NSDictionaryDecl->getCanonicalDecl())
9135 return;
9136
9137 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9138 if (TypeArgs.size() != 2)
9139 return;
9140
9141 QualType TargetKeyType = TypeArgs[0];
9142 QualType TargetObjectType = TypeArgs[1];
9143 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9144 auto Element = DictionaryLiteral->getKeyValueElement(I);
9145 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9146 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9147 }
9148}
9149
Richard Trieufc404c72016-02-05 23:02:38 +00009150// Helper function to filter out cases for constant width constant conversion.
9151// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009152bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9153 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00009154 // If initializing from a constant, and the constant starts with '0',
9155 // then it is a binary, octal, or hexadecimal. Allow these constants
9156 // to fill all the bits, even if there is a sign change.
9157 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9158 const char FirstLiteralCharacter =
9159 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9160 if (FirstLiteralCharacter == '0')
9161 return false;
9162 }
9163
9164 // If the CC location points to a '{', and the type is char, then assume
9165 // assume it is an array initialization.
9166 if (CC.isValid() && T->isCharType()) {
9167 const char FirstContextCharacter =
9168 S.getSourceManager().getCharacterData(CC)[0];
9169 if (FirstContextCharacter == '{')
9170 return false;
9171 }
9172
9173 return true;
9174}
9175
John McCallcc7e5bf2010-05-06 08:58:33 +00009176void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00009177 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009178 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00009179
John McCallcc7e5bf2010-05-06 08:58:33 +00009180 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9181 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9182 if (Source == Target) return;
9183 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00009184
Chandler Carruthc22845a2011-07-26 05:40:03 +00009185 // If the conversion context location is invalid don't complain. We also
9186 // don't want to emit a warning if the issue occurs from the expansion of
9187 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9188 // delay this check as long as possible. Once we detect we are in that
9189 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009190 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00009191 return;
9192
Richard Trieu021baa32011-09-23 20:10:00 +00009193 // Diagnose implicit casts to bool.
9194 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9195 if (isa<StringLiteral>(E))
9196 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00009197 // and expressions, for instance, assert(0 && "error here"), are
9198 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00009199 return DiagnoseImpCast(S, E, T, CC,
9200 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00009201 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9202 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9203 // This covers the literal expressions that evaluate to Objective-C
9204 // objects.
9205 return DiagnoseImpCast(S, E, T, CC,
9206 diag::warn_impcast_objective_c_literal_to_bool);
9207 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009208 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9209 // Warn on pointer to bool conversion that is always true.
9210 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9211 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00009212 }
Richard Trieu021baa32011-09-23 20:10:00 +00009213 }
John McCall263a48b2010-01-04 23:31:57 +00009214
Douglas Gregor5054cb02015-07-07 03:58:22 +00009215 // Check implicit casts from Objective-C collection literals to specialized
9216 // collection types, e.g., NSArray<NSString *> *.
9217 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9218 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9219 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9220 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9221
John McCall263a48b2010-01-04 23:31:57 +00009222 // Strip vector types.
9223 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009224 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009225 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009226 return;
John McCallacf0ee52010-10-08 02:01:28 +00009227 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009228 }
Chris Lattneree7286f2011-06-14 04:51:15 +00009229
9230 // If the vector cast is cast between two vectors of the same size, it is
9231 // a bitcast, not a conversion.
9232 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9233 return;
John McCall263a48b2010-01-04 23:31:57 +00009234
9235 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9236 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9237 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00009238 if (auto VecTy = dyn_cast<VectorType>(Target))
9239 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00009240
9241 // Strip complex types.
9242 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009243 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009244 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009245 return;
9246
John McCallacf0ee52010-10-08 02:01:28 +00009247 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009248 }
John McCall263a48b2010-01-04 23:31:57 +00009249
9250 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9251 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9252 }
9253
9254 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9255 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9256
9257 // If the source is floating point...
9258 if (SourceBT && SourceBT->isFloatingPoint()) {
9259 // ...and the target is floating point...
9260 if (TargetBT && TargetBT->isFloatingPoint()) {
9261 // ...then warn if we're dropping FP rank.
9262
9263 // Builtin FP kinds are ordered by increasing FP rank.
9264 if (SourceBT->getKind() > TargetBT->getKind()) {
9265 // Don't warn about float constants that are precisely
9266 // representable in the target type.
9267 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009268 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00009269 // Value might be a float, a float vector, or a float complex.
9270 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00009271 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9272 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00009273 return;
9274 }
9275
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009276 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009277 return;
9278
John McCallacf0ee52010-10-08 02:01:28 +00009279 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00009280 }
9281 // ... or possibly if we're increasing rank, too
9282 else if (TargetBT->getKind() > SourceBT->getKind()) {
9283 if (S.SourceMgr.isInSystemMacro(CC))
9284 return;
9285
9286 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00009287 }
9288 return;
9289 }
9290
Richard Trieube234c32016-04-21 21:04:55 +00009291 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00009292 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009293 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009294 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00009295
Richard Trieube234c32016-04-21 21:04:55 +00009296 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00009297 }
John McCall263a48b2010-01-04 23:31:57 +00009298
Richard Smith54894fd2015-12-30 01:06:52 +00009299 // Detect the case where a call result is converted from floating-point to
9300 // to bool, and the final argument to the call is converted from bool, to
9301 // discover this typo:
9302 //
9303 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9304 //
9305 // FIXME: This is an incredibly special case; is there some more general
9306 // way to detect this class of misplaced-parentheses bug?
9307 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009308 // Check last argument of function call to see if it is an
9309 // implicit cast from a type matching the type the result
9310 // is being cast to.
9311 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00009312 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009313 Expr *LastA = CEx->getArg(NumArgs - 1);
9314 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00009315 if (isa<ImplicitCastExpr>(LastA) &&
9316 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009317 // Warn on this floating-point to bool conversion
9318 DiagnoseImpCast(S, E, T, CC,
9319 diag::warn_impcast_floating_point_to_bool);
9320 }
9321 }
9322 }
John McCall263a48b2010-01-04 23:31:57 +00009323 return;
9324 }
9325
Richard Trieu5b993502014-10-15 03:42:06 +00009326 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00009327
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009328 S.DiscardMisalignedMemberAddress(Target, E);
9329
David Blaikie9366d2b2012-06-19 21:19:06 +00009330 if (!Source->isIntegerType() || !Target->isIntegerType())
9331 return;
9332
David Blaikie7555b6a2012-05-15 16:56:36 +00009333 // TODO: remove this early return once the false positives for constant->bool
9334 // in templates, macros, etc, are reduced or removed.
9335 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9336 return;
9337
John McCallcc7e5bf2010-05-06 08:58:33 +00009338 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00009339 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00009340
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009341 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00009342 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009343 // TODO: this should happen for bitfield stores, too.
9344 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00009345 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009346 if (S.SourceMgr.isInSystemMacro(CC))
9347 return;
9348
John McCall18a2c2c2010-11-09 22:22:12 +00009349 std::string PrettySourceValue = Value.toString(10);
9350 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009351
Ted Kremenek33ba9952011-10-22 02:37:33 +00009352 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9353 S.PDiag(diag::warn_impcast_integer_precision_constant)
9354 << PrettySourceValue << PrettyTargetValue
9355 << E->getType() << T << E->getSourceRange()
9356 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00009357 return;
9358 }
9359
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009360 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9361 if (S.SourceMgr.isInSystemMacro(CC))
9362 return;
9363
David Blaikie9455da02012-04-12 22:40:54 +00009364 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00009365 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9366 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00009367 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00009368 }
9369
Richard Trieudcb55572016-01-29 23:51:16 +00009370 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9371 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9372 // Warn when doing a signed to signed conversion, warn if the positive
9373 // source value is exactly the width of the target type, which will
9374 // cause a negative value to be stored.
9375
9376 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00009377 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9378 !S.SourceMgr.isInSystemMacro(CC)) {
9379 if (isSameWidthConstantConversion(S, E, T, CC)) {
9380 std::string PrettySourceValue = Value.toString(10);
9381 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00009382
Richard Trieufc404c72016-02-05 23:02:38 +00009383 S.DiagRuntimeBehavior(
9384 E->getExprLoc(), E,
9385 S.PDiag(diag::warn_impcast_integer_precision_constant)
9386 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9387 << E->getSourceRange() << clang::SourceRange(CC));
9388 return;
Richard Trieudcb55572016-01-29 23:51:16 +00009389 }
9390 }
Richard Trieufc404c72016-02-05 23:02:38 +00009391
Richard Trieudcb55572016-01-29 23:51:16 +00009392 // Fall through for non-constants to give a sign conversion warning.
9393 }
9394
John McCallcc7e5bf2010-05-06 08:58:33 +00009395 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9396 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9397 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009398 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009399 return;
9400
John McCallcc7e5bf2010-05-06 08:58:33 +00009401 unsigned DiagID = diag::warn_impcast_integer_sign;
9402
9403 // Traditionally, gcc has warned about this under -Wsign-compare.
9404 // We also want to warn about it in -Wconversion.
9405 // So if -Wconversion is off, use a completely identical diagnostic
9406 // in the sign-compare group.
9407 // The conditional-checking code will
9408 if (ICContext) {
9409 DiagID = diag::warn_impcast_integer_sign_conditional;
9410 *ICContext = true;
9411 }
9412
John McCallacf0ee52010-10-08 02:01:28 +00009413 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00009414 }
9415
Douglas Gregora78f1932011-02-22 02:45:07 +00009416 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00009417 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9418 // type, to give us better diagnostics.
9419 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009420 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00009421 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9422 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9423 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9424 SourceType = S.Context.getTypeDeclType(Enum);
9425 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9426 }
9427 }
9428
Douglas Gregora78f1932011-02-22 02:45:07 +00009429 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9430 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00009431 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9432 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009433 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009434 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009435 return;
9436
Douglas Gregor364f7db2011-03-12 00:14:31 +00009437 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00009438 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009439 }
John McCall263a48b2010-01-04 23:31:57 +00009440}
9441
David Blaikie18e9ac72012-05-15 21:57:38 +00009442void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9443 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009444
9445void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00009446 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009447 E = E->IgnoreParenImpCasts();
9448
9449 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00009450 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009451
John McCallacf0ee52010-10-08 02:01:28 +00009452 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009453 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009454 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00009455}
9456
David Blaikie18e9ac72012-05-15 21:57:38 +00009457void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9458 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00009459 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009460
9461 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00009462 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9463 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009464
9465 // If -Wconversion would have warned about either of the candidates
9466 // for a signedness conversion to the context type...
9467 if (!Suspicious) return;
9468
9469 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009470 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00009471 return;
9472
John McCallcc7e5bf2010-05-06 08:58:33 +00009473 // ...then check whether it would have warned about either of the
9474 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00009475 if (E->getType() == T) return;
9476
9477 Suspicious = false;
9478 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9479 E->getType(), CC, &Suspicious);
9480 if (!Suspicious)
9481 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00009482 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009483}
9484
Richard Trieu65724892014-11-15 06:37:39 +00009485/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9486/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009487void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00009488 if (S.getLangOpts().Bool)
9489 return;
9490 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9491}
9492
John McCallcc7e5bf2010-05-06 08:58:33 +00009493/// AnalyzeImplicitConversions - Find and report any interesting
9494/// implicit conversions in the given expression. There are a couple
9495/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009496void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00009497 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00009498 Expr *E = OrigE->IgnoreParenImpCasts();
9499
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00009500 if (E->isTypeDependent() || E->isValueDependent())
9501 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00009502
John McCallcc7e5bf2010-05-06 08:58:33 +00009503 // For conditional operators, we analyze the arguments as if they
9504 // were being fed directly into the output.
9505 if (isa<ConditionalOperator>(E)) {
9506 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00009507 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009508 return;
9509 }
9510
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009511 // Check implicit argument conversions for function calls.
9512 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9513 CheckImplicitArgumentConversions(S, Call, CC);
9514
John McCallcc7e5bf2010-05-06 08:58:33 +00009515 // Go ahead and check any implicit conversions we might have skipped.
9516 // The non-canonical typecheck is just an optimization;
9517 // CheckImplicitConversion will filter out dead implicit conversions.
9518 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009519 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009520
9521 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00009522
9523 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9524 // The bound subexpressions in a PseudoObjectExpr are not reachable
9525 // as transitive children.
9526 // FIXME: Use a more uniform representation for this.
9527 for (auto *SE : POE->semantics())
9528 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9529 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00009530 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00009531
John McCallcc7e5bf2010-05-06 08:58:33 +00009532 // Skip past explicit casts.
9533 if (isa<ExplicitCastExpr>(E)) {
9534 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00009535 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009536 }
9537
John McCalld2a53122010-11-09 23:24:47 +00009538 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9539 // Do a somewhat different check with comparison operators.
9540 if (BO->isComparisonOp())
9541 return AnalyzeComparison(S, BO);
9542
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009543 // And with simple assignments.
9544 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00009545 return AnalyzeAssignment(S, BO);
9546 }
John McCallcc7e5bf2010-05-06 08:58:33 +00009547
9548 // These break the otherwise-useful invariant below. Fortunately,
9549 // we don't really need to recurse into them, because any internal
9550 // expressions should have been analyzed already when they were
9551 // built into statements.
9552 if (isa<StmtExpr>(E)) return;
9553
9554 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00009555 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00009556
9557 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00009558 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00009559 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00009560 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00009561 for (Stmt *SubStmt : E->children()) {
9562 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00009563 if (!ChildExpr)
9564 continue;
9565
Richard Trieu955231d2014-01-25 01:10:35 +00009566 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00009567 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00009568 // Ignore checking string literals that are in logical and operators.
9569 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00009570 continue;
9571 AnalyzeImplicitConversions(S, ChildExpr, CC);
9572 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009573
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009574 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00009575 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9576 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009577 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00009578
9579 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9580 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009581 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009582 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009583
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009584 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9585 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00009586 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009587}
9588
9589} // end anonymous namespace
9590
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009591/// Diagnose integer type and any valid implicit convertion to it.
9592static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9593 // Taking into account implicit conversions,
9594 // allow any integer.
9595 if (!E->getType()->isIntegerType()) {
9596 S.Diag(E->getLocStart(),
9597 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9598 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009599 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009600 // Potentially emit standard warnings for implicit conversions if enabled
9601 // using -Wconversion.
9602 CheckImplicitConversion(S, E, IntT, E->getLocStart());
9603 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009604}
9605
Richard Trieuc1888e02014-06-28 23:25:37 +00009606// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9607// Returns true when emitting a warning about taking the address of a reference.
9608static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00009609 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00009610 E = E->IgnoreParenImpCasts();
9611
9612 const FunctionDecl *FD = nullptr;
9613
9614 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9615 if (!DRE->getDecl()->getType()->isReferenceType())
9616 return false;
9617 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9618 if (!M->getMemberDecl()->getType()->isReferenceType())
9619 return false;
9620 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00009621 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00009622 return false;
9623 FD = Call->getDirectCallee();
9624 } else {
9625 return false;
9626 }
9627
9628 SemaRef.Diag(E->getExprLoc(), PD);
9629
9630 // If possible, point to location of function.
9631 if (FD) {
9632 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9633 }
9634
9635 return true;
9636}
9637
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009638// Returns true if the SourceLocation is expanded from any macro body.
9639// Returns false if the SourceLocation is invalid, is from not in a macro
9640// expansion, or is from expanded from a top-level macro argument.
9641static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9642 if (Loc.isInvalid())
9643 return false;
9644
9645 while (Loc.isMacroID()) {
9646 if (SM.isMacroBodyExpansion(Loc))
9647 return true;
9648 Loc = SM.getImmediateMacroCallerLoc(Loc);
9649 }
9650
9651 return false;
9652}
9653
Richard Trieu3bb8b562014-02-26 02:36:06 +00009654/// \brief Diagnose pointers that are always non-null.
9655/// \param E the expression containing the pointer
9656/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9657/// compared to a null pointer
9658/// \param IsEqual True when the comparison is equal to a null pointer
9659/// \param Range Extra SourceRange to highlight in the diagnostic
9660void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9661 Expr::NullPointerConstantKind NullKind,
9662 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00009663 if (!E)
9664 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009665
9666 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009667 if (E->getExprLoc().isMacroID()) {
9668 const SourceManager &SM = getSourceManager();
9669 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9670 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00009671 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009672 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009673 E = E->IgnoreImpCasts();
9674
9675 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9676
Richard Trieuf7432752014-06-06 21:39:26 +00009677 if (isa<CXXThisExpr>(E)) {
9678 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9679 : diag::warn_this_bool_conversion;
9680 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9681 return;
9682 }
9683
Richard Trieu3bb8b562014-02-26 02:36:06 +00009684 bool IsAddressOf = false;
9685
9686 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9687 if (UO->getOpcode() != UO_AddrOf)
9688 return;
9689 IsAddressOf = true;
9690 E = UO->getSubExpr();
9691 }
9692
Richard Trieuc1888e02014-06-28 23:25:37 +00009693 if (IsAddressOf) {
9694 unsigned DiagID = IsCompare
9695 ? diag::warn_address_of_reference_null_compare
9696 : diag::warn_address_of_reference_bool_conversion;
9697 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9698 << IsEqual;
9699 if (CheckForReference(*this, E, PD)) {
9700 return;
9701 }
9702 }
9703
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009704 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9705 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00009706 std::string Str;
9707 llvm::raw_string_ostream S(Str);
9708 E->printPretty(S, nullptr, getPrintingPolicy());
9709 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9710 : diag::warn_cast_nonnull_to_bool;
9711 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9712 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009713 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00009714 };
9715
9716 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9717 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9718 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009719 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9720 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009721 return;
9722 }
9723 }
9724 }
9725
Richard Trieu3bb8b562014-02-26 02:36:06 +00009726 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00009727 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009728 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9729 D = R->getDecl();
9730 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9731 D = M->getMemberDecl();
9732 }
9733
9734 // Weak Decls can be null.
9735 if (!D || D->isWeak())
9736 return;
George Burgess IV850269a2015-12-08 22:02:00 +00009737
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009738 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00009739 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9740 if (getCurFunction() &&
9741 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009742 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9743 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009744 return;
9745 }
9746
9747 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +00009748 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +00009749 assert(ParamIter != FD->param_end());
9750 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9751
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009752 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9753 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009754 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +00009755 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009756 }
George Burgess IV850269a2015-12-08 22:02:00 +00009757
9758 for (unsigned ArgNo : NonNull->args()) {
9759 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009760 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009761 return;
9762 }
George Burgess IV850269a2015-12-08 22:02:00 +00009763 }
9764 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009765 }
9766 }
George Burgess IV850269a2015-12-08 22:02:00 +00009767 }
9768
Richard Trieu3bb8b562014-02-26 02:36:06 +00009769 QualType T = D->getType();
9770 const bool IsArray = T->isArrayType();
9771 const bool IsFunction = T->isFunctionType();
9772
Richard Trieuc1888e02014-06-28 23:25:37 +00009773 // Address of function is used to silence the function warning.
9774 if (IsAddressOf && IsFunction) {
9775 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009776 }
9777
9778 // Found nothing.
9779 if (!IsAddressOf && !IsFunction && !IsArray)
9780 return;
9781
9782 // Pretty print the expression for the diagnostic.
9783 std::string Str;
9784 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00009785 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00009786
9787 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9788 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00009789 enum {
9790 AddressOf,
9791 FunctionPointer,
9792 ArrayPointer
9793 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009794 if (IsAddressOf)
9795 DiagType = AddressOf;
9796 else if (IsFunction)
9797 DiagType = FunctionPointer;
9798 else if (IsArray)
9799 DiagType = ArrayPointer;
9800 else
9801 llvm_unreachable("Could not determine diagnostic.");
9802 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9803 << Range << IsEqual;
9804
9805 if (!IsFunction)
9806 return;
9807
9808 // Suggest '&' to silence the function warning.
9809 Diag(E->getExprLoc(), diag::note_function_warning_silence)
9810 << FixItHint::CreateInsertion(E->getLocStart(), "&");
9811
9812 // Check to see if '()' fixit should be emitted.
9813 QualType ReturnType;
9814 UnresolvedSet<4> NonTemplateOverloads;
9815 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9816 if (ReturnType.isNull())
9817 return;
9818
9819 if (IsCompare) {
9820 // There are two cases here. If there is null constant, the only suggest
9821 // for a pointer return type. If the null is 0, then suggest if the return
9822 // type is a pointer or an integer type.
9823 if (!ReturnType->isPointerType()) {
9824 if (NullKind == Expr::NPCK_ZeroExpression ||
9825 NullKind == Expr::NPCK_ZeroLiteral) {
9826 if (!ReturnType->isIntegerType())
9827 return;
9828 } else {
9829 return;
9830 }
9831 }
9832 } else { // !IsCompare
9833 // For function to bool, only suggest if the function pointer has bool
9834 // return type.
9835 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9836 return;
9837 }
9838 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00009839 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00009840}
9841
John McCallcc7e5bf2010-05-06 08:58:33 +00009842/// Diagnoses "dangerous" implicit conversions within the given
9843/// expression (which is a full expression). Implements -Wconversion
9844/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009845///
9846/// \param CC the "context" location of the implicit conversion, i.e.
9847/// the most location of the syntactic entity requiring the implicit
9848/// conversion
9849void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009850 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00009851 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00009852 return;
9853
9854 // Don't diagnose for value- or type-dependent expressions.
9855 if (E->isTypeDependent() || E->isValueDependent())
9856 return;
9857
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009858 // Check for array bounds violations in cases where the check isn't triggered
9859 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9860 // ArraySubscriptExpr is on the RHS of a variable initialization.
9861 CheckArrayAccess(E);
9862
John McCallacf0ee52010-10-08 02:01:28 +00009863 // This is not the right CC for (e.g.) a variable initialization.
9864 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009865}
9866
Richard Trieu65724892014-11-15 06:37:39 +00009867/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9868/// Input argument E is a logical expression.
9869void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9870 ::CheckBoolLikeConversion(*this, E, CC);
9871}
9872
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009873/// Diagnose when expression is an integer constant expression and its evaluation
9874/// results in integer overflow
9875void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00009876 // Use a work list to deal with nested struct initializers.
9877 SmallVector<Expr *, 2> Exprs(1, E);
9878
9879 do {
9880 Expr *E = Exprs.pop_back_val();
9881
9882 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9883 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9884 continue;
9885 }
9886
9887 if (auto InitList = dyn_cast<InitListExpr>(E))
9888 Exprs.append(InitList->inits().begin(), InitList->inits().end());
9889 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009890}
9891
Richard Smithc406cb72013-01-17 01:17:56 +00009892namespace {
9893/// \brief Visitor for expressions which looks for unsequenced operations on the
9894/// same object.
9895class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009896 typedef EvaluatedExprVisitor<SequenceChecker> Base;
9897
Richard Smithc406cb72013-01-17 01:17:56 +00009898 /// \brief A tree of sequenced regions within an expression. Two regions are
9899 /// unsequenced if one is an ancestor or a descendent of the other. When we
9900 /// finish processing an expression with sequencing, such as a comma
9901 /// expression, we fold its tree nodes into its parent, since they are
9902 /// unsequenced with respect to nodes we will visit later.
9903 class SequenceTree {
9904 struct Value {
9905 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9906 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +00009907 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +00009908 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009909 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00009910
9911 public:
9912 /// \brief A region within an expression which may be sequenced with respect
9913 /// to some other region.
9914 class Seq {
9915 explicit Seq(unsigned N) : Index(N) {}
9916 unsigned Index;
9917 friend class SequenceTree;
9918 public:
9919 Seq() : Index(0) {}
9920 };
9921
9922 SequenceTree() { Values.push_back(Value(0)); }
9923 Seq root() const { return Seq(0); }
9924
9925 /// \brief Create a new sequence of operations, which is an unsequenced
9926 /// subset of \p Parent. This sequence of operations is sequenced with
9927 /// respect to other children of \p Parent.
9928 Seq allocate(Seq Parent) {
9929 Values.push_back(Value(Parent.Index));
9930 return Seq(Values.size() - 1);
9931 }
9932
9933 /// \brief Merge a sequence of operations into its parent.
9934 void merge(Seq S) {
9935 Values[S.Index].Merged = true;
9936 }
9937
9938 /// \brief Determine whether two operations are unsequenced. This operation
9939 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9940 /// should have been merged into its parent as appropriate.
9941 bool isUnsequenced(Seq Cur, Seq Old) {
9942 unsigned C = representative(Cur.Index);
9943 unsigned Target = representative(Old.Index);
9944 while (C >= Target) {
9945 if (C == Target)
9946 return true;
9947 C = Values[C].Parent;
9948 }
9949 return false;
9950 }
9951
9952 private:
9953 /// \brief Pick a representative for a sequence.
9954 unsigned representative(unsigned K) {
9955 if (Values[K].Merged)
9956 // Perform path compression as we go.
9957 return Values[K].Parent = representative(Values[K].Parent);
9958 return K;
9959 }
9960 };
9961
9962 /// An object for which we can track unsequenced uses.
9963 typedef NamedDecl *Object;
9964
9965 /// Different flavors of object usage which we track. We only track the
9966 /// least-sequenced usage of each kind.
9967 enum UsageKind {
9968 /// A read of an object. Multiple unsequenced reads are OK.
9969 UK_Use,
9970 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00009971 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00009972 UK_ModAsValue,
9973 /// A modification of an object which is not sequenced before the value
9974 /// computation of the expression, such as n++.
9975 UK_ModAsSideEffect,
9976
9977 UK_Count = UK_ModAsSideEffect + 1
9978 };
9979
9980 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00009981 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00009982 Expr *Use;
9983 SequenceTree::Seq Seq;
9984 };
9985
9986 struct UsageInfo {
9987 UsageInfo() : Diagnosed(false) {}
9988 Usage Uses[UK_Count];
9989 /// Have we issued a diagnostic for this variable already?
9990 bool Diagnosed;
9991 };
9992 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9993
9994 Sema &SemaRef;
9995 /// Sequenced regions within the expression.
9996 SequenceTree Tree;
9997 /// Declaration modifications and references which we have seen.
9998 UsageInfoMap UsageMap;
9999 /// The region we are currently within.
10000 SequenceTree::Seq Region;
10001 /// Filled in with declarations which were modified as a side-effect
10002 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010003 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +000010004 /// Expressions to check later. We defer checking these to reduce
10005 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010006 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000010007
10008 /// RAII object wrapping the visitation of a sequenced subexpression of an
10009 /// expression. At the end of this process, the side-effects of the evaluation
10010 /// become sequenced with respect to the value computation of the result, so
10011 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10012 /// UK_ModAsValue.
10013 struct SequencedSubexpression {
10014 SequencedSubexpression(SequenceChecker &Self)
10015 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10016 Self.ModAsSideEffect = &ModAsSideEffect;
10017 }
10018 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000010019 for (auto &M : llvm::reverse(ModAsSideEffect)) {
10020 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000010021 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000010022 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10023 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000010024 }
10025 Self.ModAsSideEffect = OldModAsSideEffect;
10026 }
10027
10028 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010029 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
10030 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000010031 };
10032
Richard Smith40238f02013-06-20 22:21:56 +000010033 /// RAII object wrapping the visitation of a subexpression which we might
10034 /// choose to evaluate as a constant. If any subexpression is evaluated and
10035 /// found to be non-constant, this allows us to suppress the evaluation of
10036 /// the outer expression.
10037 class EvaluationTracker {
10038 public:
10039 EvaluationTracker(SequenceChecker &Self)
10040 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
10041 Self.EvalTracker = this;
10042 }
10043 ~EvaluationTracker() {
10044 Self.EvalTracker = Prev;
10045 if (Prev)
10046 Prev->EvalOK &= EvalOK;
10047 }
10048
10049 bool evaluate(const Expr *E, bool &Result) {
10050 if (!EvalOK || E->isValueDependent())
10051 return false;
10052 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10053 return EvalOK;
10054 }
10055
10056 private:
10057 SequenceChecker &Self;
10058 EvaluationTracker *Prev;
10059 bool EvalOK;
10060 } *EvalTracker;
10061
Richard Smithc406cb72013-01-17 01:17:56 +000010062 /// \brief Find the object which is produced by the specified expression,
10063 /// if any.
10064 Object getObject(Expr *E, bool Mod) const {
10065 E = E->IgnoreParenCasts();
10066 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10067 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10068 return getObject(UO->getSubExpr(), Mod);
10069 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10070 if (BO->getOpcode() == BO_Comma)
10071 return getObject(BO->getRHS(), Mod);
10072 if (Mod && BO->isAssignmentOp())
10073 return getObject(BO->getLHS(), Mod);
10074 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10075 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10076 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10077 return ME->getMemberDecl();
10078 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10079 // FIXME: If this is a reference, map through to its value.
10080 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000010081 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010082 }
10083
10084 /// \brief Note that an object was modified or used by an expression.
10085 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10086 Usage &U = UI.Uses[UK];
10087 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10088 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10089 ModAsSideEffect->push_back(std::make_pair(O, U));
10090 U.Use = Ref;
10091 U.Seq = Region;
10092 }
10093 }
10094 /// \brief Check whether a modification or use conflicts with a prior usage.
10095 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10096 bool IsModMod) {
10097 if (UI.Diagnosed)
10098 return;
10099
10100 const Usage &U = UI.Uses[OtherKind];
10101 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10102 return;
10103
10104 Expr *Mod = U.Use;
10105 Expr *ModOrUse = Ref;
10106 if (OtherKind == UK_Use)
10107 std::swap(Mod, ModOrUse);
10108
10109 SemaRef.Diag(Mod->getExprLoc(),
10110 IsModMod ? diag::warn_unsequenced_mod_mod
10111 : diag::warn_unsequenced_mod_use)
10112 << O << SourceRange(ModOrUse->getExprLoc());
10113 UI.Diagnosed = true;
10114 }
10115
10116 void notePreUse(Object O, Expr *Use) {
10117 UsageInfo &U = UsageMap[O];
10118 // Uses conflict with other modifications.
10119 checkUsage(O, U, Use, UK_ModAsValue, false);
10120 }
10121 void notePostUse(Object O, Expr *Use) {
10122 UsageInfo &U = UsageMap[O];
10123 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10124 addUsage(U, O, Use, UK_Use);
10125 }
10126
10127 void notePreMod(Object O, Expr *Mod) {
10128 UsageInfo &U = UsageMap[O];
10129 // Modifications conflict with other modifications and with uses.
10130 checkUsage(O, U, Mod, UK_ModAsValue, true);
10131 checkUsage(O, U, Mod, UK_Use, false);
10132 }
10133 void notePostMod(Object O, Expr *Use, UsageKind UK) {
10134 UsageInfo &U = UsageMap[O];
10135 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10136 addUsage(U, O, Use, UK);
10137 }
10138
10139public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010140 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +000010141 : Base(S.Context), SemaRef(S), Region(Tree.root()),
10142 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010143 Visit(E);
10144 }
10145
10146 void VisitStmt(Stmt *S) {
10147 // Skip all statements which aren't expressions for now.
10148 }
10149
10150 void VisitExpr(Expr *E) {
10151 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000010152 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000010153 }
10154
10155 void VisitCastExpr(CastExpr *E) {
10156 Object O = Object();
10157 if (E->getCastKind() == CK_LValueToRValue)
10158 O = getObject(E->getSubExpr(), false);
10159
10160 if (O)
10161 notePreUse(O, E);
10162 VisitExpr(E);
10163 if (O)
10164 notePostUse(O, E);
10165 }
10166
10167 void VisitBinComma(BinaryOperator *BO) {
10168 // C++11 [expr.comma]p1:
10169 // Every value computation and side effect associated with the left
10170 // expression is sequenced before every value computation and side
10171 // effect associated with the right expression.
10172 SequenceTree::Seq LHS = Tree.allocate(Region);
10173 SequenceTree::Seq RHS = Tree.allocate(Region);
10174 SequenceTree::Seq OldRegion = Region;
10175
10176 {
10177 SequencedSubexpression SeqLHS(*this);
10178 Region = LHS;
10179 Visit(BO->getLHS());
10180 }
10181
10182 Region = RHS;
10183 Visit(BO->getRHS());
10184
10185 Region = OldRegion;
10186
10187 // Forget that LHS and RHS are sequenced. They are both unsequenced
10188 // with respect to other stuff.
10189 Tree.merge(LHS);
10190 Tree.merge(RHS);
10191 }
10192
10193 void VisitBinAssign(BinaryOperator *BO) {
10194 // The modification is sequenced after the value computation of the LHS
10195 // and RHS, so check it before inspecting the operands and update the
10196 // map afterwards.
10197 Object O = getObject(BO->getLHS(), true);
10198 if (!O)
10199 return VisitExpr(BO);
10200
10201 notePreMod(O, BO);
10202
10203 // C++11 [expr.ass]p7:
10204 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10205 // only once.
10206 //
10207 // Therefore, for a compound assignment operator, O is considered used
10208 // everywhere except within the evaluation of E1 itself.
10209 if (isa<CompoundAssignOperator>(BO))
10210 notePreUse(O, BO);
10211
10212 Visit(BO->getLHS());
10213
10214 if (isa<CompoundAssignOperator>(BO))
10215 notePostUse(O, BO);
10216
10217 Visit(BO->getRHS());
10218
Richard Smith83e37bee2013-06-26 23:16:51 +000010219 // C++11 [expr.ass]p1:
10220 // the assignment is sequenced [...] before the value computation of the
10221 // assignment expression.
10222 // C11 6.5.16/3 has no such rule.
10223 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10224 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010225 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010226
Richard Smithc406cb72013-01-17 01:17:56 +000010227 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10228 VisitBinAssign(CAO);
10229 }
10230
10231 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10232 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10233 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10234 Object O = getObject(UO->getSubExpr(), true);
10235 if (!O)
10236 return VisitExpr(UO);
10237
10238 notePreMod(O, UO);
10239 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000010240 // C++11 [expr.pre.incr]p1:
10241 // the expression ++x is equivalent to x+=1
10242 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10243 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010244 }
10245
10246 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10247 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10248 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10249 Object O = getObject(UO->getSubExpr(), true);
10250 if (!O)
10251 return VisitExpr(UO);
10252
10253 notePreMod(O, UO);
10254 Visit(UO->getSubExpr());
10255 notePostMod(O, UO, UK_ModAsSideEffect);
10256 }
10257
10258 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10259 void VisitBinLOr(BinaryOperator *BO) {
10260 // The side-effects of the LHS of an '&&' are sequenced before the
10261 // value computation of the RHS, and hence before the value computation
10262 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10263 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000010264 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010265 {
10266 SequencedSubexpression Sequenced(*this);
10267 Visit(BO->getLHS());
10268 }
10269
10270 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010271 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010272 if (!Result)
10273 Visit(BO->getRHS());
10274 } else {
10275 // Check for unsequenced operations in the RHS, treating it as an
10276 // entirely separate evaluation.
10277 //
10278 // FIXME: If there are operations in the RHS which are unsequenced
10279 // with respect to operations outside the RHS, and those operations
10280 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000010281 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010282 }
Richard Smithc406cb72013-01-17 01:17:56 +000010283 }
10284 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000010285 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010286 {
10287 SequencedSubexpression Sequenced(*this);
10288 Visit(BO->getLHS());
10289 }
10290
10291 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010292 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010293 if (Result)
10294 Visit(BO->getRHS());
10295 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000010296 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010297 }
Richard Smithc406cb72013-01-17 01:17:56 +000010298 }
10299
10300 // Only visit the condition, unless we can be sure which subexpression will
10301 // be chosen.
10302 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000010303 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000010304 {
10305 SequencedSubexpression Sequenced(*this);
10306 Visit(CO->getCond());
10307 }
Richard Smithc406cb72013-01-17 01:17:56 +000010308
10309 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010310 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000010311 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010312 else {
Richard Smithd33f5202013-01-17 23:18:09 +000010313 WorkList.push_back(CO->getTrueExpr());
10314 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010315 }
Richard Smithc406cb72013-01-17 01:17:56 +000010316 }
10317
Richard Smithe3dbfe02013-06-30 10:40:20 +000010318 void VisitCallExpr(CallExpr *CE) {
10319 // C++11 [intro.execution]p15:
10320 // When calling a function [...], every value computation and side effect
10321 // associated with any argument expression, or with the postfix expression
10322 // designating the called function, is sequenced before execution of every
10323 // expression or statement in the body of the function [and thus before
10324 // the value computation of its result].
10325 SequencedSubexpression Sequenced(*this);
10326 Base::VisitCallExpr(CE);
10327
10328 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10329 }
10330
Richard Smithc406cb72013-01-17 01:17:56 +000010331 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010332 // This is a call, so all subexpressions are sequenced before the result.
10333 SequencedSubexpression Sequenced(*this);
10334
Richard Smithc406cb72013-01-17 01:17:56 +000010335 if (!CCE->isListInitialization())
10336 return VisitExpr(CCE);
10337
10338 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010339 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010340 SequenceTree::Seq Parent = Region;
10341 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10342 E = CCE->arg_end();
10343 I != E; ++I) {
10344 Region = Tree.allocate(Parent);
10345 Elts.push_back(Region);
10346 Visit(*I);
10347 }
10348
10349 // Forget that the initializers are sequenced.
10350 Region = Parent;
10351 for (unsigned I = 0; I < Elts.size(); ++I)
10352 Tree.merge(Elts[I]);
10353 }
10354
10355 void VisitInitListExpr(InitListExpr *ILE) {
10356 if (!SemaRef.getLangOpts().CPlusPlus11)
10357 return VisitExpr(ILE);
10358
10359 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010360 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010361 SequenceTree::Seq Parent = Region;
10362 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10363 Expr *E = ILE->getInit(I);
10364 if (!E) continue;
10365 Region = Tree.allocate(Parent);
10366 Elts.push_back(Region);
10367 Visit(E);
10368 }
10369
10370 // Forget that the initializers are sequenced.
10371 Region = Parent;
10372 for (unsigned I = 0; I < Elts.size(); ++I)
10373 Tree.merge(Elts[I]);
10374 }
10375};
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010376} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +000010377
10378void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010379 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000010380 WorkList.push_back(E);
10381 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000010382 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000010383 SequenceChecker(*this, Item, WorkList);
10384 }
Richard Smithc406cb72013-01-17 01:17:56 +000010385}
10386
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010387void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10388 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010389 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000010390 if (!E->isInstantiationDependent())
10391 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010392 if (!IsConstexpr && !E->isValueDependent())
10393 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010394 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000010395}
10396
John McCall1f425642010-11-11 03:21:53 +000010397void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10398 FieldDecl *BitField,
10399 Expr *Init) {
10400 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10401}
10402
David Majnemer61a5bbf2015-04-07 22:08:51 +000010403static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10404 SourceLocation Loc) {
10405 if (!PType->isVariablyModifiedType())
10406 return;
10407 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10408 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10409 return;
10410 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000010411 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10412 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10413 return;
10414 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000010415 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10416 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10417 return;
10418 }
10419
10420 const ArrayType *AT = S.Context.getAsArrayType(PType);
10421 if (!AT)
10422 return;
10423
10424 if (AT->getSizeModifier() != ArrayType::Star) {
10425 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10426 return;
10427 }
10428
10429 S.Diag(Loc, diag::err_array_star_in_function_definition);
10430}
10431
Mike Stump0c2ec772010-01-21 03:59:47 +000010432/// CheckParmsForFunctionDef - Check that the parameters of the given
10433/// function are appropriate for the definition of a function. This
10434/// takes care of any checks that cannot be performed on the
10435/// declaration itself, e.g., that the types of each of the function
10436/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000010437bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000010438 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010439 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000010440 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010441 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10442 // function declarator that is part of a function definition of
10443 // that function shall not have incomplete type.
10444 //
10445 // This is also C++ [dcl.fct]p6.
10446 if (!Param->isInvalidDecl() &&
10447 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010448 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010449 Param->setInvalidDecl();
10450 HasInvalidParm = true;
10451 }
10452
10453 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10454 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000010455 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000010456 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000010457 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000010458 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000010459 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000010460
10461 // C99 6.7.5.3p12:
10462 // If the function declarator is not part of a definition of that
10463 // function, parameters may have incomplete type and may use the [*]
10464 // notation in their sequences of declarator specifiers to specify
10465 // variable length array types.
10466 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000010467 // FIXME: This diagnostic should point the '[*]' if source-location
10468 // information is added for it.
10469 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010470
10471 // MSVC destroys objects passed by value in the callee. Therefore a
10472 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010473 // object's destructor. However, we don't perform any direct access check
10474 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +000010475 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10476 .getCXXABI()
10477 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +000010478 if (!Param->isInvalidDecl()) {
10479 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10480 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10481 if (!ClassDecl->isInvalidDecl() &&
10482 !ClassDecl->hasIrrelevantDestructor() &&
10483 !ClassDecl->isDependentContext()) {
10484 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10485 MarkFunctionReferenced(Param->getLocation(), Destructor);
10486 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10487 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010488 }
10489 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010490 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010491
10492 // Parameters with the pass_object_size attribute only need to be marked
10493 // constant at function definitions. Because we lack information about
10494 // whether we're on a declaration or definition when we're instantiating the
10495 // attribute, we need to check for constness here.
10496 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10497 if (!Param->getType().isConstQualified())
10498 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10499 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000010500 }
10501
10502 return HasInvalidParm;
10503}
John McCall2b5c1b22010-08-12 21:44:57 +000010504
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010505/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10506/// or MemberExpr.
10507static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10508 ASTContext &Context) {
10509 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10510 return Context.getDeclAlign(DRE->getDecl());
10511
10512 if (const auto *ME = dyn_cast<MemberExpr>(E))
10513 return Context.getDeclAlign(ME->getMemberDecl());
10514
10515 return TypeAlign;
10516}
10517
John McCall2b5c1b22010-08-12 21:44:57 +000010518/// CheckCastAlign - Implements -Wcast-align, which warns when a
10519/// pointer cast increases the alignment requirements.
10520void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10521 // This is actually a lot of work to potentially be doing on every
10522 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010523 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000010524 return;
10525
10526 // Ignore dependent types.
10527 if (T->isDependentType() || Op->getType()->isDependentType())
10528 return;
10529
10530 // Require that the destination be a pointer type.
10531 const PointerType *DestPtr = T->getAs<PointerType>();
10532 if (!DestPtr) return;
10533
10534 // If the destination has alignment 1, we're done.
10535 QualType DestPointee = DestPtr->getPointeeType();
10536 if (DestPointee->isIncompleteType()) return;
10537 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10538 if (DestAlign.isOne()) return;
10539
10540 // Require that the source be a pointer type.
10541 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10542 if (!SrcPtr) return;
10543 QualType SrcPointee = SrcPtr->getPointeeType();
10544
10545 // Whitelist casts from cv void*. We already implicitly
10546 // whitelisted casts to cv void*, since they have alignment 1.
10547 // Also whitelist casts involving incomplete types, which implicitly
10548 // includes 'void'.
10549 if (SrcPointee->isIncompleteType()) return;
10550
10551 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010552
10553 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10554 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10555 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10556 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10557 if (UO->getOpcode() == UO_AddrOf)
10558 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10559 }
10560
John McCall2b5c1b22010-08-12 21:44:57 +000010561 if (SrcAlign >= DestAlign) return;
10562
10563 Diag(TRange.getBegin(), diag::warn_cast_align)
10564 << Op->getType() << T
10565 << static_cast<unsigned>(SrcAlign.getQuantity())
10566 << static_cast<unsigned>(DestAlign.getQuantity())
10567 << TRange << Op->getSourceRange();
10568}
10569
Chandler Carruth28389f02011-08-05 09:10:50 +000010570/// \brief Check whether this array fits the idiom of a size-one tail padded
10571/// array member of a struct.
10572///
10573/// We avoid emitting out-of-bounds access warnings for such arrays as they are
10574/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000010575static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000010576 const NamedDecl *ND) {
10577 if (Size != 1 || !ND) return false;
10578
10579 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10580 if (!FD) return false;
10581
10582 // Don't consider sizes resulting from macro expansions or template argument
10583 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000010584
10585 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010586 while (TInfo) {
10587 TypeLoc TL = TInfo->getTypeLoc();
10588 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000010589 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10590 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010591 TInfo = TDL->getTypeSourceInfo();
10592 continue;
10593 }
David Blaikie6adc78e2013-02-18 22:06:02 +000010594 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10595 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000010596 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10597 return false;
10598 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010599 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000010600 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010601
10602 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000010603 if (!RD) return false;
10604 if (RD->isUnion()) return false;
10605 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10606 if (!CRD->isStandardLayout()) return false;
10607 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010608
Benjamin Kramer8c543672011-08-06 03:04:42 +000010609 // See if this is the last field decl in the record.
10610 const Decl *D = FD;
10611 while ((D = D->getNextDeclInContext()))
10612 if (isa<FieldDecl>(D))
10613 return false;
10614 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000010615}
10616
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010617void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010618 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000010619 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010620 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010621 if (IndexExpr->isValueDependent())
10622 return;
10623
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010624 const Type *EffectiveType =
10625 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010626 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010627 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010628 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010629 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000010630 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000010631
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010632 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000010633 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000010634 return;
Richard Smith13f67182011-12-16 19:31:14 +000010635 if (IndexNegated)
10636 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000010637
Craig Topperc3ec1492014-05-26 06:22:03 +000010638 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000010639 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10640 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +000010641 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +000010642 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +000010643
Ted Kremeneke4b316c2011-02-23 23:06:04 +000010644 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010645 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000010646 if (!size.isStrictlyPositive())
10647 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010648
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010649 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000010650 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010651 // Make sure we're comparing apples to apples when comparing index to size
10652 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10653 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000010654 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000010655 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010656 if (ptrarith_typesize != array_typesize) {
10657 // There's a cast to a different size type involved
10658 uint64_t ratio = array_typesize / ptrarith_typesize;
10659 // TODO: Be smarter about handling cases where array_typesize is not a
10660 // multiple of ptrarith_typesize
10661 if (ptrarith_typesize * ratio == array_typesize)
10662 size *= llvm::APInt(size.getBitWidth(), ratio);
10663 }
10664 }
10665
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010666 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010667 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010668 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010669 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010670
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010671 // For array subscripting the index must be less than size, but for pointer
10672 // arithmetic also allow the index (offset) to be equal to size since
10673 // computing the next address after the end of the array is legal and
10674 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010675 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000010676 return;
10677
10678 // Also don't warn for arrays of size 1 which are members of some
10679 // structure. These are often used to approximate flexible arrays in C89
10680 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010681 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000010682 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010683
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010684 // Suppress the warning if the subscript expression (as identified by the
10685 // ']' location) and the index expression are both from macro expansions
10686 // within a system header.
10687 if (ASE) {
10688 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10689 ASE->getRBracketLoc());
10690 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10691 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10692 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000010693 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010694 return;
10695 }
10696 }
10697
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010698 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010699 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010700 DiagID = diag::warn_array_index_exceeds_bounds;
10701
10702 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10703 PDiag(DiagID) << index.toString(10, true)
10704 << size.toString(10, true)
10705 << (unsigned)size.getLimitedValue(~0U)
10706 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010707 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010708 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010709 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010710 DiagID = diag::warn_ptr_arith_precedes_bounds;
10711 if (index.isNegative()) index = -index;
10712 }
10713
10714 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10715 PDiag(DiagID) << index.toString(10, true)
10716 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000010717 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000010718
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000010719 if (!ND) {
10720 // Try harder to find a NamedDecl to point at in the note.
10721 while (const ArraySubscriptExpr *ASE =
10722 dyn_cast<ArraySubscriptExpr>(BaseExpr))
10723 BaseExpr = ASE->getBase()->IgnoreParenCasts();
10724 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10725 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10726 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10727 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10728 }
10729
Chandler Carruth1af88f12011-02-17 21:10:52 +000010730 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010731 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10732 PDiag(diag::note_array_index_out_of_bounds)
10733 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000010734}
10735
Ted Kremenekdf26df72011-03-01 18:41:00 +000010736void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010737 int AllowOnePastEnd = 0;
10738 while (expr) {
10739 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000010740 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010741 case Stmt::ArraySubscriptExprClass: {
10742 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010743 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010744 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +000010745 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010746 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010747 case Stmt::OMPArraySectionExprClass: {
10748 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10749 if (ASE->getLowerBound())
10750 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10751 /*ASE=*/nullptr, AllowOnePastEnd > 0);
10752 return;
10753 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010754 case Stmt::UnaryOperatorClass: {
10755 // Only unwrap the * and & unary operators
10756 const UnaryOperator *UO = cast<UnaryOperator>(expr);
10757 expr = UO->getSubExpr();
10758 switch (UO->getOpcode()) {
10759 case UO_AddrOf:
10760 AllowOnePastEnd++;
10761 break;
10762 case UO_Deref:
10763 AllowOnePastEnd--;
10764 break;
10765 default:
10766 return;
10767 }
10768 break;
10769 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010770 case Stmt::ConditionalOperatorClass: {
10771 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10772 if (const Expr *lhs = cond->getLHS())
10773 CheckArrayAccess(lhs);
10774 if (const Expr *rhs = cond->getRHS())
10775 CheckArrayAccess(rhs);
10776 return;
10777 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000010778 case Stmt::CXXOperatorCallExprClass: {
10779 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
10780 for (const auto *Arg : OCE->arguments())
10781 CheckArrayAccess(Arg);
10782 return;
10783 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010784 default:
10785 return;
10786 }
Peter Collingbourne91147592011-04-15 00:35:48 +000010787 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010788}
John McCall31168b02011-06-15 23:02:42 +000010789
10790//===--- CHECK: Objective-C retain cycles ----------------------------------//
10791
10792namespace {
10793 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +000010794 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +000010795 VarDecl *Variable;
10796 SourceRange Range;
10797 SourceLocation Loc;
10798 bool Indirect;
10799
10800 void setLocsFrom(Expr *e) {
10801 Loc = e->getExprLoc();
10802 Range = e->getSourceRange();
10803 }
10804 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010805} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010806
10807/// Consider whether capturing the given variable can possibly lead to
10808/// a retain cycle.
10809static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010810 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000010811 // lifetime. In MRR, it's captured strongly if the variable is
10812 // __block and has an appropriate type.
10813 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10814 return false;
10815
10816 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010817 if (ref)
10818 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000010819 return true;
10820}
10821
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010822static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000010823 while (true) {
10824 e = e->IgnoreParens();
10825 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10826 switch (cast->getCastKind()) {
10827 case CK_BitCast:
10828 case CK_LValueBitCast:
10829 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000010830 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000010831 e = cast->getSubExpr();
10832 continue;
10833
John McCall31168b02011-06-15 23:02:42 +000010834 default:
10835 return false;
10836 }
10837 }
10838
10839 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10840 ObjCIvarDecl *ivar = ref->getDecl();
10841 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10842 return false;
10843
10844 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010845 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000010846 return false;
10847
10848 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10849 owner.Indirect = true;
10850 return true;
10851 }
10852
10853 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10854 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10855 if (!var) return false;
10856 return considerVariable(var, ref, owner);
10857 }
10858
John McCall31168b02011-06-15 23:02:42 +000010859 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10860 if (member->isArrow()) return false;
10861
10862 // Don't count this as an indirect ownership.
10863 e = member->getBase();
10864 continue;
10865 }
10866
John McCallfe96e0b2011-11-06 09:01:30 +000010867 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10868 // Only pay attention to pseudo-objects on property references.
10869 ObjCPropertyRefExpr *pre
10870 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10871 ->IgnoreParens());
10872 if (!pre) return false;
10873 if (pre->isImplicitProperty()) return false;
10874 ObjCPropertyDecl *property = pre->getExplicitProperty();
10875 if (!property->isRetaining() &&
10876 !(property->getPropertyIvarDecl() &&
10877 property->getPropertyIvarDecl()->getType()
10878 .getObjCLifetime() == Qualifiers::OCL_Strong))
10879 return false;
10880
10881 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010882 if (pre->isSuperReceiver()) {
10883 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10884 if (!owner.Variable)
10885 return false;
10886 owner.Loc = pre->getLocation();
10887 owner.Range = pre->getSourceRange();
10888 return true;
10889 }
John McCallfe96e0b2011-11-06 09:01:30 +000010890 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10891 ->getSourceExpr());
10892 continue;
10893 }
10894
John McCall31168b02011-06-15 23:02:42 +000010895 // Array ivars?
10896
10897 return false;
10898 }
10899}
10900
10901namespace {
10902 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10903 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10904 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010905 Context(Context), Variable(variable), Capturer(nullptr),
10906 VarWillBeReased(false) {}
10907 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000010908 VarDecl *Variable;
10909 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010910 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +000010911
10912 void VisitDeclRefExpr(DeclRefExpr *ref) {
10913 if (ref->getDecl() == Variable && !Capturer)
10914 Capturer = ref;
10915 }
10916
John McCall31168b02011-06-15 23:02:42 +000010917 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10918 if (Capturer) return;
10919 Visit(ref->getBase());
10920 if (Capturer && ref->isFreeIvar())
10921 Capturer = ref;
10922 }
10923
10924 void VisitBlockExpr(BlockExpr *block) {
10925 // Look inside nested blocks
10926 if (block->getBlockDecl()->capturesVariable(Variable))
10927 Visit(block->getBlockDecl()->getBody());
10928 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000010929
10930 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
10931 if (Capturer) return;
10932 if (OVE->getSourceExpr())
10933 Visit(OVE->getSourceExpr());
10934 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010935 void VisitBinaryOperator(BinaryOperator *BinOp) {
10936 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
10937 return;
10938 Expr *LHS = BinOp->getLHS();
10939 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
10940 if (DRE->getDecl() != Variable)
10941 return;
10942 if (Expr *RHS = BinOp->getRHS()) {
10943 RHS = RHS->IgnoreParenCasts();
10944 llvm::APSInt Value;
10945 VarWillBeReased =
10946 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
10947 }
10948 }
10949 }
John McCall31168b02011-06-15 23:02:42 +000010950 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010951} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010952
10953/// Check whether the given argument is a block which captures a
10954/// variable.
10955static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
10956 assert(owner.Variable && owner.Loc.isValid());
10957
10958 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000010959
10960 // Look through [^{...} copy] and Block_copy(^{...}).
10961 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
10962 Selector Cmd = ME->getSelector();
10963 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
10964 e = ME->getInstanceReceiver();
10965 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000010966 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000010967 e = e->IgnoreParenCasts();
10968 }
10969 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
10970 if (CE->getNumArgs() == 1) {
10971 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000010972 if (Fn) {
10973 const IdentifierInfo *FnI = Fn->getIdentifier();
10974 if (FnI && FnI->isStr("_Block_copy")) {
10975 e = CE->getArg(0)->IgnoreParenCasts();
10976 }
10977 }
Jordan Rose67e887c2012-09-17 17:54:30 +000010978 }
10979 }
10980
John McCall31168b02011-06-15 23:02:42 +000010981 BlockExpr *block = dyn_cast<BlockExpr>(e);
10982 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000010983 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000010984
10985 FindCaptureVisitor visitor(S.Context, owner.Variable);
10986 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010987 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000010988}
10989
10990static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10991 RetainCycleOwner &owner) {
10992 assert(capturer);
10993 assert(owner.Variable && owner.Loc.isValid());
10994
10995 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10996 << owner.Variable << capturer->getSourceRange();
10997 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10998 << owner.Indirect << owner.Range;
10999}
11000
11001/// Check for a keyword selector that starts with the word 'add' or
11002/// 'set'.
11003static bool isSetterLikeSelector(Selector sel) {
11004 if (sel.isUnarySelector()) return false;
11005
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011006 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000011007 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011008 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000011009 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011010 else if (str.startswith("add")) {
11011 // Specially whitelist 'addOperationWithBlock:'.
11012 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11013 return false;
11014 str = str.substr(3);
11015 }
John McCall31168b02011-06-15 23:02:42 +000011016 else
11017 return false;
11018
11019 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000011020 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000011021}
11022
Benjamin Kramer3a743452015-03-09 15:03:32 +000011023static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11024 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011025 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11026 Message->getReceiverInterface(),
11027 NSAPI::ClassId_NSMutableArray);
11028 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011029 return None;
11030 }
11031
11032 Selector Sel = Message->getSelector();
11033
11034 Optional<NSAPI::NSArrayMethodKind> MKOpt =
11035 S.NSAPIObj->getNSArrayMethodKind(Sel);
11036 if (!MKOpt) {
11037 return None;
11038 }
11039
11040 NSAPI::NSArrayMethodKind MK = *MKOpt;
11041
11042 switch (MK) {
11043 case NSAPI::NSMutableArr_addObject:
11044 case NSAPI::NSMutableArr_insertObjectAtIndex:
11045 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11046 return 0;
11047 case NSAPI::NSMutableArr_replaceObjectAtIndex:
11048 return 1;
11049
11050 default:
11051 return None;
11052 }
11053
11054 return None;
11055}
11056
11057static
11058Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11059 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011060 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11061 Message->getReceiverInterface(),
11062 NSAPI::ClassId_NSMutableDictionary);
11063 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011064 return None;
11065 }
11066
11067 Selector Sel = Message->getSelector();
11068
11069 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11070 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11071 if (!MKOpt) {
11072 return None;
11073 }
11074
11075 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11076
11077 switch (MK) {
11078 case NSAPI::NSMutableDict_setObjectForKey:
11079 case NSAPI::NSMutableDict_setValueForKey:
11080 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11081 return 0;
11082
11083 default:
11084 return None;
11085 }
11086
11087 return None;
11088}
11089
11090static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011091 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11092 Message->getReceiverInterface(),
11093 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000011094
Alex Denisov5dfac812015-08-06 04:51:14 +000011095 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11096 Message->getReceiverInterface(),
11097 NSAPI::ClassId_NSMutableOrderedSet);
11098 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011099 return None;
11100 }
11101
11102 Selector Sel = Message->getSelector();
11103
11104 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11105 if (!MKOpt) {
11106 return None;
11107 }
11108
11109 NSAPI::NSSetMethodKind MK = *MKOpt;
11110
11111 switch (MK) {
11112 case NSAPI::NSMutableSet_addObject:
11113 case NSAPI::NSOrderedSet_setObjectAtIndex:
11114 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11115 case NSAPI::NSOrderedSet_insertObjectAtIndex:
11116 return 0;
11117 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11118 return 1;
11119 }
11120
11121 return None;
11122}
11123
11124void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11125 if (!Message->isInstanceMessage()) {
11126 return;
11127 }
11128
11129 Optional<int> ArgOpt;
11130
11131 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11132 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11133 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11134 return;
11135 }
11136
11137 int ArgIndex = *ArgOpt;
11138
Alex Denisove1d882c2015-03-04 17:55:52 +000011139 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11140 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11141 Arg = OE->getSourceExpr()->IgnoreImpCasts();
11142 }
11143
Alex Denisov5dfac812015-08-06 04:51:14 +000011144 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011145 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011146 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011147 Diag(Message->getSourceRange().getBegin(),
11148 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000011149 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000011150 }
11151 }
Alex Denisov5dfac812015-08-06 04:51:14 +000011152 } else {
11153 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11154
11155 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11156 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11157 }
11158
11159 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11160 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11161 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11162 ValueDecl *Decl = ReceiverRE->getDecl();
11163 Diag(Message->getSourceRange().getBegin(),
11164 diag::warn_objc_circular_container)
11165 << Decl->getName() << Decl->getName();
11166 if (!ArgRE->isObjCSelfExpr()) {
11167 Diag(Decl->getLocation(),
11168 diag::note_objc_circular_container_declared_here)
11169 << Decl->getName();
11170 }
11171 }
11172 }
11173 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11174 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11175 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11176 ObjCIvarDecl *Decl = IvarRE->getDecl();
11177 Diag(Message->getSourceRange().getBegin(),
11178 diag::warn_objc_circular_container)
11179 << Decl->getName() << Decl->getName();
11180 Diag(Decl->getLocation(),
11181 diag::note_objc_circular_container_declared_here)
11182 << Decl->getName();
11183 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011184 }
11185 }
11186 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011187}
11188
John McCall31168b02011-06-15 23:02:42 +000011189/// Check a message send to see if it's likely to cause a retain cycle.
11190void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11191 // Only check instance methods whose selector looks like a setter.
11192 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11193 return;
11194
11195 // Try to find a variable that the receiver is strongly owned by.
11196 RetainCycleOwner owner;
11197 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011198 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000011199 return;
11200 } else {
11201 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11202 owner.Variable = getCurMethodDecl()->getSelfDecl();
11203 owner.Loc = msg->getSuperLoc();
11204 owner.Range = msg->getSuperLoc();
11205 }
11206
11207 // Check whether the receiver is captured by any of the arguments.
11208 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
11209 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
11210 return diagnoseRetainCycle(*this, capturer, owner);
11211}
11212
11213/// Check a property assign to see if it's likely to cause a retain cycle.
11214void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11215 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011216 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000011217 return;
11218
11219 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11220 diagnoseRetainCycle(*this, capturer, owner);
11221}
11222
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011223void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11224 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000011225 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011226 return;
11227
11228 // Because we don't have an expression for the variable, we have to set the
11229 // location explicitly here.
11230 Owner.Loc = Var->getLocation();
11231 Owner.Range = Var->getSourceRange();
11232
11233 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11234 diagnoseRetainCycle(*this, Capturer, Owner);
11235}
11236
Ted Kremenek9304da92012-12-21 08:04:28 +000011237static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11238 Expr *RHS, bool isProperty) {
11239 // Check if RHS is an Objective-C object literal, which also can get
11240 // immediately zapped in a weak reference. Note that we explicitly
11241 // allow ObjCStringLiterals, since those are designed to never really die.
11242 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011243
Ted Kremenek64873352012-12-21 22:46:35 +000011244 // This enum needs to match with the 'select' in
11245 // warn_objc_arc_literal_assign (off-by-1).
11246 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11247 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11248 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011249
11250 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000011251 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000011252 << (isProperty ? 0 : 1)
11253 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011254
11255 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000011256}
11257
Ted Kremenekc1f014a2012-12-21 19:45:30 +000011258static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11259 Qualifiers::ObjCLifetime LT,
11260 Expr *RHS, bool isProperty) {
11261 // Strip off any implicit cast added to get to the one ARC-specific.
11262 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11263 if (cast->getCastKind() == CK_ARCConsumeObject) {
11264 S.Diag(Loc, diag::warn_arc_retained_assign)
11265 << (LT == Qualifiers::OCL_ExplicitNone)
11266 << (isProperty ? 0 : 1)
11267 << RHS->getSourceRange();
11268 return true;
11269 }
11270 RHS = cast->getSubExpr();
11271 }
11272
11273 if (LT == Qualifiers::OCL_Weak &&
11274 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11275 return true;
11276
11277 return false;
11278}
11279
Ted Kremenekb36234d2012-12-21 08:04:20 +000011280bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11281 QualType LHS, Expr *RHS) {
11282 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11283
11284 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11285 return false;
11286
11287 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11288 return true;
11289
11290 return false;
11291}
11292
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011293void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11294 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011295 QualType LHSType;
11296 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011297 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011298 ObjCPropertyRefExpr *PRE
11299 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11300 if (PRE && !PRE->isImplicitProperty()) {
11301 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11302 if (PD)
11303 LHSType = PD->getType();
11304 }
11305
11306 if (LHSType.isNull())
11307 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000011308
11309 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11310
11311 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011312 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000011313 getCurFunction()->markSafeWeakUse(LHS);
11314 }
11315
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011316 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11317 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000011318
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011319 // FIXME. Check for other life times.
11320 if (LT != Qualifiers::OCL_None)
11321 return;
11322
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011323 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011324 if (PRE->isImplicitProperty())
11325 return;
11326 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11327 if (!PD)
11328 return;
11329
Bill Wendling44426052012-12-20 19:22:21 +000011330 unsigned Attributes = PD->getPropertyAttributes();
11331 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011332 // when 'assign' attribute was not explicitly specified
11333 // by user, ignore it and rely on property type itself
11334 // for lifetime info.
11335 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11336 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11337 LHSType->isObjCRetainableType())
11338 return;
11339
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011340 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000011341 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011342 Diag(Loc, diag::warn_arc_retained_property_assign)
11343 << RHS->getSourceRange();
11344 return;
11345 }
11346 RHS = cast->getSubExpr();
11347 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011348 }
Bill Wendling44426052012-12-20 19:22:21 +000011349 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000011350 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11351 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000011352 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011353 }
11354}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011355
11356//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11357
11358namespace {
11359bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11360 SourceLocation StmtLoc,
11361 const NullStmt *Body) {
11362 // Do not warn if the body is a macro that expands to nothing, e.g:
11363 //
11364 // #define CALL(x)
11365 // if (condition)
11366 // CALL(0);
11367 //
11368 if (Body->hasLeadingEmptyMacro())
11369 return false;
11370
11371 // Get line numbers of statement and body.
11372 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000011373 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011374 &StmtLineInvalid);
11375 if (StmtLineInvalid)
11376 return false;
11377
11378 bool BodyLineInvalid;
11379 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11380 &BodyLineInvalid);
11381 if (BodyLineInvalid)
11382 return false;
11383
11384 // Warn if null statement and body are on the same line.
11385 if (StmtLine != BodyLine)
11386 return false;
11387
11388 return true;
11389}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011390} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011391
11392void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11393 const Stmt *Body,
11394 unsigned DiagID) {
11395 // Since this is a syntactic check, don't emit diagnostic for template
11396 // instantiations, this just adds noise.
11397 if (CurrentInstantiationScope)
11398 return;
11399
11400 // The body should be a null statement.
11401 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11402 if (!NBody)
11403 return;
11404
11405 // Do the usual checks.
11406 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11407 return;
11408
11409 Diag(NBody->getSemiLoc(), DiagID);
11410 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11411}
11412
11413void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11414 const Stmt *PossibleBody) {
11415 assert(!CurrentInstantiationScope); // Ensured by caller
11416
11417 SourceLocation StmtLoc;
11418 const Stmt *Body;
11419 unsigned DiagID;
11420 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11421 StmtLoc = FS->getRParenLoc();
11422 Body = FS->getBody();
11423 DiagID = diag::warn_empty_for_body;
11424 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11425 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11426 Body = WS->getBody();
11427 DiagID = diag::warn_empty_while_body;
11428 } else
11429 return; // Neither `for' nor `while'.
11430
11431 // The body should be a null statement.
11432 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11433 if (!NBody)
11434 return;
11435
11436 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011437 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011438 return;
11439
11440 // Do the usual checks.
11441 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11442 return;
11443
11444 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11445 // noise level low, emit diagnostics only if for/while is followed by a
11446 // CompoundStmt, e.g.:
11447 // for (int i = 0; i < n; i++);
11448 // {
11449 // a(i);
11450 // }
11451 // or if for/while is followed by a statement with more indentation
11452 // than for/while itself:
11453 // for (int i = 0; i < n; i++);
11454 // a(i);
11455 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11456 if (!ProbableTypo) {
11457 bool BodyColInvalid;
11458 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11459 PossibleBody->getLocStart(),
11460 &BodyColInvalid);
11461 if (BodyColInvalid)
11462 return;
11463
11464 bool StmtColInvalid;
11465 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11466 S->getLocStart(),
11467 &StmtColInvalid);
11468 if (StmtColInvalid)
11469 return;
11470
11471 if (BodyCol > StmtCol)
11472 ProbableTypo = true;
11473 }
11474
11475 if (ProbableTypo) {
11476 Diag(NBody->getSemiLoc(), DiagID);
11477 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11478 }
11479}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011480
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011481//===--- CHECK: Warn on self move with std::move. -------------------------===//
11482
11483/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11484void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11485 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011486 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11487 return;
11488
Richard Smith51ec0cf2017-02-21 01:17:38 +000011489 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011490 return;
11491
11492 // Strip parens and casts away.
11493 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11494 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11495
11496 // Check for a call expression
11497 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11498 if (!CE || CE->getNumArgs() != 1)
11499 return;
11500
11501 // Check for a call to std::move
11502 const FunctionDecl *FD = CE->getDirectCallee();
11503 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11504 !FD->getIdentifier()->isStr("move"))
11505 return;
11506
11507 // Get argument from std::move
11508 RHSExpr = CE->getArg(0);
11509
11510 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11511 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11512
11513 // Two DeclRefExpr's, check that the decls are the same.
11514 if (LHSDeclRef && RHSDeclRef) {
11515 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11516 return;
11517 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11518 RHSDeclRef->getDecl()->getCanonicalDecl())
11519 return;
11520
11521 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11522 << LHSExpr->getSourceRange()
11523 << RHSExpr->getSourceRange();
11524 return;
11525 }
11526
11527 // Member variables require a different approach to check for self moves.
11528 // MemberExpr's are the same if every nested MemberExpr refers to the same
11529 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11530 // the base Expr's are CXXThisExpr's.
11531 const Expr *LHSBase = LHSExpr;
11532 const Expr *RHSBase = RHSExpr;
11533 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11534 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11535 if (!LHSME || !RHSME)
11536 return;
11537
11538 while (LHSME && RHSME) {
11539 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11540 RHSME->getMemberDecl()->getCanonicalDecl())
11541 return;
11542
11543 LHSBase = LHSME->getBase();
11544 RHSBase = RHSME->getBase();
11545 LHSME = dyn_cast<MemberExpr>(LHSBase);
11546 RHSME = dyn_cast<MemberExpr>(RHSBase);
11547 }
11548
11549 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11550 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11551 if (LHSDeclRef && RHSDeclRef) {
11552 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11553 return;
11554 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11555 RHSDeclRef->getDecl()->getCanonicalDecl())
11556 return;
11557
11558 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11559 << LHSExpr->getSourceRange()
11560 << RHSExpr->getSourceRange();
11561 return;
11562 }
11563
11564 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11565 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11566 << LHSExpr->getSourceRange()
11567 << RHSExpr->getSourceRange();
11568}
11569
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011570//===--- Layout compatibility ----------------------------------------------//
11571
11572namespace {
11573
11574bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11575
11576/// \brief Check if two enumeration types are layout-compatible.
11577bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11578 // C++11 [dcl.enum] p8:
11579 // Two enumeration types are layout-compatible if they have the same
11580 // underlying type.
11581 return ED1->isComplete() && ED2->isComplete() &&
11582 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11583}
11584
11585/// \brief Check if two fields are layout-compatible.
11586bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11587 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11588 return false;
11589
11590 if (Field1->isBitField() != Field2->isBitField())
11591 return false;
11592
11593 if (Field1->isBitField()) {
11594 // Make sure that the bit-fields are the same length.
11595 unsigned Bits1 = Field1->getBitWidthValue(C);
11596 unsigned Bits2 = Field2->getBitWidthValue(C);
11597
11598 if (Bits1 != Bits2)
11599 return false;
11600 }
11601
11602 return true;
11603}
11604
11605/// \brief Check if two standard-layout structs are layout-compatible.
11606/// (C++11 [class.mem] p17)
11607bool isLayoutCompatibleStruct(ASTContext &C,
11608 RecordDecl *RD1,
11609 RecordDecl *RD2) {
11610 // If both records are C++ classes, check that base classes match.
11611 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11612 // If one of records is a CXXRecordDecl we are in C++ mode,
11613 // thus the other one is a CXXRecordDecl, too.
11614 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11615 // Check number of base classes.
11616 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11617 return false;
11618
11619 // Check the base classes.
11620 for (CXXRecordDecl::base_class_const_iterator
11621 Base1 = D1CXX->bases_begin(),
11622 BaseEnd1 = D1CXX->bases_end(),
11623 Base2 = D2CXX->bases_begin();
11624 Base1 != BaseEnd1;
11625 ++Base1, ++Base2) {
11626 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11627 return false;
11628 }
11629 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11630 // If only RD2 is a C++ class, it should have zero base classes.
11631 if (D2CXX->getNumBases() > 0)
11632 return false;
11633 }
11634
11635 // Check the fields.
11636 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11637 Field2End = RD2->field_end(),
11638 Field1 = RD1->field_begin(),
11639 Field1End = RD1->field_end();
11640 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11641 if (!isLayoutCompatible(C, *Field1, *Field2))
11642 return false;
11643 }
11644 if (Field1 != Field1End || Field2 != Field2End)
11645 return false;
11646
11647 return true;
11648}
11649
11650/// \brief Check if two standard-layout unions are layout-compatible.
11651/// (C++11 [class.mem] p18)
11652bool isLayoutCompatibleUnion(ASTContext &C,
11653 RecordDecl *RD1,
11654 RecordDecl *RD2) {
11655 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011656 for (auto *Field2 : RD2->fields())
11657 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011658
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011659 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011660 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11661 I = UnmatchedFields.begin(),
11662 E = UnmatchedFields.end();
11663
11664 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011665 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011666 bool Result = UnmatchedFields.erase(*I);
11667 (void) Result;
11668 assert(Result);
11669 break;
11670 }
11671 }
11672 if (I == E)
11673 return false;
11674 }
11675
11676 return UnmatchedFields.empty();
11677}
11678
11679bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11680 if (RD1->isUnion() != RD2->isUnion())
11681 return false;
11682
11683 if (RD1->isUnion())
11684 return isLayoutCompatibleUnion(C, RD1, RD2);
11685 else
11686 return isLayoutCompatibleStruct(C, RD1, RD2);
11687}
11688
11689/// \brief Check if two types are layout-compatible in C++11 sense.
11690bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11691 if (T1.isNull() || T2.isNull())
11692 return false;
11693
11694 // C++11 [basic.types] p11:
11695 // If two types T1 and T2 are the same type, then T1 and T2 are
11696 // layout-compatible types.
11697 if (C.hasSameType(T1, T2))
11698 return true;
11699
11700 T1 = T1.getCanonicalType().getUnqualifiedType();
11701 T2 = T2.getCanonicalType().getUnqualifiedType();
11702
11703 const Type::TypeClass TC1 = T1->getTypeClass();
11704 const Type::TypeClass TC2 = T2->getTypeClass();
11705
11706 if (TC1 != TC2)
11707 return false;
11708
11709 if (TC1 == Type::Enum) {
11710 return isLayoutCompatible(C,
11711 cast<EnumType>(T1)->getDecl(),
11712 cast<EnumType>(T2)->getDecl());
11713 } else if (TC1 == Type::Record) {
11714 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11715 return false;
11716
11717 return isLayoutCompatible(C,
11718 cast<RecordType>(T1)->getDecl(),
11719 cast<RecordType>(T2)->getDecl());
11720 }
11721
11722 return false;
11723}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011724} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011725
11726//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11727
11728namespace {
11729/// \brief Given a type tag expression find the type tag itself.
11730///
11731/// \param TypeExpr Type tag expression, as it appears in user's code.
11732///
11733/// \param VD Declaration of an identifier that appears in a type tag.
11734///
11735/// \param MagicValue Type tag magic value.
11736bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11737 const ValueDecl **VD, uint64_t *MagicValue) {
11738 while(true) {
11739 if (!TypeExpr)
11740 return false;
11741
11742 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11743
11744 switch (TypeExpr->getStmtClass()) {
11745 case Stmt::UnaryOperatorClass: {
11746 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11747 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11748 TypeExpr = UO->getSubExpr();
11749 continue;
11750 }
11751 return false;
11752 }
11753
11754 case Stmt::DeclRefExprClass: {
11755 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11756 *VD = DRE->getDecl();
11757 return true;
11758 }
11759
11760 case Stmt::IntegerLiteralClass: {
11761 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11762 llvm::APInt MagicValueAPInt = IL->getValue();
11763 if (MagicValueAPInt.getActiveBits() <= 64) {
11764 *MagicValue = MagicValueAPInt.getZExtValue();
11765 return true;
11766 } else
11767 return false;
11768 }
11769
11770 case Stmt::BinaryConditionalOperatorClass:
11771 case Stmt::ConditionalOperatorClass: {
11772 const AbstractConditionalOperator *ACO =
11773 cast<AbstractConditionalOperator>(TypeExpr);
11774 bool Result;
11775 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11776 if (Result)
11777 TypeExpr = ACO->getTrueExpr();
11778 else
11779 TypeExpr = ACO->getFalseExpr();
11780 continue;
11781 }
11782 return false;
11783 }
11784
11785 case Stmt::BinaryOperatorClass: {
11786 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11787 if (BO->getOpcode() == BO_Comma) {
11788 TypeExpr = BO->getRHS();
11789 continue;
11790 }
11791 return false;
11792 }
11793
11794 default:
11795 return false;
11796 }
11797 }
11798}
11799
11800/// \brief Retrieve the C type corresponding to type tag TypeExpr.
11801///
11802/// \param TypeExpr Expression that specifies a type tag.
11803///
11804/// \param MagicValues Registered magic values.
11805///
11806/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11807/// kind.
11808///
11809/// \param TypeInfo Information about the corresponding C type.
11810///
11811/// \returns true if the corresponding C type was found.
11812bool GetMatchingCType(
11813 const IdentifierInfo *ArgumentKind,
11814 const Expr *TypeExpr, const ASTContext &Ctx,
11815 const llvm::DenseMap<Sema::TypeTagMagicValue,
11816 Sema::TypeTagData> *MagicValues,
11817 bool &FoundWrongKind,
11818 Sema::TypeTagData &TypeInfo) {
11819 FoundWrongKind = false;
11820
11821 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000011822 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011823
11824 uint64_t MagicValue;
11825
11826 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11827 return false;
11828
11829 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000011830 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011831 if (I->getArgumentKind() != ArgumentKind) {
11832 FoundWrongKind = true;
11833 return false;
11834 }
11835 TypeInfo.Type = I->getMatchingCType();
11836 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11837 TypeInfo.MustBeNull = I->getMustBeNull();
11838 return true;
11839 }
11840 return false;
11841 }
11842
11843 if (!MagicValues)
11844 return false;
11845
11846 llvm::DenseMap<Sema::TypeTagMagicValue,
11847 Sema::TypeTagData>::const_iterator I =
11848 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11849 if (I == MagicValues->end())
11850 return false;
11851
11852 TypeInfo = I->second;
11853 return true;
11854}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011855} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011856
11857void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11858 uint64_t MagicValue, QualType Type,
11859 bool LayoutCompatible,
11860 bool MustBeNull) {
11861 if (!TypeTagForDatatypeMagicValues)
11862 TypeTagForDatatypeMagicValues.reset(
11863 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11864
11865 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11866 (*TypeTagForDatatypeMagicValues)[Magic] =
11867 TypeTagData(Type, LayoutCompatible, MustBeNull);
11868}
11869
11870namespace {
11871bool IsSameCharType(QualType T1, QualType T2) {
11872 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11873 if (!BT1)
11874 return false;
11875
11876 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11877 if (!BT2)
11878 return false;
11879
11880 BuiltinType::Kind T1Kind = BT1->getKind();
11881 BuiltinType::Kind T2Kind = BT2->getKind();
11882
11883 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
11884 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
11885 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11886 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11887}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011888} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011889
11890void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11891 const Expr * const *ExprArgs) {
11892 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11893 bool IsPointerAttr = Attr->getIsPointer();
11894
11895 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11896 bool FoundWrongKind;
11897 TypeTagData TypeInfo;
11898 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11899 TypeTagForDatatypeMagicValues.get(),
11900 FoundWrongKind, TypeInfo)) {
11901 if (FoundWrongKind)
11902 Diag(TypeTagExpr->getExprLoc(),
11903 diag::warn_type_tag_for_datatype_wrong_kind)
11904 << TypeTagExpr->getSourceRange();
11905 return;
11906 }
11907
11908 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11909 if (IsPointerAttr) {
11910 // Skip implicit cast of pointer to `void *' (as a function argument).
11911 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000011912 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000011913 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011914 ArgumentExpr = ICE->getSubExpr();
11915 }
11916 QualType ArgumentType = ArgumentExpr->getType();
11917
11918 // Passing a `void*' pointer shouldn't trigger a warning.
11919 if (IsPointerAttr && ArgumentType->isVoidPointerType())
11920 return;
11921
11922 if (TypeInfo.MustBeNull) {
11923 // Type tag with matching void type requires a null pointer.
11924 if (!ArgumentExpr->isNullPointerConstant(Context,
11925 Expr::NPC_ValueDependentIsNotNull)) {
11926 Diag(ArgumentExpr->getExprLoc(),
11927 diag::warn_type_safety_null_pointer_required)
11928 << ArgumentKind->getName()
11929 << ArgumentExpr->getSourceRange()
11930 << TypeTagExpr->getSourceRange();
11931 }
11932 return;
11933 }
11934
11935 QualType RequiredType = TypeInfo.Type;
11936 if (IsPointerAttr)
11937 RequiredType = Context.getPointerType(RequiredType);
11938
11939 bool mismatch = false;
11940 if (!TypeInfo.LayoutCompatible) {
11941 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
11942
11943 // C++11 [basic.fundamental] p1:
11944 // Plain char, signed char, and unsigned char are three distinct types.
11945 //
11946 // But we treat plain `char' as equivalent to `signed char' or `unsigned
11947 // char' depending on the current char signedness mode.
11948 if (mismatch)
11949 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
11950 RequiredType->getPointeeType())) ||
11951 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
11952 mismatch = false;
11953 } else
11954 if (IsPointerAttr)
11955 mismatch = !isLayoutCompatible(Context,
11956 ArgumentType->getPointeeType(),
11957 RequiredType->getPointeeType());
11958 else
11959 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
11960
11961 if (mismatch)
11962 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000011963 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011964 << TypeInfo.LayoutCompatible << RequiredType
11965 << ArgumentExpr->getSourceRange()
11966 << TypeTagExpr->getSourceRange();
11967}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011968
11969void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11970 CharUnits Alignment) {
11971 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
11972}
11973
11974void Sema::DiagnoseMisalignedMembers() {
11975 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000011976 const NamedDecl *ND = m.RD;
11977 if (ND->getName().empty()) {
11978 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
11979 ND = TD;
11980 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011981 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000011982 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011983 }
11984 MisalignedMembers.clear();
11985}
11986
11987void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011988 E = E->IgnoreParens();
11989 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011990 return;
11991 if (isa<UnaryOperator>(E) &&
11992 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
11993 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11994 if (isa<MemberExpr>(Op)) {
11995 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
11996 MisalignedMember(Op));
11997 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011998 (T->isIntegerType() ||
11999 (T->isPointerType() &&
12000 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012001 MisalignedMembers.erase(MA);
12002 }
12003 }
12004}
12005
12006void Sema::RefersToMemberWithReducedAlignment(
12007 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000012008 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12009 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012010 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012011 if (!ME)
12012 return;
12013
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000012014 // No need to check expressions with an __unaligned-qualified type.
12015 if (E->getType().getQualifiers().hasUnaligned())
12016 return;
12017
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012018 // For a chain of MemberExpr like "a.b.c.d" this list
12019 // will keep FieldDecl's like [d, c, b].
12020 SmallVector<FieldDecl *, 4> ReverseMemberChain;
12021 const MemberExpr *TopME = nullptr;
12022 bool AnyIsPacked = false;
12023 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012024 QualType BaseType = ME->getBase()->getType();
12025 if (ME->isArrow())
12026 BaseType = BaseType->getPointeeType();
12027 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
12028
12029 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012030 auto *FD = dyn_cast<FieldDecl>(MD);
12031 // We do not care about non-data members.
12032 if (!FD || FD->isInvalidDecl())
12033 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012034
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012035 AnyIsPacked =
12036 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12037 ReverseMemberChain.push_back(FD);
12038
12039 TopME = ME;
12040 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12041 } while (ME);
12042 assert(TopME && "We did not compute a topmost MemberExpr!");
12043
12044 // Not the scope of this diagnostic.
12045 if (!AnyIsPacked)
12046 return;
12047
12048 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12049 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12050 // TODO: The innermost base of the member expression may be too complicated.
12051 // For now, just disregard these cases. This is left for future
12052 // improvement.
12053 if (!DRE && !isa<CXXThisExpr>(TopBase))
12054 return;
12055
12056 // Alignment expected by the whole expression.
12057 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12058
12059 // No need to do anything else with this case.
12060 if (ExpectedAlignment.isOne())
12061 return;
12062
12063 // Synthesize offset of the whole access.
12064 CharUnits Offset;
12065 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12066 I++) {
12067 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12068 }
12069
12070 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12071 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12072 ReverseMemberChain.back()->getParent()->getTypeForDecl());
12073
12074 // The base expression of the innermost MemberExpr may give
12075 // stronger guarantees than the class containing the member.
12076 if (DRE && !TopME->isArrow()) {
12077 const ValueDecl *VD = DRE->getDecl();
12078 if (!VD->getType()->isReferenceType())
12079 CompleteObjectAlignment =
12080 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12081 }
12082
12083 // Check if the synthesized offset fulfills the alignment.
12084 if (Offset % ExpectedAlignment != 0 ||
12085 // It may fulfill the offset it but the effective alignment may still be
12086 // lower than the expected expression alignment.
12087 CompleteObjectAlignment < ExpectedAlignment) {
12088 // If this happens, we want to determine a sensible culprit of this.
12089 // Intuitively, watching the chain of member expressions from right to
12090 // left, we start with the required alignment (as required by the field
12091 // type) but some packed attribute in that chain has reduced the alignment.
12092 // It may happen that another packed structure increases it again. But if
12093 // we are here such increase has not been enough. So pointing the first
12094 // FieldDecl that either is packed or else its RecordDecl is,
12095 // seems reasonable.
12096 FieldDecl *FD = nullptr;
12097 CharUnits Alignment;
12098 for (FieldDecl *FDI : ReverseMemberChain) {
12099 if (FDI->hasAttr<PackedAttr>() ||
12100 FDI->getParent()->hasAttr<PackedAttr>()) {
12101 FD = FDI;
12102 Alignment = std::min(
12103 Context.getTypeAlignInChars(FD->getType()),
12104 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12105 break;
12106 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012107 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012108 assert(FD && "We did not find a packed FieldDecl!");
12109 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012110 }
12111}
12112
12113void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12114 using namespace std::placeholders;
12115 RefersToMemberWithReducedAlignment(
12116 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12117 _2, _3, _4));
12118}
12119