blob: 9e16554c2f9c8733062774cd6bfd256c705a30dd [file] [log] [blame]
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattnerb87b1b32007-08-10 20:18:51 +000015#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000017#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000020#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000021#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000022#include "clang/AST/ExprObjC.h"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000023#include "clang/AST/ExprOpenMP.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000030#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000035#include "clang/Sema/SemaInternal.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000036#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000037#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "llvm/ADT/SmallString.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000039#include "llvm/Support/ConvertUTF.h"
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +000040#include "llvm/Support/Format.h"
41#include "llvm/Support/Locale.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000042#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000043
Chris Lattnerb87b1b32007-08-10 20:18:51 +000044using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000045using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000046
Chris Lattnera26fb342009-02-18 17:49:48 +000047SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
48 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000049 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
50 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000051}
52
John McCallbebede42011-02-26 05:39:39 +000053/// Checks that a call expression's argument count is the desired number.
54/// This is useful when doing custom type-checking. Returns true on error.
55static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
56 unsigned argCount = call->getNumArgs();
57 if (argCount == desiredArgCount) return false;
58
59 if (argCount < desiredArgCount)
60 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
61 << 0 /*function call*/ << desiredArgCount << argCount
62 << call->getSourceRange();
63
64 // Highlight all the excess arguments.
65 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
66 call->getArg(argCount - 1)->getLocEnd());
67
68 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
69 << 0 /*function call*/ << desiredArgCount << argCount
70 << call->getArg(1)->getSourceRange();
71}
72
Julien Lerouge4a5b4442012-04-28 17:39:16 +000073/// Check that the first argument to __builtin_annotation is an integer
74/// and the second argument is a non-wide string literal.
75static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
76 if (checkArgCount(S, TheCall, 2))
77 return true;
78
79 // First argument should be an integer.
80 Expr *ValArg = TheCall->getArg(0);
81 QualType Ty = ValArg->getType();
82 if (!Ty->isIntegerType()) {
83 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
84 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000085 return true;
86 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000087
88 // Second argument should be a constant string.
89 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
90 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
91 if (!Literal || !Literal->isAscii()) {
92 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
93 << StrArg->getSourceRange();
94 return true;
95 }
96
97 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000098 return false;
99}
100
Richard Smith6cbd65d2013-07-11 02:27:57 +0000101/// Check that the argument to __builtin_addressof is a glvalue, and set the
102/// result type to the corresponding pointer type.
103static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
104 if (checkArgCount(S, TheCall, 1))
105 return true;
106
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000107 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000108 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
109 if (ResultType.isNull())
110 return true;
111
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000112 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000113 TheCall->setType(ResultType);
114 return false;
115}
116
John McCall03107a42015-10-29 20:48:01 +0000117static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
118 if (checkArgCount(S, TheCall, 3))
119 return true;
120
121 // First two arguments should be integers.
122 for (unsigned I = 0; I < 2; ++I) {
123 Expr *Arg = TheCall->getArg(I);
124 QualType Ty = Arg->getType();
125 if (!Ty->isIntegerType()) {
126 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
127 << Ty << Arg->getSourceRange();
128 return true;
129 }
130 }
131
132 // Third argument should be a pointer to a non-const integer.
133 // IRGen correctly handles volatile, restrict, and address spaces, and
134 // the other qualifiers aren't possible.
135 {
136 Expr *Arg = TheCall->getArg(2);
137 QualType Ty = Arg->getType();
138 const auto *PtrTy = Ty->getAs<PointerType>();
139 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
140 !PtrTy->getPointeeType().isConstQualified())) {
141 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
142 << Ty << Arg->getSourceRange();
143 return true;
144 }
145 }
146
147 return false;
148}
149
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000150static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
151 CallExpr *TheCall, unsigned SizeIdx,
152 unsigned DstSizeIdx) {
153 if (TheCall->getNumArgs() <= SizeIdx ||
154 TheCall->getNumArgs() <= DstSizeIdx)
155 return;
156
157 const Expr *SizeArg = TheCall->getArg(SizeIdx);
158 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
159
160 llvm::APSInt Size, DstSize;
161
162 // find out if both sizes are known at compile time
163 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
164 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
165 return;
166
167 if (Size.ule(DstSize))
168 return;
169
170 // confirmed overflow so generate the diagnostic.
171 IdentifierInfo *FnName = FDecl->getIdentifier();
172 SourceLocation SL = TheCall->getLocStart();
173 SourceRange SR = TheCall->getSourceRange();
174
175 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
176}
177
Peter Collingbournef7706832014-12-12 23:41:25 +0000178static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
179 if (checkArgCount(S, BuiltinCall, 2))
180 return true;
181
182 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
183 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
184 Expr *Call = BuiltinCall->getArg(0);
185 Expr *Chain = BuiltinCall->getArg(1);
186
187 if (Call->getStmtClass() != Stmt::CallExprClass) {
188 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
189 << Call->getSourceRange();
190 return true;
191 }
192
193 auto CE = cast<CallExpr>(Call);
194 if (CE->getCallee()->getType()->isBlockPointerType()) {
195 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
196 << Call->getSourceRange();
197 return true;
198 }
199
200 const Decl *TargetDecl = CE->getCalleeDecl();
201 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
202 if (FD->getBuiltinID()) {
203 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
204 << Call->getSourceRange();
205 return true;
206 }
207
208 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
209 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
210 << Call->getSourceRange();
211 return true;
212 }
213
214 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
215 if (ChainResult.isInvalid())
216 return true;
217 if (!ChainResult.get()->getType()->isPointerType()) {
218 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
219 << Chain->getSourceRange();
220 return true;
221 }
222
David Majnemerced8bdf2015-02-25 17:36:15 +0000223 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000224 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
225 QualType BuiltinTy = S.Context.getFunctionType(
226 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
227 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
228
229 Builtin =
230 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
231
232 BuiltinCall->setType(CE->getType());
233 BuiltinCall->setValueKind(CE->getValueKind());
234 BuiltinCall->setObjectKind(CE->getObjectKind());
235 BuiltinCall->setCallee(Builtin);
236 BuiltinCall->setArg(1, ChainResult.get());
237
238 return false;
239}
240
Reid Kleckner1d59f992015-01-22 01:36:17 +0000241static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
242 Scope::ScopeFlags NeededScopeFlags,
243 unsigned DiagID) {
244 // Scopes aren't available during instantiation. Fortunately, builtin
245 // functions cannot be template args so they cannot be formed through template
246 // instantiation. Therefore checking once during the parse is sufficient.
247 if (!SemaRef.ActiveTemplateInstantiations.empty())
248 return false;
249
250 Scope *S = SemaRef.getCurScope();
251 while (S && !S->isSEHExceptScope())
252 S = S->getParent();
253 if (!S || !(S->getFlags() & NeededScopeFlags)) {
254 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
255 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
256 << DRE->getDecl()->getIdentifier();
257 return true;
258 }
259
260 return false;
261}
262
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000263static inline bool isBlockPointer(Expr *Arg) {
264 return Arg->getType()->isBlockPointerType();
265}
266
267/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
268/// void*, which is a requirement of device side enqueue.
269static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
270 const BlockPointerType *BPT =
271 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
272 ArrayRef<QualType> Params =
273 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
274 unsigned ArgCounter = 0;
275 bool IllegalParams = false;
276 // Iterate through the block parameters until either one is found that is not
277 // a local void*, or the block is valid.
278 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
279 I != E; ++I, ++ArgCounter) {
280 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
281 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
282 LangAS::opencl_local) {
283 // Get the location of the error. If a block literal has been passed
284 // (BlockExpr) then we can point straight to the offending argument,
285 // else we just point to the variable reference.
286 SourceLocation ErrorLoc;
287 if (isa<BlockExpr>(BlockArg)) {
288 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
289 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
290 } else if (isa<DeclRefExpr>(BlockArg)) {
291 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
292 }
293 S.Diag(ErrorLoc,
294 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
295 IllegalParams = true;
296 }
297 }
298
299 return IllegalParams;
300}
301
302/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
303/// get_kernel_work_group_size
304/// and get_kernel_preferred_work_group_size_multiple builtin functions.
305static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
306 if (checkArgCount(S, TheCall, 1))
307 return true;
308
309 Expr *BlockArg = TheCall->getArg(0);
310 if (!isBlockPointer(BlockArg)) {
311 S.Diag(BlockArg->getLocStart(),
312 diag::err_opencl_enqueue_kernel_expected_type) << "block";
313 return true;
314 }
315 return checkOpenCLBlockArgs(S, BlockArg);
316}
317
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000318/// Diagnose integer type and any valid implicit convertion to it.
319static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
320 const QualType &IntType);
321
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000322static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000323 unsigned Start, unsigned End) {
324 bool IllegalParams = false;
325 for (unsigned I = Start; I <= End; ++I)
326 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
327 S.Context.getSizeType());
328 return IllegalParams;
329}
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000330
331/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
332/// 'local void*' parameter of passed block.
333static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
334 Expr *BlockArg,
335 unsigned NumNonVarArgs) {
336 const BlockPointerType *BPT =
337 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
338 unsigned NumBlockParams =
339 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
340 unsigned TotalNumArgs = TheCall->getNumArgs();
341
342 // For each argument passed to the block, a corresponding uint needs to
343 // be passed to describe the size of the local memory.
344 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
345 S.Diag(TheCall->getLocStart(),
346 diag::err_opencl_enqueue_kernel_local_size_args);
347 return true;
348 }
349
350 // Check that the sizes of the local memory are specified by integers.
351 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
352 TotalNumArgs - 1);
353}
354
355/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
356/// overload formats specified in Table 6.13.17.1.
357/// int enqueue_kernel(queue_t queue,
358/// kernel_enqueue_flags_t flags,
359/// const ndrange_t ndrange,
360/// void (^block)(void))
361/// int enqueue_kernel(queue_t queue,
362/// kernel_enqueue_flags_t flags,
363/// const ndrange_t ndrange,
364/// uint num_events_in_wait_list,
365/// clk_event_t *event_wait_list,
366/// clk_event_t *event_ret,
367/// void (^block)(void))
368/// int enqueue_kernel(queue_t queue,
369/// kernel_enqueue_flags_t flags,
370/// const ndrange_t ndrange,
371/// void (^block)(local void*, ...),
372/// uint size0, ...)
373/// int enqueue_kernel(queue_t queue,
374/// kernel_enqueue_flags_t flags,
375/// const ndrange_t ndrange,
376/// uint num_events_in_wait_list,
377/// clk_event_t *event_wait_list,
378/// clk_event_t *event_ret,
379/// void (^block)(local void*, ...),
380/// uint size0, ...)
381static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
382 unsigned NumArgs = TheCall->getNumArgs();
383
384 if (NumArgs < 4) {
385 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
386 return true;
387 }
388
389 Expr *Arg0 = TheCall->getArg(0);
390 Expr *Arg1 = TheCall->getArg(1);
391 Expr *Arg2 = TheCall->getArg(2);
392 Expr *Arg3 = TheCall->getArg(3);
393
394 // First argument always needs to be a queue_t type.
395 if (!Arg0->getType()->isQueueT()) {
396 S.Diag(TheCall->getArg(0)->getLocStart(),
397 diag::err_opencl_enqueue_kernel_expected_type)
398 << S.Context.OCLQueueTy;
399 return true;
400 }
401
402 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
403 if (!Arg1->getType()->isIntegerType()) {
404 S.Diag(TheCall->getArg(1)->getLocStart(),
405 diag::err_opencl_enqueue_kernel_expected_type)
406 << "'kernel_enqueue_flags_t' (i.e. uint)";
407 return true;
408 }
409
410 // Third argument is always an ndrange_t type.
411 if (!Arg2->getType()->isNDRangeT()) {
412 S.Diag(TheCall->getArg(2)->getLocStart(),
413 diag::err_opencl_enqueue_kernel_expected_type)
414 << S.Context.OCLNDRangeTy;
415 return true;
416 }
417
418 // With four arguments, there is only one form that the function could be
419 // called in: no events and no variable arguments.
420 if (NumArgs == 4) {
421 // check that the last argument is the right block type.
422 if (!isBlockPointer(Arg3)) {
423 S.Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
424 << "block";
425 return true;
426 }
427 // we have a block type, check the prototype
428 const BlockPointerType *BPT =
429 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
430 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
431 S.Diag(Arg3->getLocStart(),
432 diag::err_opencl_enqueue_kernel_blocks_no_args);
433 return true;
434 }
435 return false;
436 }
437 // we can have block + varargs.
438 if (isBlockPointer(Arg3))
439 return (checkOpenCLBlockArgs(S, Arg3) ||
440 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
441 // last two cases with either exactly 7 args or 7 args and varargs.
442 if (NumArgs >= 7) {
443 // check common block argument.
444 Expr *Arg6 = TheCall->getArg(6);
445 if (!isBlockPointer(Arg6)) {
446 S.Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
447 << "block";
448 return true;
449 }
450 if (checkOpenCLBlockArgs(S, Arg6))
451 return true;
452
453 // Forth argument has to be any integer type.
454 if (!Arg3->getType()->isIntegerType()) {
455 S.Diag(TheCall->getArg(3)->getLocStart(),
456 diag::err_opencl_enqueue_kernel_expected_type)
457 << "integer";
458 return true;
459 }
460 // check remaining common arguments.
461 Expr *Arg4 = TheCall->getArg(4);
462 Expr *Arg5 = TheCall->getArg(5);
463
Anastasia Stulova2b461202016-11-14 15:34:01 +0000464 // Fifth argument is always passed as a pointer to clk_event_t.
465 if (!Arg4->isNullPointerConstant(S.Context,
466 Expr::NPC_ValueDependentIsNotNull) &&
467 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000468 S.Diag(TheCall->getArg(4)->getLocStart(),
469 diag::err_opencl_enqueue_kernel_expected_type)
470 << S.Context.getPointerType(S.Context.OCLClkEventTy);
471 return true;
472 }
473
Anastasia Stulova2b461202016-11-14 15:34:01 +0000474 // Sixth argument is always passed as a pointer to clk_event_t.
475 if (!Arg5->isNullPointerConstant(S.Context,
476 Expr::NPC_ValueDependentIsNotNull) &&
477 !(Arg5->getType()->isPointerType() &&
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000478 Arg5->getType()->getPointeeType()->isClkEventT())) {
479 S.Diag(TheCall->getArg(5)->getLocStart(),
480 diag::err_opencl_enqueue_kernel_expected_type)
481 << S.Context.getPointerType(S.Context.OCLClkEventTy);
482 return true;
483 }
484
485 if (NumArgs == 7)
486 return false;
487
488 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
489 }
490
491 // None of the specific case has been detected, give generic error
492 S.Diag(TheCall->getLocStart(),
493 diag::err_opencl_enqueue_kernel_incorrect_args);
494 return true;
495}
496
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000497/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000498static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000499 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000500}
501
502/// Returns true if pipe element type is different from the pointer.
503static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
504 const Expr *Arg0 = Call->getArg(0);
505 // First argument type should always be pipe.
506 if (!Arg0->getType()->isPipeType()) {
507 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000508 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000509 return true;
510 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000511 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000512 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
513 // Validates the access qualifier is compatible with the call.
514 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
515 // read_only and write_only, and assumed to be read_only if no qualifier is
516 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000517 switch (Call->getDirectCallee()->getBuiltinID()) {
518 case Builtin::BIread_pipe:
519 case Builtin::BIreserve_read_pipe:
520 case Builtin::BIcommit_read_pipe:
521 case Builtin::BIwork_group_reserve_read_pipe:
522 case Builtin::BIsub_group_reserve_read_pipe:
523 case Builtin::BIwork_group_commit_read_pipe:
524 case Builtin::BIsub_group_commit_read_pipe:
525 if (!(!AccessQual || AccessQual->isReadOnly())) {
526 S.Diag(Arg0->getLocStart(),
527 diag::err_opencl_builtin_pipe_invalid_access_modifier)
528 << "read_only" << Arg0->getSourceRange();
529 return true;
530 }
531 break;
532 case Builtin::BIwrite_pipe:
533 case Builtin::BIreserve_write_pipe:
534 case Builtin::BIcommit_write_pipe:
535 case Builtin::BIwork_group_reserve_write_pipe:
536 case Builtin::BIsub_group_reserve_write_pipe:
537 case Builtin::BIwork_group_commit_write_pipe:
538 case Builtin::BIsub_group_commit_write_pipe:
539 if (!(AccessQual && AccessQual->isWriteOnly())) {
540 S.Diag(Arg0->getLocStart(),
541 diag::err_opencl_builtin_pipe_invalid_access_modifier)
542 << "write_only" << Arg0->getSourceRange();
543 return true;
544 }
545 break;
546 default:
547 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000548 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000549 return false;
550}
551
552/// Returns true if pipe element type is different from the pointer.
553static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
554 const Expr *Arg0 = Call->getArg(0);
555 const Expr *ArgIdx = Call->getArg(Idx);
556 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000557 const QualType EltTy = PipeTy->getElementType();
558 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000559 // The Idx argument should be a pointer and the type of the pointer and
560 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000561 if (!ArgTy ||
562 !S.Context.hasSameType(
563 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000564 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000565 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000566 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000567 return true;
568 }
569 return false;
570}
571
572// \brief Performs semantic analysis for the read/write_pipe call.
573// \param S Reference to the semantic analyzer.
574// \param Call A pointer to the builtin call.
575// \return True if a semantic error has been found, false otherwise.
576static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000577 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
578 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000579 switch (Call->getNumArgs()) {
580 case 2: {
581 if (checkOpenCLPipeArg(S, Call))
582 return true;
583 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000584 // read/write_pipe(pipe T, T*).
585 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000586 if (checkOpenCLPipePacketType(S, Call, 1))
587 return true;
588 } break;
589
590 case 4: {
591 if (checkOpenCLPipeArg(S, Call))
592 return true;
593 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000594 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
595 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000596 if (!Call->getArg(1)->getType()->isReserveIDT()) {
597 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000598 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000599 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000600 return true;
601 }
602
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000603 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000604 const Expr *Arg2 = Call->getArg(2);
605 if (!Arg2->getType()->isIntegerType() &&
606 !Arg2->getType()->isUnsignedIntegerType()) {
607 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000608 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000609 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000610 return true;
611 }
612
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000613 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000614 if (checkOpenCLPipePacketType(S, Call, 3))
615 return true;
616 } break;
617 default:
618 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000619 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000620 return true;
621 }
622
623 return false;
624}
625
626// \brief Performs a semantic analysis on the {work_group_/sub_group_
627// /_}reserve_{read/write}_pipe
628// \param S Reference to the semantic analyzer.
629// \param Call The call to the builtin function to be analyzed.
630// \return True if a semantic error was found, false otherwise.
631static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
632 if (checkArgCount(S, Call, 2))
633 return true;
634
635 if (checkOpenCLPipeArg(S, Call))
636 return true;
637
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000638 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000639 if (!Call->getArg(1)->getType()->isIntegerType() &&
640 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
641 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000642 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000643 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000644 return true;
645 }
646
647 return false;
648}
649
650// \brief Performs a semantic analysis on {work_group_/sub_group_
651// /_}commit_{read/write}_pipe
652// \param S Reference to the semantic analyzer.
653// \param Call The call to the builtin function to be analyzed.
654// \return True if a semantic error was found, false otherwise.
655static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
656 if (checkArgCount(S, Call, 2))
657 return true;
658
659 if (checkOpenCLPipeArg(S, Call))
660 return true;
661
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000662 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000663 if (!Call->getArg(1)->getType()->isReserveIDT()) {
664 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000665 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000666 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000667 return true;
668 }
669
670 return false;
671}
672
673// \brief Performs a semantic analysis on the call to built-in Pipe
674// Query Functions.
675// \param S Reference to the semantic analyzer.
676// \param Call The call to the builtin function to be analyzed.
677// \return True if a semantic error was found, false otherwise.
678static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
679 if (checkArgCount(S, Call, 1))
680 return true;
681
682 if (!Call->getArg(0)->getType()->isPipeType()) {
683 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000684 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000685 return true;
686 }
687
688 return false;
689}
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +0000690// \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
Yaxun Liuf7449a12016-05-20 19:54:38 +0000691// \brief Performs semantic analysis for the to_global/local/private call.
692// \param S Reference to the semantic analyzer.
693// \param BuiltinID ID of the builtin function.
694// \param Call A pointer to the builtin call.
695// \return True if a semantic error has been found, false otherwise.
696static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
697 CallExpr *Call) {
Yaxun Liuf7449a12016-05-20 19:54:38 +0000698 if (Call->getNumArgs() != 1) {
699 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
700 << Call->getDirectCallee() << Call->getSourceRange();
701 return true;
702 }
703
704 auto RT = Call->getArg(0)->getType();
705 if (!RT->isPointerType() || RT->getPointeeType()
706 .getAddressSpace() == LangAS::opencl_constant) {
707 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
708 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
709 return true;
710 }
711
712 RT = RT->getPointeeType();
713 auto Qual = RT.getQualifiers();
714 switch (BuiltinID) {
715 case Builtin::BIto_global:
716 Qual.setAddressSpace(LangAS::opencl_global);
717 break;
718 case Builtin::BIto_local:
719 Qual.setAddressSpace(LangAS::opencl_local);
720 break;
721 default:
722 Qual.removeAddressSpace();
723 }
724 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
725 RT.getUnqualifiedType(), Qual)));
726
727 return false;
728}
729
John McCalldadc5752010-08-24 06:29:42 +0000730ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000731Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
732 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000733 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000734
Chris Lattner3be167f2010-10-01 23:23:24 +0000735 // Find out if any arguments are required to be integer constant expressions.
736 unsigned ICEArguments = 0;
737 ASTContext::GetBuiltinTypeError Error;
738 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
739 if (Error != ASTContext::GE_None)
740 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
741
742 // If any arguments are required to be ICE's, check and diagnose.
743 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
744 // Skip arguments not required to be ICE's.
745 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
746
747 llvm::APSInt Result;
748 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
749 return true;
750 ICEArguments &= ~(1 << ArgNo);
751 }
752
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000753 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000754 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000755 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000756 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000757 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000758 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000759 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000760 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000761 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000762 if (SemaBuiltinVAStart(TheCall))
763 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000764 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000765 case Builtin::BI__va_start: {
766 switch (Context.getTargetInfo().getTriple().getArch()) {
767 case llvm::Triple::arm:
768 case llvm::Triple::thumb:
769 if (SemaBuiltinVAStartARM(TheCall))
770 return ExprError();
771 break;
772 default:
773 if (SemaBuiltinVAStart(TheCall))
774 return ExprError();
775 break;
776 }
777 break;
778 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000779 case Builtin::BI__builtin_isgreater:
780 case Builtin::BI__builtin_isgreaterequal:
781 case Builtin::BI__builtin_isless:
782 case Builtin::BI__builtin_islessequal:
783 case Builtin::BI__builtin_islessgreater:
784 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000785 if (SemaBuiltinUnorderedCompare(TheCall))
786 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000787 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000788 case Builtin::BI__builtin_fpclassify:
789 if (SemaBuiltinFPClassification(TheCall, 6))
790 return ExprError();
791 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000792 case Builtin::BI__builtin_isfinite:
793 case Builtin::BI__builtin_isinf:
794 case Builtin::BI__builtin_isinf_sign:
795 case Builtin::BI__builtin_isnan:
796 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000797 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000798 return ExprError();
799 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000800 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000801 return SemaBuiltinShuffleVector(TheCall);
802 // TheCall will be freed by the smart pointer here, but that's fine, since
803 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000804 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000805 if (SemaBuiltinPrefetch(TheCall))
806 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000807 break;
David Majnemer51169932016-10-31 05:37:48 +0000808 case Builtin::BI__builtin_alloca_with_align:
809 if (SemaBuiltinAllocaWithAlign(TheCall))
810 return ExprError();
811 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000812 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000813 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000814 if (SemaBuiltinAssume(TheCall))
815 return ExprError();
816 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000817 case Builtin::BI__builtin_assume_aligned:
818 if (SemaBuiltinAssumeAligned(TheCall))
819 return ExprError();
820 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000821 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000822 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000823 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000824 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000825 case Builtin::BI__builtin_longjmp:
826 if (SemaBuiltinLongjmp(TheCall))
827 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000828 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000829 case Builtin::BI__builtin_setjmp:
830 if (SemaBuiltinSetjmp(TheCall))
831 return ExprError();
832 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000833 case Builtin::BI_setjmp:
834 case Builtin::BI_setjmpex:
835 if (checkArgCount(*this, TheCall, 1))
836 return true;
837 break;
John McCallbebede42011-02-26 05:39:39 +0000838
839 case Builtin::BI__builtin_classify_type:
840 if (checkArgCount(*this, TheCall, 1)) return true;
841 TheCall->setType(Context.IntTy);
842 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000843 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000844 if (checkArgCount(*this, TheCall, 1)) return true;
845 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000846 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000847 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000848 case Builtin::BI__sync_fetch_and_add_1:
849 case Builtin::BI__sync_fetch_and_add_2:
850 case Builtin::BI__sync_fetch_and_add_4:
851 case Builtin::BI__sync_fetch_and_add_8:
852 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000853 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000854 case Builtin::BI__sync_fetch_and_sub_1:
855 case Builtin::BI__sync_fetch_and_sub_2:
856 case Builtin::BI__sync_fetch_and_sub_4:
857 case Builtin::BI__sync_fetch_and_sub_8:
858 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000859 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000860 case Builtin::BI__sync_fetch_and_or_1:
861 case Builtin::BI__sync_fetch_and_or_2:
862 case Builtin::BI__sync_fetch_and_or_4:
863 case Builtin::BI__sync_fetch_and_or_8:
864 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000865 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000866 case Builtin::BI__sync_fetch_and_and_1:
867 case Builtin::BI__sync_fetch_and_and_2:
868 case Builtin::BI__sync_fetch_and_and_4:
869 case Builtin::BI__sync_fetch_and_and_8:
870 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000871 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000872 case Builtin::BI__sync_fetch_and_xor_1:
873 case Builtin::BI__sync_fetch_and_xor_2:
874 case Builtin::BI__sync_fetch_and_xor_4:
875 case Builtin::BI__sync_fetch_and_xor_8:
876 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000877 case Builtin::BI__sync_fetch_and_nand:
878 case Builtin::BI__sync_fetch_and_nand_1:
879 case Builtin::BI__sync_fetch_and_nand_2:
880 case Builtin::BI__sync_fetch_and_nand_4:
881 case Builtin::BI__sync_fetch_and_nand_8:
882 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000883 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000884 case Builtin::BI__sync_add_and_fetch_1:
885 case Builtin::BI__sync_add_and_fetch_2:
886 case Builtin::BI__sync_add_and_fetch_4:
887 case Builtin::BI__sync_add_and_fetch_8:
888 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000889 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000890 case Builtin::BI__sync_sub_and_fetch_1:
891 case Builtin::BI__sync_sub_and_fetch_2:
892 case Builtin::BI__sync_sub_and_fetch_4:
893 case Builtin::BI__sync_sub_and_fetch_8:
894 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000895 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000896 case Builtin::BI__sync_and_and_fetch_1:
897 case Builtin::BI__sync_and_and_fetch_2:
898 case Builtin::BI__sync_and_and_fetch_4:
899 case Builtin::BI__sync_and_and_fetch_8:
900 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000901 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000902 case Builtin::BI__sync_or_and_fetch_1:
903 case Builtin::BI__sync_or_and_fetch_2:
904 case Builtin::BI__sync_or_and_fetch_4:
905 case Builtin::BI__sync_or_and_fetch_8:
906 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000907 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000908 case Builtin::BI__sync_xor_and_fetch_1:
909 case Builtin::BI__sync_xor_and_fetch_2:
910 case Builtin::BI__sync_xor_and_fetch_4:
911 case Builtin::BI__sync_xor_and_fetch_8:
912 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000913 case Builtin::BI__sync_nand_and_fetch:
914 case Builtin::BI__sync_nand_and_fetch_1:
915 case Builtin::BI__sync_nand_and_fetch_2:
916 case Builtin::BI__sync_nand_and_fetch_4:
917 case Builtin::BI__sync_nand_and_fetch_8:
918 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000919 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000920 case Builtin::BI__sync_val_compare_and_swap_1:
921 case Builtin::BI__sync_val_compare_and_swap_2:
922 case Builtin::BI__sync_val_compare_and_swap_4:
923 case Builtin::BI__sync_val_compare_and_swap_8:
924 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000925 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000926 case Builtin::BI__sync_bool_compare_and_swap_1:
927 case Builtin::BI__sync_bool_compare_and_swap_2:
928 case Builtin::BI__sync_bool_compare_and_swap_4:
929 case Builtin::BI__sync_bool_compare_and_swap_8:
930 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000931 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000932 case Builtin::BI__sync_lock_test_and_set_1:
933 case Builtin::BI__sync_lock_test_and_set_2:
934 case Builtin::BI__sync_lock_test_and_set_4:
935 case Builtin::BI__sync_lock_test_and_set_8:
936 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000937 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000938 case Builtin::BI__sync_lock_release_1:
939 case Builtin::BI__sync_lock_release_2:
940 case Builtin::BI__sync_lock_release_4:
941 case Builtin::BI__sync_lock_release_8:
942 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000943 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000944 case Builtin::BI__sync_swap_1:
945 case Builtin::BI__sync_swap_2:
946 case Builtin::BI__sync_swap_4:
947 case Builtin::BI__sync_swap_8:
948 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000949 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000950 case Builtin::BI__builtin_nontemporal_load:
951 case Builtin::BI__builtin_nontemporal_store:
952 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000953#define BUILTIN(ID, TYPE, ATTRS)
954#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
955 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000956 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000957#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000958 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000959 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000960 return ExprError();
961 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000962 case Builtin::BI__builtin_addressof:
963 if (SemaBuiltinAddressof(*this, TheCall))
964 return ExprError();
965 break;
John McCall03107a42015-10-29 20:48:01 +0000966 case Builtin::BI__builtin_add_overflow:
967 case Builtin::BI__builtin_sub_overflow:
968 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +0000969 if (SemaBuiltinOverflow(*this, TheCall))
970 return ExprError();
971 break;
Richard Smith760520b2014-06-03 23:27:44 +0000972 case Builtin::BI__builtin_operator_new:
973 case Builtin::BI__builtin_operator_delete:
974 if (!getLangOpts().CPlusPlus) {
975 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
976 << (BuiltinID == Builtin::BI__builtin_operator_new
977 ? "__builtin_operator_new"
978 : "__builtin_operator_delete")
979 << "C++";
980 return ExprError();
981 }
982 // CodeGen assumes it can find the global new and delete to call,
983 // so ensure that they are declared.
984 DeclareGlobalNewDelete();
985 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000986
987 // check secure string manipulation functions where overflows
988 // are detectable at compile time
989 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000990 case Builtin::BI__builtin___memmove_chk:
991 case Builtin::BI__builtin___memset_chk:
992 case Builtin::BI__builtin___strlcat_chk:
993 case Builtin::BI__builtin___strlcpy_chk:
994 case Builtin::BI__builtin___strncat_chk:
995 case Builtin::BI__builtin___strncpy_chk:
996 case Builtin::BI__builtin___stpncpy_chk:
997 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
998 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000999 case Builtin::BI__builtin___memccpy_chk:
1000 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1001 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001002 case Builtin::BI__builtin___snprintf_chk:
1003 case Builtin::BI__builtin___vsnprintf_chk:
1004 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1005 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001006 case Builtin::BI__builtin_call_with_static_chain:
1007 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1008 return ExprError();
1009 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001010 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001011 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001012 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1013 diag::err_seh___except_block))
1014 return ExprError();
1015 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001016 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001017 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001018 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1019 diag::err_seh___except_filter))
1020 return ExprError();
1021 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001022 case Builtin::BI__GetExceptionInfo:
1023 if (checkArgCount(*this, TheCall, 1))
1024 return ExprError();
1025
1026 if (CheckCXXThrowOperand(
1027 TheCall->getLocStart(),
1028 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1029 TheCall))
1030 return ExprError();
1031
1032 TheCall->setType(Context.VoidPtrTy);
1033 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001034 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001035 case Builtin::BIread_pipe:
1036 case Builtin::BIwrite_pipe:
1037 // Since those two functions are declared with var args, we need a semantic
1038 // check for the argument.
1039 if (SemaBuiltinRWPipe(*this, TheCall))
1040 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001041 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001042 break;
1043 case Builtin::BIreserve_read_pipe:
1044 case Builtin::BIreserve_write_pipe:
1045 case Builtin::BIwork_group_reserve_read_pipe:
1046 case Builtin::BIwork_group_reserve_write_pipe:
1047 case Builtin::BIsub_group_reserve_read_pipe:
1048 case Builtin::BIsub_group_reserve_write_pipe:
1049 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1050 return ExprError();
1051 // Since return type of reserve_read/write_pipe built-in function is
1052 // reserve_id_t, which is not defined in the builtin def file , we used int
1053 // as return type and need to override the return type of these functions.
1054 TheCall->setType(Context.OCLReserveIDTy);
1055 break;
1056 case Builtin::BIcommit_read_pipe:
1057 case Builtin::BIcommit_write_pipe:
1058 case Builtin::BIwork_group_commit_read_pipe:
1059 case Builtin::BIwork_group_commit_write_pipe:
1060 case Builtin::BIsub_group_commit_read_pipe:
1061 case Builtin::BIsub_group_commit_write_pipe:
1062 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1063 return ExprError();
1064 break;
1065 case Builtin::BIget_pipe_num_packets:
1066 case Builtin::BIget_pipe_max_packets:
1067 if (SemaBuiltinPipePackets(*this, TheCall))
1068 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001069 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001070 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001071 case Builtin::BIto_global:
1072 case Builtin::BIto_local:
1073 case Builtin::BIto_private:
1074 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1075 return ExprError();
1076 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001077 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1078 case Builtin::BIenqueue_kernel:
1079 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1080 return ExprError();
1081 break;
1082 case Builtin::BIget_kernel_work_group_size:
1083 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1084 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1085 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001086 break;
1087 case Builtin::BI__builtin_os_log_format:
1088 case Builtin::BI__builtin_os_log_format_buffer_size:
1089 if (SemaBuiltinOSLogFormat(TheCall)) {
1090 return ExprError();
1091 }
1092 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001093 }
Richard Smith760520b2014-06-03 23:27:44 +00001094
Nate Begeman4904e322010-06-08 02:47:44 +00001095 // Since the target specific builtins for each arch overlap, only check those
1096 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001097 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001098 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001099 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001100 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001101 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001102 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001103 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1104 return ExprError();
1105 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001106 case llvm::Triple::aarch64:
1107 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001108 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001109 return ExprError();
1110 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001111 case llvm::Triple::mips:
1112 case llvm::Triple::mipsel:
1113 case llvm::Triple::mips64:
1114 case llvm::Triple::mips64el:
1115 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1116 return ExprError();
1117 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001118 case llvm::Triple::systemz:
1119 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1120 return ExprError();
1121 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001122 case llvm::Triple::x86:
1123 case llvm::Triple::x86_64:
1124 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1125 return ExprError();
1126 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001127 case llvm::Triple::ppc:
1128 case llvm::Triple::ppc64:
1129 case llvm::Triple::ppc64le:
1130 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1131 return ExprError();
1132 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001133 default:
1134 break;
1135 }
1136 }
1137
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001138 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001139}
1140
Nate Begeman91e1fea2010-06-14 05:21:25 +00001141// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001142static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001143 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001144 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001145 switch (Type.getEltType()) {
1146 case NeonTypeFlags::Int8:
1147 case NeonTypeFlags::Poly8:
1148 return shift ? 7 : (8 << IsQuad) - 1;
1149 case NeonTypeFlags::Int16:
1150 case NeonTypeFlags::Poly16:
1151 return shift ? 15 : (4 << IsQuad) - 1;
1152 case NeonTypeFlags::Int32:
1153 return shift ? 31 : (2 << IsQuad) - 1;
1154 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001155 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001156 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001157 case NeonTypeFlags::Poly128:
1158 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001159 case NeonTypeFlags::Float16:
1160 assert(!shift && "cannot shift float types!");
1161 return (4 << IsQuad) - 1;
1162 case NeonTypeFlags::Float32:
1163 assert(!shift && "cannot shift float types!");
1164 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001165 case NeonTypeFlags::Float64:
1166 assert(!shift && "cannot shift float types!");
1167 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001168 }
David Blaikie8a40f702012-01-17 06:56:22 +00001169 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001170}
1171
Bob Wilsone4d77232011-11-08 05:04:11 +00001172/// getNeonEltType - Return the QualType corresponding to the elements of
1173/// the vector type specified by the NeonTypeFlags. This is used to check
1174/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001175static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001176 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001177 switch (Flags.getEltType()) {
1178 case NeonTypeFlags::Int8:
1179 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1180 case NeonTypeFlags::Int16:
1181 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1182 case NeonTypeFlags::Int32:
1183 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1184 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001185 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001186 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1187 else
1188 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1189 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001190 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001191 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001192 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001193 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001194 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001195 if (IsInt64Long)
1196 return Context.UnsignedLongTy;
1197 else
1198 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001199 case NeonTypeFlags::Poly128:
1200 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001201 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001202 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001203 case NeonTypeFlags::Float32:
1204 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001205 case NeonTypeFlags::Float64:
1206 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001207 }
David Blaikie8a40f702012-01-17 06:56:22 +00001208 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001209}
1210
Tim Northover12670412014-02-19 10:37:05 +00001211bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001212 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001213 uint64_t mask = 0;
1214 unsigned TV = 0;
1215 int PtrArgNum = -1;
1216 bool HasConstPtr = false;
1217 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001218#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001219#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001220#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001221 }
1222
1223 // For NEON intrinsics which are overloaded on vector element type, validate
1224 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001225 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001226 if (mask) {
1227 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1228 return true;
1229
1230 TV = Result.getLimitedValue(64);
1231 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1232 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001233 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001234 }
1235
1236 if (PtrArgNum >= 0) {
1237 // Check that pointer arguments have the specified type.
1238 Expr *Arg = TheCall->getArg(PtrArgNum);
1239 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1240 Arg = ICE->getSubExpr();
1241 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1242 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001243
Tim Northovera2ee4332014-03-29 15:09:45 +00001244 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +00001245 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +00001246 bool IsInt64Long =
1247 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1248 QualType EltTy =
1249 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001250 if (HasConstPtr)
1251 EltTy = EltTy.withConst();
1252 QualType LHSTy = Context.getPointerType(EltTy);
1253 AssignConvertType ConvTy;
1254 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1255 if (RHS.isInvalid())
1256 return true;
1257 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1258 RHS.get(), AA_Assigning))
1259 return true;
1260 }
1261
1262 // For NEON intrinsics which take an immediate value as part of the
1263 // instruction, range check them here.
1264 unsigned i = 0, l = 0, u = 0;
1265 switch (BuiltinID) {
1266 default:
1267 return false;
Tim Northover12670412014-02-19 10:37:05 +00001268#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001269#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001270#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001271 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001272
Richard Sandiford28940af2014-04-16 08:47:51 +00001273 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001274}
1275
Tim Northovera2ee4332014-03-29 15:09:45 +00001276bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1277 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001278 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001279 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001280 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001281 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001282 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001283 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1284 BuiltinID == AArch64::BI__builtin_arm_strex ||
1285 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001286 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001287 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001288 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1289 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1290 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001291
1292 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1293
1294 // Ensure that we have the proper number of arguments.
1295 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1296 return true;
1297
1298 // Inspect the pointer argument of the atomic builtin. This should always be
1299 // a pointer type, whose element is an integral scalar or pointer type.
1300 // Because it is a pointer type, we don't have to worry about any implicit
1301 // casts here.
1302 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1303 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1304 if (PointerArgRes.isInvalid())
1305 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001306 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001307
1308 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1309 if (!pointerType) {
1310 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1311 << PointerArg->getType() << PointerArg->getSourceRange();
1312 return true;
1313 }
1314
1315 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1316 // task is to insert the appropriate casts into the AST. First work out just
1317 // what the appropriate type is.
1318 QualType ValType = pointerType->getPointeeType();
1319 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1320 if (IsLdrex)
1321 AddrType.addConst();
1322
1323 // Issue a warning if the cast is dodgy.
1324 CastKind CastNeeded = CK_NoOp;
1325 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1326 CastNeeded = CK_BitCast;
1327 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1328 << PointerArg->getType()
1329 << Context.getPointerType(AddrType)
1330 << AA_Passing << PointerArg->getSourceRange();
1331 }
1332
1333 // Finally, do the cast and replace the argument with the corrected version.
1334 AddrType = Context.getPointerType(AddrType);
1335 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1336 if (PointerArgRes.isInvalid())
1337 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001338 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001339
1340 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1341
1342 // In general, we allow ints, floats and pointers to be loaded and stored.
1343 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1344 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1345 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1346 << PointerArg->getType() << PointerArg->getSourceRange();
1347 return true;
1348 }
1349
1350 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001351 if (Context.getTypeSize(ValType) > MaxWidth) {
1352 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001353 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1354 << PointerArg->getType() << PointerArg->getSourceRange();
1355 return true;
1356 }
1357
1358 switch (ValType.getObjCLifetime()) {
1359 case Qualifiers::OCL_None:
1360 case Qualifiers::OCL_ExplicitNone:
1361 // okay
1362 break;
1363
1364 case Qualifiers::OCL_Weak:
1365 case Qualifiers::OCL_Strong:
1366 case Qualifiers::OCL_Autoreleasing:
1367 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1368 << ValType << PointerArg->getSourceRange();
1369 return true;
1370 }
1371
Tim Northover6aacd492013-07-16 09:47:53 +00001372 if (IsLdrex) {
1373 TheCall->setType(ValType);
1374 return false;
1375 }
1376
1377 // Initialize the argument to be stored.
1378 ExprResult ValArg = TheCall->getArg(0);
1379 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1380 Context, ValType, /*consume*/ false);
1381 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1382 if (ValArg.isInvalid())
1383 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001384 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001385
1386 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1387 // but the custom checker bypasses all default analysis.
1388 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001389 return false;
1390}
1391
Nate Begeman4904e322010-06-08 02:47:44 +00001392bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +00001393 llvm::APSInt Result;
1394
Tim Northover6aacd492013-07-16 09:47:53 +00001395 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001396 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1397 BuiltinID == ARM::BI__builtin_arm_strex ||
1398 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001399 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001400 }
1401
Yi Kong26d104a2014-08-13 19:18:14 +00001402 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1403 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1404 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1405 }
1406
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001407 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1408 BuiltinID == ARM::BI__builtin_arm_wsr64)
1409 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1410
1411 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1412 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1413 BuiltinID == ARM::BI__builtin_arm_wsr ||
1414 BuiltinID == ARM::BI__builtin_arm_wsrp)
1415 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1416
Tim Northover12670412014-02-19 10:37:05 +00001417 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1418 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001419
Yi Kong4efadfb2014-07-03 16:01:25 +00001420 // For intrinsics which take an immediate value as part of the instruction,
1421 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001422 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001423 switch (BuiltinID) {
1424 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001425 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1426 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001427 case ARM::BI__builtin_arm_vcvtr_f:
1428 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001429 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001430 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001431 case ARM::BI__builtin_arm_isb:
1432 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001433 }
Nate Begemand773fe62010-06-13 04:47:52 +00001434
Nate Begemanf568b072010-08-03 21:32:34 +00001435 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001436 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001437}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001438
Tim Northover573cbee2014-05-24 12:52:07 +00001439bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001440 CallExpr *TheCall) {
1441 llvm::APSInt Result;
1442
Tim Northover573cbee2014-05-24 12:52:07 +00001443 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001444 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1445 BuiltinID == AArch64::BI__builtin_arm_strex ||
1446 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001447 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1448 }
1449
Yi Konga5548432014-08-13 19:18:20 +00001450 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1451 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1452 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1453 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1454 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1455 }
1456
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001457 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1458 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001459 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001460
1461 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1462 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1463 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1464 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1465 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1466
Tim Northovera2ee4332014-03-29 15:09:45 +00001467 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1468 return true;
1469
Yi Kong19a29ac2014-07-17 10:52:06 +00001470 // For intrinsics which take an immediate value as part of the instruction,
1471 // range check them here.
1472 unsigned i = 0, l = 0, u = 0;
1473 switch (BuiltinID) {
1474 default: return false;
1475 case AArch64::BI__builtin_arm_dmb:
1476 case AArch64::BI__builtin_arm_dsb:
1477 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1478 }
1479
Yi Kong19a29ac2014-07-17 10:52:06 +00001480 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001481}
1482
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001483// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1484// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1485// ordering for DSP is unspecified. MSA is ordered by the data format used
1486// by the underlying instruction i.e., df/m, df/n and then by size.
1487//
1488// FIXME: The size tests here should instead be tablegen'd along with the
1489// definitions from include/clang/Basic/BuiltinsMips.def.
1490// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1491// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001492bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001493 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001494 switch (BuiltinID) {
1495 default: return false;
1496 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1497 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001498 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1499 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1500 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1501 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1502 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001503 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1504 // df/m field.
1505 // These intrinsics take an unsigned 3 bit immediate.
1506 case Mips::BI__builtin_msa_bclri_b:
1507 case Mips::BI__builtin_msa_bnegi_b:
1508 case Mips::BI__builtin_msa_bseti_b:
1509 case Mips::BI__builtin_msa_sat_s_b:
1510 case Mips::BI__builtin_msa_sat_u_b:
1511 case Mips::BI__builtin_msa_slli_b:
1512 case Mips::BI__builtin_msa_srai_b:
1513 case Mips::BI__builtin_msa_srari_b:
1514 case Mips::BI__builtin_msa_srli_b:
1515 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1516 case Mips::BI__builtin_msa_binsli_b:
1517 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1518 // These intrinsics take an unsigned 4 bit immediate.
1519 case Mips::BI__builtin_msa_bclri_h:
1520 case Mips::BI__builtin_msa_bnegi_h:
1521 case Mips::BI__builtin_msa_bseti_h:
1522 case Mips::BI__builtin_msa_sat_s_h:
1523 case Mips::BI__builtin_msa_sat_u_h:
1524 case Mips::BI__builtin_msa_slli_h:
1525 case Mips::BI__builtin_msa_srai_h:
1526 case Mips::BI__builtin_msa_srari_h:
1527 case Mips::BI__builtin_msa_srli_h:
1528 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1529 case Mips::BI__builtin_msa_binsli_h:
1530 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1531 // These intrinsics take an unsigned 5 bit immedate.
1532 // The first block of intrinsics actually have an unsigned 5 bit field,
1533 // not a df/n field.
1534 case Mips::BI__builtin_msa_clei_u_b:
1535 case Mips::BI__builtin_msa_clei_u_h:
1536 case Mips::BI__builtin_msa_clei_u_w:
1537 case Mips::BI__builtin_msa_clei_u_d:
1538 case Mips::BI__builtin_msa_clti_u_b:
1539 case Mips::BI__builtin_msa_clti_u_h:
1540 case Mips::BI__builtin_msa_clti_u_w:
1541 case Mips::BI__builtin_msa_clti_u_d:
1542 case Mips::BI__builtin_msa_maxi_u_b:
1543 case Mips::BI__builtin_msa_maxi_u_h:
1544 case Mips::BI__builtin_msa_maxi_u_w:
1545 case Mips::BI__builtin_msa_maxi_u_d:
1546 case Mips::BI__builtin_msa_mini_u_b:
1547 case Mips::BI__builtin_msa_mini_u_h:
1548 case Mips::BI__builtin_msa_mini_u_w:
1549 case Mips::BI__builtin_msa_mini_u_d:
1550 case Mips::BI__builtin_msa_addvi_b:
1551 case Mips::BI__builtin_msa_addvi_h:
1552 case Mips::BI__builtin_msa_addvi_w:
1553 case Mips::BI__builtin_msa_addvi_d:
1554 case Mips::BI__builtin_msa_bclri_w:
1555 case Mips::BI__builtin_msa_bnegi_w:
1556 case Mips::BI__builtin_msa_bseti_w:
1557 case Mips::BI__builtin_msa_sat_s_w:
1558 case Mips::BI__builtin_msa_sat_u_w:
1559 case Mips::BI__builtin_msa_slli_w:
1560 case Mips::BI__builtin_msa_srai_w:
1561 case Mips::BI__builtin_msa_srari_w:
1562 case Mips::BI__builtin_msa_srli_w:
1563 case Mips::BI__builtin_msa_srlri_w:
1564 case Mips::BI__builtin_msa_subvi_b:
1565 case Mips::BI__builtin_msa_subvi_h:
1566 case Mips::BI__builtin_msa_subvi_w:
1567 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1568 case Mips::BI__builtin_msa_binsli_w:
1569 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1570 // These intrinsics take an unsigned 6 bit immediate.
1571 case Mips::BI__builtin_msa_bclri_d:
1572 case Mips::BI__builtin_msa_bnegi_d:
1573 case Mips::BI__builtin_msa_bseti_d:
1574 case Mips::BI__builtin_msa_sat_s_d:
1575 case Mips::BI__builtin_msa_sat_u_d:
1576 case Mips::BI__builtin_msa_slli_d:
1577 case Mips::BI__builtin_msa_srai_d:
1578 case Mips::BI__builtin_msa_srari_d:
1579 case Mips::BI__builtin_msa_srli_d:
1580 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1581 case Mips::BI__builtin_msa_binsli_d:
1582 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1583 // These intrinsics take a signed 5 bit immediate.
1584 case Mips::BI__builtin_msa_ceqi_b:
1585 case Mips::BI__builtin_msa_ceqi_h:
1586 case Mips::BI__builtin_msa_ceqi_w:
1587 case Mips::BI__builtin_msa_ceqi_d:
1588 case Mips::BI__builtin_msa_clti_s_b:
1589 case Mips::BI__builtin_msa_clti_s_h:
1590 case Mips::BI__builtin_msa_clti_s_w:
1591 case Mips::BI__builtin_msa_clti_s_d:
1592 case Mips::BI__builtin_msa_clei_s_b:
1593 case Mips::BI__builtin_msa_clei_s_h:
1594 case Mips::BI__builtin_msa_clei_s_w:
1595 case Mips::BI__builtin_msa_clei_s_d:
1596 case Mips::BI__builtin_msa_maxi_s_b:
1597 case Mips::BI__builtin_msa_maxi_s_h:
1598 case Mips::BI__builtin_msa_maxi_s_w:
1599 case Mips::BI__builtin_msa_maxi_s_d:
1600 case Mips::BI__builtin_msa_mini_s_b:
1601 case Mips::BI__builtin_msa_mini_s_h:
1602 case Mips::BI__builtin_msa_mini_s_w:
1603 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1604 // These intrinsics take an unsigned 8 bit immediate.
1605 case Mips::BI__builtin_msa_andi_b:
1606 case Mips::BI__builtin_msa_nori_b:
1607 case Mips::BI__builtin_msa_ori_b:
1608 case Mips::BI__builtin_msa_shf_b:
1609 case Mips::BI__builtin_msa_shf_h:
1610 case Mips::BI__builtin_msa_shf_w:
1611 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1612 case Mips::BI__builtin_msa_bseli_b:
1613 case Mips::BI__builtin_msa_bmnzi_b:
1614 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1615 // df/n format
1616 // These intrinsics take an unsigned 4 bit immediate.
1617 case Mips::BI__builtin_msa_copy_s_b:
1618 case Mips::BI__builtin_msa_copy_u_b:
1619 case Mips::BI__builtin_msa_insve_b:
1620 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1621 case Mips::BI__builtin_msa_sld_b:
1622 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1623 // These intrinsics take an unsigned 3 bit immediate.
1624 case Mips::BI__builtin_msa_copy_s_h:
1625 case Mips::BI__builtin_msa_copy_u_h:
1626 case Mips::BI__builtin_msa_insve_h:
1627 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1628 case Mips::BI__builtin_msa_sld_h:
1629 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1630 // These intrinsics take an unsigned 2 bit immediate.
1631 case Mips::BI__builtin_msa_copy_s_w:
1632 case Mips::BI__builtin_msa_copy_u_w:
1633 case Mips::BI__builtin_msa_insve_w:
1634 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1635 case Mips::BI__builtin_msa_sld_w:
1636 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1637 // These intrinsics take an unsigned 1 bit immediate.
1638 case Mips::BI__builtin_msa_copy_s_d:
1639 case Mips::BI__builtin_msa_copy_u_d:
1640 case Mips::BI__builtin_msa_insve_d:
1641 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1642 case Mips::BI__builtin_msa_sld_d:
1643 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1644 // Memory offsets and immediate loads.
1645 // These intrinsics take a signed 10 bit immediate.
1646 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 127; break;
1647 case Mips::BI__builtin_msa_ldi_h:
1648 case Mips::BI__builtin_msa_ldi_w:
1649 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1650 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1651 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1652 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1653 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1654 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1655 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1656 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1657 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001658 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001659
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001660 if (!m)
1661 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1662
1663 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1664 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001665}
1666
Kit Bartone50adcb2015-03-30 19:40:59 +00001667bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1668 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001669 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1670 BuiltinID == PPC::BI__builtin_divdeu ||
1671 BuiltinID == PPC::BI__builtin_bpermd;
1672 bool IsTarget64Bit = Context.getTargetInfo()
1673 .getTypeWidth(Context
1674 .getTargetInfo()
1675 .getIntPtrType()) == 64;
1676 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1677 BuiltinID == PPC::BI__builtin_divweu ||
1678 BuiltinID == PPC::BI__builtin_divde ||
1679 BuiltinID == PPC::BI__builtin_divdeu;
1680
1681 if (Is64BitBltin && !IsTarget64Bit)
1682 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1683 << TheCall->getSourceRange();
1684
1685 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1686 (BuiltinID == PPC::BI__builtin_bpermd &&
1687 !Context.getTargetInfo().hasFeature("bpermd")))
1688 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1689 << TheCall->getSourceRange();
1690
Kit Bartone50adcb2015-03-30 19:40:59 +00001691 switch (BuiltinID) {
1692 default: return false;
1693 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1694 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1695 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1696 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1697 case PPC::BI__builtin_tbegin:
1698 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1699 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1700 case PPC::BI__builtin_tabortwc:
1701 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1702 case PPC::BI__builtin_tabortwci:
1703 case PPC::BI__builtin_tabortdci:
1704 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1705 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1706 }
1707 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1708}
1709
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001710bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1711 CallExpr *TheCall) {
1712 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1713 Expr *Arg = TheCall->getArg(0);
1714 llvm::APSInt AbortCode(32);
1715 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1716 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1717 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1718 << Arg->getSourceRange();
1719 }
1720
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001721 // For intrinsics which take an immediate value as part of the instruction,
1722 // range check them here.
1723 unsigned i = 0, l = 0, u = 0;
1724 switch (BuiltinID) {
1725 default: return false;
1726 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1727 case SystemZ::BI__builtin_s390_verimb:
1728 case SystemZ::BI__builtin_s390_verimh:
1729 case SystemZ::BI__builtin_s390_verimf:
1730 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1731 case SystemZ::BI__builtin_s390_vfaeb:
1732 case SystemZ::BI__builtin_s390_vfaeh:
1733 case SystemZ::BI__builtin_s390_vfaef:
1734 case SystemZ::BI__builtin_s390_vfaebs:
1735 case SystemZ::BI__builtin_s390_vfaehs:
1736 case SystemZ::BI__builtin_s390_vfaefs:
1737 case SystemZ::BI__builtin_s390_vfaezb:
1738 case SystemZ::BI__builtin_s390_vfaezh:
1739 case SystemZ::BI__builtin_s390_vfaezf:
1740 case SystemZ::BI__builtin_s390_vfaezbs:
1741 case SystemZ::BI__builtin_s390_vfaezhs:
1742 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1743 case SystemZ::BI__builtin_s390_vfidb:
1744 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1745 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1746 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1747 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1748 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1749 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1750 case SystemZ::BI__builtin_s390_vstrcb:
1751 case SystemZ::BI__builtin_s390_vstrch:
1752 case SystemZ::BI__builtin_s390_vstrcf:
1753 case SystemZ::BI__builtin_s390_vstrczb:
1754 case SystemZ::BI__builtin_s390_vstrczh:
1755 case SystemZ::BI__builtin_s390_vstrczf:
1756 case SystemZ::BI__builtin_s390_vstrcbs:
1757 case SystemZ::BI__builtin_s390_vstrchs:
1758 case SystemZ::BI__builtin_s390_vstrcfs:
1759 case SystemZ::BI__builtin_s390_vstrczbs:
1760 case SystemZ::BI__builtin_s390_vstrczhs:
1761 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1762 }
1763 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001764}
1765
Craig Topper5ba2c502015-11-07 08:08:31 +00001766/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1767/// This checks that the target supports __builtin_cpu_supports and
1768/// that the string argument is constant and valid.
1769static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1770 Expr *Arg = TheCall->getArg(0);
1771
1772 // Check if the argument is a string literal.
1773 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1774 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1775 << Arg->getSourceRange();
1776
1777 // Check the contents of the string.
1778 StringRef Feature =
1779 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1780 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1781 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1782 << Arg->getSourceRange();
1783 return false;
1784}
1785
Craig Toppera7e253e2016-09-23 04:48:31 +00001786// Check if the rounding mode is legal.
1787bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1788 // Indicates if this instruction has rounding control or just SAE.
1789 bool HasRC = false;
1790
1791 unsigned ArgNum = 0;
1792 switch (BuiltinID) {
1793 default:
1794 return false;
1795 case X86::BI__builtin_ia32_vcvttsd2si32:
1796 case X86::BI__builtin_ia32_vcvttsd2si64:
1797 case X86::BI__builtin_ia32_vcvttsd2usi32:
1798 case X86::BI__builtin_ia32_vcvttsd2usi64:
1799 case X86::BI__builtin_ia32_vcvttss2si32:
1800 case X86::BI__builtin_ia32_vcvttss2si64:
1801 case X86::BI__builtin_ia32_vcvttss2usi32:
1802 case X86::BI__builtin_ia32_vcvttss2usi64:
1803 ArgNum = 1;
1804 break;
1805 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1806 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1807 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1808 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1809 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1810 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1811 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1812 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1813 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1814 case X86::BI__builtin_ia32_exp2pd_mask:
1815 case X86::BI__builtin_ia32_exp2ps_mask:
1816 case X86::BI__builtin_ia32_getexppd512_mask:
1817 case X86::BI__builtin_ia32_getexpps512_mask:
1818 case X86::BI__builtin_ia32_rcp28pd_mask:
1819 case X86::BI__builtin_ia32_rcp28ps_mask:
1820 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1821 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1822 case X86::BI__builtin_ia32_vcomisd:
1823 case X86::BI__builtin_ia32_vcomiss:
1824 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1825 ArgNum = 3;
1826 break;
1827 case X86::BI__builtin_ia32_cmppd512_mask:
1828 case X86::BI__builtin_ia32_cmpps512_mask:
1829 case X86::BI__builtin_ia32_cmpsd_mask:
1830 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001831 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001832 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1833 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001834 case X86::BI__builtin_ia32_maxpd512_mask:
1835 case X86::BI__builtin_ia32_maxps512_mask:
1836 case X86::BI__builtin_ia32_maxsd_round_mask:
1837 case X86::BI__builtin_ia32_maxss_round_mask:
1838 case X86::BI__builtin_ia32_minpd512_mask:
1839 case X86::BI__builtin_ia32_minps512_mask:
1840 case X86::BI__builtin_ia32_minsd_round_mask:
1841 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001842 case X86::BI__builtin_ia32_rcp28sd_round_mask:
1843 case X86::BI__builtin_ia32_rcp28ss_round_mask:
1844 case X86::BI__builtin_ia32_reducepd512_mask:
1845 case X86::BI__builtin_ia32_reduceps512_mask:
1846 case X86::BI__builtin_ia32_rndscalepd_mask:
1847 case X86::BI__builtin_ia32_rndscaleps_mask:
1848 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1849 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1850 ArgNum = 4;
1851 break;
1852 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001853 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001854 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001855 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001856 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001857 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001858 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001859 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001860 case X86::BI__builtin_ia32_rangepd512_mask:
1861 case X86::BI__builtin_ia32_rangeps512_mask:
1862 case X86::BI__builtin_ia32_rangesd128_round_mask:
1863 case X86::BI__builtin_ia32_rangess128_round_mask:
1864 case X86::BI__builtin_ia32_reducesd_mask:
1865 case X86::BI__builtin_ia32_reducess_mask:
1866 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1867 case X86::BI__builtin_ia32_rndscaless_round_mask:
1868 ArgNum = 5;
1869 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00001870 case X86::BI__builtin_ia32_vcvtsd2si64:
1871 case X86::BI__builtin_ia32_vcvtsd2si32:
1872 case X86::BI__builtin_ia32_vcvtsd2usi32:
1873 case X86::BI__builtin_ia32_vcvtsd2usi64:
1874 case X86::BI__builtin_ia32_vcvtss2si32:
1875 case X86::BI__builtin_ia32_vcvtss2si64:
1876 case X86::BI__builtin_ia32_vcvtss2usi32:
1877 case X86::BI__builtin_ia32_vcvtss2usi64:
1878 ArgNum = 1;
1879 HasRC = true;
1880 break;
Craig Topper8e066312016-11-07 07:01:09 +00001881 case X86::BI__builtin_ia32_cvtsi2sd64:
1882 case X86::BI__builtin_ia32_cvtsi2ss32:
1883 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00001884 case X86::BI__builtin_ia32_cvtusi2sd64:
1885 case X86::BI__builtin_ia32_cvtusi2ss32:
1886 case X86::BI__builtin_ia32_cvtusi2ss64:
1887 ArgNum = 2;
1888 HasRC = true;
1889 break;
1890 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1891 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1892 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1893 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1894 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1895 case X86::BI__builtin_ia32_cvtps2qq512_mask:
1896 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1897 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1898 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1899 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1900 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001901 case X86::BI__builtin_ia32_sqrtpd512_mask:
1902 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001903 ArgNum = 3;
1904 HasRC = true;
1905 break;
1906 case X86::BI__builtin_ia32_addpd512_mask:
1907 case X86::BI__builtin_ia32_addps512_mask:
1908 case X86::BI__builtin_ia32_divpd512_mask:
1909 case X86::BI__builtin_ia32_divps512_mask:
1910 case X86::BI__builtin_ia32_mulpd512_mask:
1911 case X86::BI__builtin_ia32_mulps512_mask:
1912 case X86::BI__builtin_ia32_subpd512_mask:
1913 case X86::BI__builtin_ia32_subps512_mask:
1914 case X86::BI__builtin_ia32_addss_round_mask:
1915 case X86::BI__builtin_ia32_addsd_round_mask:
1916 case X86::BI__builtin_ia32_divss_round_mask:
1917 case X86::BI__builtin_ia32_divsd_round_mask:
1918 case X86::BI__builtin_ia32_mulss_round_mask:
1919 case X86::BI__builtin_ia32_mulsd_round_mask:
1920 case X86::BI__builtin_ia32_subss_round_mask:
1921 case X86::BI__builtin_ia32_subsd_round_mask:
1922 case X86::BI__builtin_ia32_scalefpd512_mask:
1923 case X86::BI__builtin_ia32_scalefps512_mask:
1924 case X86::BI__builtin_ia32_scalefsd_round_mask:
1925 case X86::BI__builtin_ia32_scalefss_round_mask:
1926 case X86::BI__builtin_ia32_getmantpd512_mask:
1927 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001928 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
1929 case X86::BI__builtin_ia32_sqrtsd_round_mask:
1930 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001931 case X86::BI__builtin_ia32_vfmaddpd512_mask:
1932 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1933 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1934 case X86::BI__builtin_ia32_vfmaddps512_mask:
1935 case X86::BI__builtin_ia32_vfmaddps512_mask3:
1936 case X86::BI__builtin_ia32_vfmaddps512_maskz:
1937 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1938 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1939 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1940 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1941 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1942 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1943 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1944 case X86::BI__builtin_ia32_vfmsubps512_mask3:
1945 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1946 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1947 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1948 case X86::BI__builtin_ia32_vfnmaddps512_mask:
1949 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1950 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1951 case X86::BI__builtin_ia32_vfnmsubps512_mask:
1952 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1953 case X86::BI__builtin_ia32_vfmaddsd3_mask:
1954 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1955 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1956 case X86::BI__builtin_ia32_vfmaddss3_mask:
1957 case X86::BI__builtin_ia32_vfmaddss3_maskz:
1958 case X86::BI__builtin_ia32_vfmaddss3_mask3:
1959 ArgNum = 4;
1960 HasRC = true;
1961 break;
1962 case X86::BI__builtin_ia32_getmantsd_round_mask:
1963 case X86::BI__builtin_ia32_getmantss_round_mask:
1964 ArgNum = 5;
1965 HasRC = true;
1966 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00001967 }
1968
1969 llvm::APSInt Result;
1970
1971 // We can't check the value of a dependent argument.
1972 Expr *Arg = TheCall->getArg(ArgNum);
1973 if (Arg->isTypeDependent() || Arg->isValueDependent())
1974 return false;
1975
1976 // Check constant-ness first.
1977 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1978 return true;
1979
1980 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1981 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1982 // combined with ROUND_NO_EXC.
1983 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1984 Result == 8/*ROUND_NO_EXC*/ ||
1985 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1986 return false;
1987
1988 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1989 << Arg->getSourceRange();
1990}
1991
Craig Topperf0ddc892016-09-23 04:48:27 +00001992bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1993 if (BuiltinID == X86::BI__builtin_cpu_supports)
1994 return SemaBuiltinCpuSupports(*this, TheCall);
1995
1996 if (BuiltinID == X86::BI__builtin_ms_va_start)
1997 return SemaBuiltinMSVAStart(TheCall);
1998
Craig Toppera7e253e2016-09-23 04:48:31 +00001999 // If the intrinsic has rounding or SAE make sure its valid.
2000 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2001 return true;
2002
Craig Topperf0ddc892016-09-23 04:48:27 +00002003 // For intrinsics which take an immediate value as part of the instruction,
2004 // range check them here.
2005 int i = 0, l = 0, u = 0;
2006 switch (BuiltinID) {
2007 default:
2008 return false;
Richard Trieucc3949d2016-02-18 22:34:54 +00002009 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00002010 i = 1; l = 0; u = 3;
2011 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002012 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00002013 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2014 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2015 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2016 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002017 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002018 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002019 case X86::BI__builtin_ia32_vpermil2pd:
2020 case X86::BI__builtin_ia32_vpermil2pd256:
2021 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002022 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002023 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002024 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002025 case X86::BI__builtin_ia32_cmpb128_mask:
2026 case X86::BI__builtin_ia32_cmpw128_mask:
2027 case X86::BI__builtin_ia32_cmpd128_mask:
2028 case X86::BI__builtin_ia32_cmpq128_mask:
2029 case X86::BI__builtin_ia32_cmpb256_mask:
2030 case X86::BI__builtin_ia32_cmpw256_mask:
2031 case X86::BI__builtin_ia32_cmpd256_mask:
2032 case X86::BI__builtin_ia32_cmpq256_mask:
2033 case X86::BI__builtin_ia32_cmpb512_mask:
2034 case X86::BI__builtin_ia32_cmpw512_mask:
2035 case X86::BI__builtin_ia32_cmpd512_mask:
2036 case X86::BI__builtin_ia32_cmpq512_mask:
2037 case X86::BI__builtin_ia32_ucmpb128_mask:
2038 case X86::BI__builtin_ia32_ucmpw128_mask:
2039 case X86::BI__builtin_ia32_ucmpd128_mask:
2040 case X86::BI__builtin_ia32_ucmpq128_mask:
2041 case X86::BI__builtin_ia32_ucmpb256_mask:
2042 case X86::BI__builtin_ia32_ucmpw256_mask:
2043 case X86::BI__builtin_ia32_ucmpd256_mask:
2044 case X86::BI__builtin_ia32_ucmpq256_mask:
2045 case X86::BI__builtin_ia32_ucmpb512_mask:
2046 case X86::BI__builtin_ia32_ucmpw512_mask:
2047 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002048 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002049 case X86::BI__builtin_ia32_vpcomub:
2050 case X86::BI__builtin_ia32_vpcomuw:
2051 case X86::BI__builtin_ia32_vpcomud:
2052 case X86::BI__builtin_ia32_vpcomuq:
2053 case X86::BI__builtin_ia32_vpcomb:
2054 case X86::BI__builtin_ia32_vpcomw:
2055 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002056 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00002057 i = 2; l = 0; u = 7;
2058 break;
2059 case X86::BI__builtin_ia32_roundps:
2060 case X86::BI__builtin_ia32_roundpd:
2061 case X86::BI__builtin_ia32_roundps256:
2062 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002063 i = 1; l = 0; u = 15;
2064 break;
2065 case X86::BI__builtin_ia32_roundss:
2066 case X86::BI__builtin_ia32_roundsd:
2067 case X86::BI__builtin_ia32_rangepd128_mask:
2068 case X86::BI__builtin_ia32_rangepd256_mask:
2069 case X86::BI__builtin_ia32_rangepd512_mask:
2070 case X86::BI__builtin_ia32_rangeps128_mask:
2071 case X86::BI__builtin_ia32_rangeps256_mask:
2072 case X86::BI__builtin_ia32_rangeps512_mask:
2073 case X86::BI__builtin_ia32_getmantsd_round_mask:
2074 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002075 i = 2; l = 0; u = 15;
2076 break;
2077 case X86::BI__builtin_ia32_cmpps:
2078 case X86::BI__builtin_ia32_cmpss:
2079 case X86::BI__builtin_ia32_cmppd:
2080 case X86::BI__builtin_ia32_cmpsd:
2081 case X86::BI__builtin_ia32_cmpps256:
2082 case X86::BI__builtin_ia32_cmppd256:
2083 case X86::BI__builtin_ia32_cmpps128_mask:
2084 case X86::BI__builtin_ia32_cmppd128_mask:
2085 case X86::BI__builtin_ia32_cmpps256_mask:
2086 case X86::BI__builtin_ia32_cmppd256_mask:
2087 case X86::BI__builtin_ia32_cmpps512_mask:
2088 case X86::BI__builtin_ia32_cmppd512_mask:
2089 case X86::BI__builtin_ia32_cmpsd_mask:
2090 case X86::BI__builtin_ia32_cmpss_mask:
2091 i = 2; l = 0; u = 31;
2092 break;
2093 case X86::BI__builtin_ia32_xabort:
2094 i = 0; l = -128; u = 255;
2095 break;
2096 case X86::BI__builtin_ia32_pshufw:
2097 case X86::BI__builtin_ia32_aeskeygenassist128:
2098 i = 1; l = -128; u = 255;
2099 break;
2100 case X86::BI__builtin_ia32_vcvtps2ph:
2101 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper39c87102016-05-18 03:18:12 +00002102 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2103 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2104 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2105 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2106 case X86::BI__builtin_ia32_rndscaleps_mask:
2107 case X86::BI__builtin_ia32_rndscalepd_mask:
2108 case X86::BI__builtin_ia32_reducepd128_mask:
2109 case X86::BI__builtin_ia32_reducepd256_mask:
2110 case X86::BI__builtin_ia32_reducepd512_mask:
2111 case X86::BI__builtin_ia32_reduceps128_mask:
2112 case X86::BI__builtin_ia32_reduceps256_mask:
2113 case X86::BI__builtin_ia32_reduceps512_mask:
2114 case X86::BI__builtin_ia32_prold512_mask:
2115 case X86::BI__builtin_ia32_prolq512_mask:
2116 case X86::BI__builtin_ia32_prold128_mask:
2117 case X86::BI__builtin_ia32_prold256_mask:
2118 case X86::BI__builtin_ia32_prolq128_mask:
2119 case X86::BI__builtin_ia32_prolq256_mask:
2120 case X86::BI__builtin_ia32_prord128_mask:
2121 case X86::BI__builtin_ia32_prord256_mask:
2122 case X86::BI__builtin_ia32_prorq128_mask:
2123 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002124 case X86::BI__builtin_ia32_fpclasspd128_mask:
2125 case X86::BI__builtin_ia32_fpclasspd256_mask:
2126 case X86::BI__builtin_ia32_fpclassps128_mask:
2127 case X86::BI__builtin_ia32_fpclassps256_mask:
2128 case X86::BI__builtin_ia32_fpclassps512_mask:
2129 case X86::BI__builtin_ia32_fpclasspd512_mask:
2130 case X86::BI__builtin_ia32_fpclasssd_mask:
2131 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002132 i = 1; l = 0; u = 255;
2133 break;
2134 case X86::BI__builtin_ia32_palignr:
2135 case X86::BI__builtin_ia32_insertps128:
2136 case X86::BI__builtin_ia32_dpps:
2137 case X86::BI__builtin_ia32_dppd:
2138 case X86::BI__builtin_ia32_dpps256:
2139 case X86::BI__builtin_ia32_mpsadbw128:
2140 case X86::BI__builtin_ia32_mpsadbw256:
2141 case X86::BI__builtin_ia32_pcmpistrm128:
2142 case X86::BI__builtin_ia32_pcmpistri128:
2143 case X86::BI__builtin_ia32_pcmpistria128:
2144 case X86::BI__builtin_ia32_pcmpistric128:
2145 case X86::BI__builtin_ia32_pcmpistrio128:
2146 case X86::BI__builtin_ia32_pcmpistris128:
2147 case X86::BI__builtin_ia32_pcmpistriz128:
2148 case X86::BI__builtin_ia32_pclmulqdq128:
2149 case X86::BI__builtin_ia32_vperm2f128_pd256:
2150 case X86::BI__builtin_ia32_vperm2f128_ps256:
2151 case X86::BI__builtin_ia32_vperm2f128_si256:
2152 case X86::BI__builtin_ia32_permti256:
2153 i = 2; l = -128; u = 255;
2154 break;
2155 case X86::BI__builtin_ia32_palignr128:
2156 case X86::BI__builtin_ia32_palignr256:
Craig Topper39c87102016-05-18 03:18:12 +00002157 case X86::BI__builtin_ia32_palignr512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002158 case X86::BI__builtin_ia32_vcomisd:
2159 case X86::BI__builtin_ia32_vcomiss:
2160 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2161 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2162 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2163 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002164 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2165 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2166 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2167 i = 2; l = 0; u = 255;
2168 break;
2169 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2170 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2171 case X86::BI__builtin_ia32_fixupimmps512_mask:
2172 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2173 case X86::BI__builtin_ia32_fixupimmsd_mask:
2174 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2175 case X86::BI__builtin_ia32_fixupimmss_mask:
2176 case X86::BI__builtin_ia32_fixupimmss_maskz:
2177 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2178 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2179 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2180 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2181 case X86::BI__builtin_ia32_fixupimmps128_mask:
2182 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2183 case X86::BI__builtin_ia32_fixupimmps256_mask:
2184 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2185 case X86::BI__builtin_ia32_pternlogd512_mask:
2186 case X86::BI__builtin_ia32_pternlogd512_maskz:
2187 case X86::BI__builtin_ia32_pternlogq512_mask:
2188 case X86::BI__builtin_ia32_pternlogq512_maskz:
2189 case X86::BI__builtin_ia32_pternlogd128_mask:
2190 case X86::BI__builtin_ia32_pternlogd128_maskz:
2191 case X86::BI__builtin_ia32_pternlogd256_mask:
2192 case X86::BI__builtin_ia32_pternlogd256_maskz:
2193 case X86::BI__builtin_ia32_pternlogq128_mask:
2194 case X86::BI__builtin_ia32_pternlogq128_maskz:
2195 case X86::BI__builtin_ia32_pternlogq256_mask:
2196 case X86::BI__builtin_ia32_pternlogq256_maskz:
2197 i = 3; l = 0; u = 255;
2198 break;
2199 case X86::BI__builtin_ia32_pcmpestrm128:
2200 case X86::BI__builtin_ia32_pcmpestri128:
2201 case X86::BI__builtin_ia32_pcmpestria128:
2202 case X86::BI__builtin_ia32_pcmpestric128:
2203 case X86::BI__builtin_ia32_pcmpestrio128:
2204 case X86::BI__builtin_ia32_pcmpestris128:
2205 case X86::BI__builtin_ia32_pcmpestriz128:
2206 i = 4; l = -128; u = 255;
2207 break;
2208 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2209 case X86::BI__builtin_ia32_rndscaless_round_mask:
2210 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002211 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002212 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002213 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002214}
2215
Richard Smith55ce3522012-06-25 20:30:08 +00002216/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2217/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2218/// Returns true when the format fits the function and the FormatStringInfo has
2219/// been populated.
2220bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2221 FormatStringInfo *FSI) {
2222 FSI->HasVAListArg = Format->getFirstArg() == 0;
2223 FSI->FormatIdx = Format->getFormatIdx() - 1;
2224 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002225
Richard Smith55ce3522012-06-25 20:30:08 +00002226 // The way the format attribute works in GCC, the implicit this argument
2227 // of member functions is counted. However, it doesn't appear in our own
2228 // lists, so decrement format_idx in that case.
2229 if (IsCXXMember) {
2230 if(FSI->FormatIdx == 0)
2231 return false;
2232 --FSI->FormatIdx;
2233 if (FSI->FirstDataArg != 0)
2234 --FSI->FirstDataArg;
2235 }
2236 return true;
2237}
Mike Stump11289f42009-09-09 15:08:12 +00002238
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002239/// Checks if a the given expression evaluates to null.
2240///
2241/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002242static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002243 // If the expression has non-null type, it doesn't evaluate to null.
2244 if (auto nullability
2245 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2246 if (*nullability == NullabilityKind::NonNull)
2247 return false;
2248 }
2249
Ted Kremeneka146db32014-01-17 06:24:47 +00002250 // As a special case, transparent unions initialized with zero are
2251 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002252 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002253 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2254 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002255 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002256 if (const InitListExpr *ILE =
2257 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002258 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002259 }
2260
2261 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002262 return (!Expr->isValueDependent() &&
2263 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2264 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002265}
2266
2267static void CheckNonNullArgument(Sema &S,
2268 const Expr *ArgExpr,
2269 SourceLocation CallSiteLoc) {
2270 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002271 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2272 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002273}
2274
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002275bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2276 FormatStringInfo FSI;
2277 if ((GetFormatStringType(Format) == FST_NSString) &&
2278 getFormatStringInfo(Format, false, &FSI)) {
2279 Idx = FSI.FormatIdx;
2280 return true;
2281 }
2282 return false;
2283}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002284/// \brief Diagnose use of %s directive in an NSString which is being passed
2285/// as formatting string to formatting method.
2286static void
2287DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2288 const NamedDecl *FDecl,
2289 Expr **Args,
2290 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002291 unsigned Idx = 0;
2292 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002293 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2294 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002295 Idx = 2;
2296 Format = true;
2297 }
2298 else
2299 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2300 if (S.GetFormatNSStringIdx(I, Idx)) {
2301 Format = true;
2302 break;
2303 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002304 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002305 if (!Format || NumArgs <= Idx)
2306 return;
2307 const Expr *FormatExpr = Args[Idx];
2308 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2309 FormatExpr = CSCE->getSubExpr();
2310 const StringLiteral *FormatString;
2311 if (const ObjCStringLiteral *OSL =
2312 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2313 FormatString = OSL->getString();
2314 else
2315 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2316 if (!FormatString)
2317 return;
2318 if (S.FormatStringHasSArg(FormatString)) {
2319 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2320 << "%s" << 1 << 1;
2321 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2322 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002323 }
2324}
2325
Douglas Gregorb4866e82015-06-19 18:13:19 +00002326/// Determine whether the given type has a non-null nullability annotation.
2327static bool isNonNullType(ASTContext &ctx, QualType type) {
2328 if (auto nullability = type->getNullability(ctx))
2329 return *nullability == NullabilityKind::NonNull;
2330
2331 return false;
2332}
2333
Ted Kremenek2bc73332014-01-17 06:24:43 +00002334static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002335 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002336 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002337 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002338 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002339 assert((FDecl || Proto) && "Need a function declaration or prototype");
2340
Ted Kremenek9aedc152014-01-17 06:24:56 +00002341 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002342 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002343 if (FDecl) {
2344 // Handle the nonnull attribute on the function/method declaration itself.
2345 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2346 if (!NonNull->args_size()) {
2347 // Easy case: all pointer arguments are nonnull.
2348 for (const auto *Arg : Args)
2349 if (S.isValidPointerAttrType(Arg->getType()))
2350 CheckNonNullArgument(S, Arg, CallSiteLoc);
2351 return;
2352 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002353
Douglas Gregorb4866e82015-06-19 18:13:19 +00002354 for (unsigned Val : NonNull->args()) {
2355 if (Val >= Args.size())
2356 continue;
2357 if (NonNullArgs.empty())
2358 NonNullArgs.resize(Args.size());
2359 NonNullArgs.set(Val);
2360 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002361 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002362 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002363
Douglas Gregorb4866e82015-06-19 18:13:19 +00002364 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2365 // Handle the nonnull attribute on the parameters of the
2366 // function/method.
2367 ArrayRef<ParmVarDecl*> parms;
2368 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2369 parms = FD->parameters();
2370 else
2371 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2372
2373 unsigned ParamIndex = 0;
2374 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2375 I != E; ++I, ++ParamIndex) {
2376 const ParmVarDecl *PVD = *I;
2377 if (PVD->hasAttr<NonNullAttr>() ||
2378 isNonNullType(S.Context, PVD->getType())) {
2379 if (NonNullArgs.empty())
2380 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002381
Douglas Gregorb4866e82015-06-19 18:13:19 +00002382 NonNullArgs.set(ParamIndex);
2383 }
2384 }
2385 } else {
2386 // If we have a non-function, non-method declaration but no
2387 // function prototype, try to dig out the function prototype.
2388 if (!Proto) {
2389 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2390 QualType type = VD->getType().getNonReferenceType();
2391 if (auto pointerType = type->getAs<PointerType>())
2392 type = pointerType->getPointeeType();
2393 else if (auto blockType = type->getAs<BlockPointerType>())
2394 type = blockType->getPointeeType();
2395 // FIXME: data member pointers?
2396
2397 // Dig out the function prototype, if there is one.
2398 Proto = type->getAs<FunctionProtoType>();
2399 }
2400 }
2401
2402 // Fill in non-null argument information from the nullability
2403 // information on the parameter types (if we have them).
2404 if (Proto) {
2405 unsigned Index = 0;
2406 for (auto paramType : Proto->getParamTypes()) {
2407 if (isNonNullType(S.Context, paramType)) {
2408 if (NonNullArgs.empty())
2409 NonNullArgs.resize(Args.size());
2410
2411 NonNullArgs.set(Index);
2412 }
2413
2414 ++Index;
2415 }
2416 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002417 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002418
Douglas Gregorb4866e82015-06-19 18:13:19 +00002419 // Check for non-null arguments.
2420 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2421 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002422 if (NonNullArgs[ArgIndex])
2423 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002424 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002425}
2426
Richard Smith55ce3522012-06-25 20:30:08 +00002427/// Handles the checks for format strings, non-POD arguments to vararg
2428/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002429void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2430 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00002431 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00002432 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002433 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002434 if (CurContext->isDependentContext())
2435 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002436
Ted Kremenekb8176da2010-09-09 04:33:05 +00002437 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002438 llvm::SmallBitVector CheckedVarArgs;
2439 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002440 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002441 // Only create vector if there are format attributes.
2442 CheckedVarArgs.resize(Args.size());
2443
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002444 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002445 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002446 }
Richard Smithd7293d72013-08-05 18:49:43 +00002447 }
Richard Smith55ce3522012-06-25 20:30:08 +00002448
2449 // Refuse POD arguments that weren't caught by the format string
2450 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00002451 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002452 unsigned NumParams = Proto ? Proto->getNumParams()
2453 : FDecl && isa<FunctionDecl>(FDecl)
2454 ? cast<FunctionDecl>(FDecl)->getNumParams()
2455 : FDecl && isa<ObjCMethodDecl>(FDecl)
2456 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2457 : 0;
2458
Alp Toker9cacbab2014-01-20 20:26:09 +00002459 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002460 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002461 if (const Expr *Arg = Args[ArgIdx]) {
2462 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2463 checkVariadicArgument(Arg, CallType);
2464 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002465 }
Richard Smithd7293d72013-08-05 18:49:43 +00002466 }
Mike Stump11289f42009-09-09 15:08:12 +00002467
Douglas Gregorb4866e82015-06-19 18:13:19 +00002468 if (FDecl || Proto) {
2469 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002470
Richard Trieu41bc0992013-06-22 00:20:41 +00002471 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002472 if (FDecl) {
2473 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2474 CheckArgumentWithTypeTag(I, Args.data());
2475 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002476 }
Richard Smith55ce3522012-06-25 20:30:08 +00002477}
2478
2479/// CheckConstructorCall - Check a constructor call for correctness and safety
2480/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002481void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2482 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002483 const FunctionProtoType *Proto,
2484 SourceLocation Loc) {
2485 VariadicCallType CallType =
2486 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002487 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
2488 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002489}
2490
2491/// CheckFunctionCall - Check a direct function call for various correctness
2492/// and safety properties not strictly enforced by the C type system.
2493bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2494 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002495 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2496 isa<CXXMethodDecl>(FDecl);
2497 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2498 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002499 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2500 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002501 Expr** Args = TheCall->getArgs();
2502 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00002503 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002504 // If this is a call to a member operator, hide the first argument
2505 // from checkCall.
2506 // FIXME: Our choice of AST representation here is less than ideal.
2507 ++Args;
2508 --NumArgs;
2509 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00002510 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002511 IsMemberFunction, TheCall->getRParenLoc(),
2512 TheCall->getCallee()->getSourceRange(), CallType);
2513
2514 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2515 // None of the checks below are needed for functions that don't have
2516 // simple names (e.g., C++ conversion functions).
2517 if (!FnInfo)
2518 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002519
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002520 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002521 if (getLangOpts().ObjC1)
2522 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002523
Anna Zaks22122702012-01-17 00:37:07 +00002524 unsigned CMId = FDecl->getMemoryFunctionKind();
2525 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002526 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002527
Anna Zaks201d4892012-01-13 21:52:01 +00002528 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002529 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002530 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002531 else if (CMId == Builtin::BIstrncat)
2532 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002533 else
Anna Zaks22122702012-01-17 00:37:07 +00002534 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002535
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002536 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002537}
2538
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002539bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002540 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002541 VariadicCallType CallType =
2542 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002543
Douglas Gregorb4866e82015-06-19 18:13:19 +00002544 checkCall(Method, nullptr, Args,
2545 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2546 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002547
2548 return false;
2549}
2550
Richard Trieu664c4c62013-06-20 21:03:13 +00002551bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2552 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002553 QualType Ty;
2554 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002555 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002556 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002557 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002558 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002559 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002560
Douglas Gregorb4866e82015-06-19 18:13:19 +00002561 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2562 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002563 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002564
Richard Trieu664c4c62013-06-20 21:03:13 +00002565 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002566 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002567 CallType = VariadicDoesNotApply;
2568 } else if (Ty->isBlockPointerType()) {
2569 CallType = VariadicBlock;
2570 } else { // Ty->isFunctionPointerType()
2571 CallType = VariadicFunction;
2572 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002573
Douglas Gregorb4866e82015-06-19 18:13:19 +00002574 checkCall(NDecl, Proto,
2575 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2576 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002577 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002578
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002579 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002580}
2581
Richard Trieu41bc0992013-06-22 00:20:41 +00002582/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2583/// such as function pointers returned from functions.
2584bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002585 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002586 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00002587 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002588 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002589 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002590 TheCall->getCallee()->getSourceRange(), CallType);
2591
2592 return false;
2593}
2594
Tim Northovere94a34c2014-03-11 10:49:14 +00002595static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002596 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002597 return false;
2598
JF Bastiendda2cb12016-04-18 18:01:49 +00002599 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002600 switch (Op) {
2601 case AtomicExpr::AO__c11_atomic_init:
2602 llvm_unreachable("There is no ordering argument for an init");
2603
2604 case AtomicExpr::AO__c11_atomic_load:
2605 case AtomicExpr::AO__atomic_load_n:
2606 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002607 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2608 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002609
2610 case AtomicExpr::AO__c11_atomic_store:
2611 case AtomicExpr::AO__atomic_store:
2612 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002613 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2614 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2615 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002616
2617 default:
2618 return true;
2619 }
2620}
2621
Richard Smithfeea8832012-04-12 05:08:17 +00002622ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2623 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002624 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2625 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002626
Richard Smithfeea8832012-04-12 05:08:17 +00002627 // All these operations take one of the following forms:
2628 enum {
2629 // C __c11_atomic_init(A *, C)
2630 Init,
2631 // C __c11_atomic_load(A *, int)
2632 Load,
2633 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002634 LoadCopy,
2635 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002636 Copy,
2637 // C __c11_atomic_add(A *, M, int)
2638 Arithmetic,
2639 // C __atomic_exchange_n(A *, CP, int)
2640 Xchg,
2641 // void __atomic_exchange(A *, C *, CP, int)
2642 GNUXchg,
2643 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2644 C11CmpXchg,
2645 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2646 GNUCmpXchg
2647 } Form = Init;
Eric Fiselier8d662442016-03-30 23:39:56 +00002648 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2649 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002650 // where:
2651 // C is an appropriate type,
2652 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2653 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2654 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2655 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002656
Gabor Horvath98bd0982015-03-16 09:59:54 +00002657 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2658 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2659 AtomicExpr::AO__atomic_load,
2660 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00002661 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2662 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2663 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2664 Op == AtomicExpr::AO__atomic_store_n ||
2665 Op == AtomicExpr::AO__atomic_exchange_n ||
2666 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2667 bool IsAddSub = false;
2668
2669 switch (Op) {
2670 case AtomicExpr::AO__c11_atomic_init:
2671 Form = Init;
2672 break;
2673
2674 case AtomicExpr::AO__c11_atomic_load:
2675 case AtomicExpr::AO__atomic_load_n:
2676 Form = Load;
2677 break;
2678
Richard Smithfeea8832012-04-12 05:08:17 +00002679 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002680 Form = LoadCopy;
2681 break;
2682
2683 case AtomicExpr::AO__c11_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002684 case AtomicExpr::AO__atomic_store:
2685 case AtomicExpr::AO__atomic_store_n:
2686 Form = Copy;
2687 break;
2688
2689 case AtomicExpr::AO__c11_atomic_fetch_add:
2690 case AtomicExpr::AO__c11_atomic_fetch_sub:
2691 case AtomicExpr::AO__atomic_fetch_add:
2692 case AtomicExpr::AO__atomic_fetch_sub:
2693 case AtomicExpr::AO__atomic_add_fetch:
2694 case AtomicExpr::AO__atomic_sub_fetch:
2695 IsAddSub = true;
2696 // Fall through.
2697 case AtomicExpr::AO__c11_atomic_fetch_and:
2698 case AtomicExpr::AO__c11_atomic_fetch_or:
2699 case AtomicExpr::AO__c11_atomic_fetch_xor:
2700 case AtomicExpr::AO__atomic_fetch_and:
2701 case AtomicExpr::AO__atomic_fetch_or:
2702 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00002703 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00002704 case AtomicExpr::AO__atomic_and_fetch:
2705 case AtomicExpr::AO__atomic_or_fetch:
2706 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00002707 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00002708 Form = Arithmetic;
2709 break;
2710
2711 case AtomicExpr::AO__c11_atomic_exchange:
2712 case AtomicExpr::AO__atomic_exchange_n:
2713 Form = Xchg;
2714 break;
2715
2716 case AtomicExpr::AO__atomic_exchange:
2717 Form = GNUXchg;
2718 break;
2719
2720 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2721 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2722 Form = C11CmpXchg;
2723 break;
2724
2725 case AtomicExpr::AO__atomic_compare_exchange:
2726 case AtomicExpr::AO__atomic_compare_exchange_n:
2727 Form = GNUCmpXchg;
2728 break;
2729 }
2730
2731 // Check we have the right number of arguments.
2732 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002733 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002734 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002735 << TheCall->getCallee()->getSourceRange();
2736 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00002737 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2738 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002739 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002740 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002741 << TheCall->getCallee()->getSourceRange();
2742 return ExprError();
2743 }
2744
Richard Smithfeea8832012-04-12 05:08:17 +00002745 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002746 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00002747 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2748 if (ConvertedPtr.isInvalid())
2749 return ExprError();
2750
2751 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002752 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2753 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00002754 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002755 << Ptr->getType() << Ptr->getSourceRange();
2756 return ExprError();
2757 }
2758
Richard Smithfeea8832012-04-12 05:08:17 +00002759 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2760 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2761 QualType ValType = AtomTy; // 'C'
2762 if (IsC11) {
2763 if (!AtomTy->isAtomicType()) {
2764 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2765 << Ptr->getType() << Ptr->getSourceRange();
2766 return ExprError();
2767 }
Richard Smithe00921a2012-09-15 06:09:58 +00002768 if (AtomTy.isConstQualified()) {
2769 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2770 << Ptr->getType() << Ptr->getSourceRange();
2771 return ExprError();
2772 }
Richard Smithfeea8832012-04-12 05:08:17 +00002773 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00002774 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002775 if (ValType.isConstQualified()) {
2776 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2777 << Ptr->getType() << Ptr->getSourceRange();
2778 return ExprError();
2779 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002780 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002781
Richard Smithfeea8832012-04-12 05:08:17 +00002782 // For an arithmetic operation, the implied arithmetic must be well-formed.
2783 if (Form == Arithmetic) {
2784 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2785 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2786 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2787 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2788 return ExprError();
2789 }
2790 if (!IsAddSub && !ValType->isIntegerType()) {
2791 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2792 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2793 return ExprError();
2794 }
David Majnemere85cff82015-01-28 05:48:06 +00002795 if (IsC11 && ValType->isPointerType() &&
2796 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2797 diag::err_incomplete_type)) {
2798 return ExprError();
2799 }
Richard Smithfeea8832012-04-12 05:08:17 +00002800 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2801 // For __atomic_*_n operations, the value type must be a scalar integral or
2802 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002803 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00002804 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2805 return ExprError();
2806 }
2807
Eli Friedmanaa769812013-09-11 03:49:34 +00002808 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2809 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00002810 // For GNU atomics, require a trivially-copyable type. This is not part of
2811 // the GNU atomics specification, but we enforce it for sanity.
2812 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002813 << Ptr->getType() << Ptr->getSourceRange();
2814 return ExprError();
2815 }
2816
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002817 switch (ValType.getObjCLifetime()) {
2818 case Qualifiers::OCL_None:
2819 case Qualifiers::OCL_ExplicitNone:
2820 // okay
2821 break;
2822
2823 case Qualifiers::OCL_Weak:
2824 case Qualifiers::OCL_Strong:
2825 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002826 // FIXME: Can this happen? By this point, ValType should be known
2827 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002828 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2829 << ValType << Ptr->getSourceRange();
2830 return ExprError();
2831 }
2832
David Majnemerc6eb6502015-06-03 00:26:35 +00002833 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2834 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00002835 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00002836 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00002837 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002838 QualType ResultType = ValType;
Eric Fiselier8d662442016-03-30 23:39:56 +00002839 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002840 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002841 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002842 ResultType = Context.BoolTy;
2843
Richard Smithfeea8832012-04-12 05:08:17 +00002844 // The type of a parameter passed 'by value'. In the GNU atomics, such
2845 // arguments are actually passed as pointers.
2846 QualType ByValType = ValType; // 'CP'
2847 if (!IsC11 && !IsN)
2848 ByValType = Ptr->getType();
2849
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002850 // The first argument --- the pointer --- has a fixed type; we
2851 // deduce the types of the rest of the arguments accordingly. Walk
2852 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002853 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002854 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002855 if (i < NumVals[Form] + 1) {
2856 switch (i) {
2857 case 1:
2858 // The second argument is the non-atomic operand. For arithmetic, this
2859 // is always passed by value, and for a compare_exchange it is always
2860 // passed by address. For the rest, GNU uses by-address and C11 uses
2861 // by-value.
2862 assert(Form != Load);
2863 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2864 Ty = ValType;
2865 else if (Form == Copy || Form == Xchg)
2866 Ty = ByValType;
2867 else if (Form == Arithmetic)
2868 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002869 else {
2870 Expr *ValArg = TheCall->getArg(i);
Alex Lorenz67522152016-11-23 16:57:03 +00002871 // Treat this argument as _Nonnull as we want to show a warning if
2872 // NULL is passed into it.
2873 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002874 unsigned AS = 0;
2875 // Keep address space of non-atomic pointer type.
2876 if (const PointerType *PtrTy =
2877 ValArg->getType()->getAs<PointerType>()) {
2878 AS = PtrTy->getPointeeType().getAddressSpace();
2879 }
2880 Ty = Context.getPointerType(
2881 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2882 }
Richard Smithfeea8832012-04-12 05:08:17 +00002883 break;
2884 case 2:
2885 // The third argument to compare_exchange / GNU exchange is a
2886 // (pointer to a) desired value.
2887 Ty = ByValType;
2888 break;
2889 case 3:
2890 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2891 Ty = Context.BoolTy;
2892 break;
2893 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002894 } else {
2895 // The order(s) are always converted to int.
2896 Ty = Context.IntTy;
2897 }
Richard Smithfeea8832012-04-12 05:08:17 +00002898
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002899 InitializedEntity Entity =
2900 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00002901 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002902 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2903 if (Arg.isInvalid())
2904 return true;
2905 TheCall->setArg(i, Arg.get());
2906 }
2907
Richard Smithfeea8832012-04-12 05:08:17 +00002908 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002909 SmallVector<Expr*, 5> SubExprs;
2910 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00002911 switch (Form) {
2912 case Init:
2913 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00002914 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002915 break;
2916 case Load:
2917 SubExprs.push_back(TheCall->getArg(1)); // Order
2918 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00002919 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00002920 case Copy:
2921 case Arithmetic:
2922 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002923 SubExprs.push_back(TheCall->getArg(2)); // Order
2924 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002925 break;
2926 case GNUXchg:
2927 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2928 SubExprs.push_back(TheCall->getArg(3)); // Order
2929 SubExprs.push_back(TheCall->getArg(1)); // Val1
2930 SubExprs.push_back(TheCall->getArg(2)); // Val2
2931 break;
2932 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002933 SubExprs.push_back(TheCall->getArg(3)); // Order
2934 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002935 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00002936 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00002937 break;
2938 case GNUCmpXchg:
2939 SubExprs.push_back(TheCall->getArg(4)); // Order
2940 SubExprs.push_back(TheCall->getArg(1)); // Val1
2941 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2942 SubExprs.push_back(TheCall->getArg(2)); // Val2
2943 SubExprs.push_back(TheCall->getArg(3)); // Weak
2944 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002945 }
Tim Northovere94a34c2014-03-11 10:49:14 +00002946
2947 if (SubExprs.size() >= 2 && Form != Init) {
2948 llvm::APSInt Result(32);
2949 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2950 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00002951 Diag(SubExprs[1]->getLocStart(),
2952 diag::warn_atomic_op_has_invalid_memory_order)
2953 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00002954 }
2955
Fariborz Jahanian615de762013-05-28 17:37:39 +00002956 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2957 SubExprs, ResultType, Op,
2958 TheCall->getRParenLoc());
2959
2960 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2961 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2962 Context.AtomicUsesUnsupportedLibcall(AE))
2963 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2964 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002965
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002966 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002967}
2968
John McCall29ad95b2011-08-27 01:09:30 +00002969/// checkBuiltinArgument - Given a call to a builtin function, perform
2970/// normal type-checking on the given argument, updating the call in
2971/// place. This is useful when a builtin function requires custom
2972/// type-checking for some of its arguments but not necessarily all of
2973/// them.
2974///
2975/// Returns true on error.
2976static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2977 FunctionDecl *Fn = E->getDirectCallee();
2978 assert(Fn && "builtin call without direct callee!");
2979
2980 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2981 InitializedEntity Entity =
2982 InitializedEntity::InitializeParameter(S.Context, Param);
2983
2984 ExprResult Arg = E->getArg(0);
2985 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2986 if (Arg.isInvalid())
2987 return true;
2988
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002989 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00002990 return false;
2991}
2992
Chris Lattnerdc046542009-05-08 06:58:22 +00002993/// SemaBuiltinAtomicOverloaded - We have a call to a function like
2994/// __sync_fetch_and_add, which is an overloaded function based on the pointer
2995/// type of its first argument. The main ActOnCallExpr routines have already
2996/// promoted the types of arguments because all of these calls are prototyped as
2997/// void(...).
2998///
2999/// This function goes through and does final semantic checking for these
3000/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003001ExprResult
3002Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003003 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003004 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3005 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3006
3007 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003008 if (TheCall->getNumArgs() < 1) {
3009 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3010 << 0 << 1 << TheCall->getNumArgs()
3011 << TheCall->getCallee()->getSourceRange();
3012 return ExprError();
3013 }
Mike Stump11289f42009-09-09 15:08:12 +00003014
Chris Lattnerdc046542009-05-08 06:58:22 +00003015 // Inspect the first argument of the atomic builtin. This should always be
3016 // a pointer type, whose element is an integral scalar or pointer type.
3017 // Because it is a pointer type, we don't have to worry about any implicit
3018 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003019 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003020 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003021 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3022 if (FirstArgResult.isInvalid())
3023 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003024 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003025 TheCall->setArg(0, FirstArg);
3026
John McCall31168b02011-06-15 23:02:42 +00003027 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3028 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003029 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3030 << FirstArg->getType() << FirstArg->getSourceRange();
3031 return ExprError();
3032 }
Mike Stump11289f42009-09-09 15:08:12 +00003033
John McCall31168b02011-06-15 23:02:42 +00003034 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003035 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003036 !ValType->isBlockPointerType()) {
3037 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3038 << FirstArg->getType() << FirstArg->getSourceRange();
3039 return ExprError();
3040 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003041
John McCall31168b02011-06-15 23:02:42 +00003042 switch (ValType.getObjCLifetime()) {
3043 case Qualifiers::OCL_None:
3044 case Qualifiers::OCL_ExplicitNone:
3045 // okay
3046 break;
3047
3048 case Qualifiers::OCL_Weak:
3049 case Qualifiers::OCL_Strong:
3050 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003051 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003052 << ValType << FirstArg->getSourceRange();
3053 return ExprError();
3054 }
3055
John McCallb50451a2011-10-05 07:41:44 +00003056 // Strip any qualifiers off ValType.
3057 ValType = ValType.getUnqualifiedType();
3058
Chandler Carruth3973af72010-07-18 20:54:12 +00003059 // The majority of builtins return a value, but a few have special return
3060 // types, so allow them to override appropriately below.
3061 QualType ResultType = ValType;
3062
Chris Lattnerdc046542009-05-08 06:58:22 +00003063 // We need to figure out which concrete builtin this maps onto. For example,
3064 // __sync_fetch_and_add with a 2 byte object turns into
3065 // __sync_fetch_and_add_2.
3066#define BUILTIN_ROW(x) \
3067 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3068 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003069
Chris Lattnerdc046542009-05-08 06:58:22 +00003070 static const unsigned BuiltinIndices[][5] = {
3071 BUILTIN_ROW(__sync_fetch_and_add),
3072 BUILTIN_ROW(__sync_fetch_and_sub),
3073 BUILTIN_ROW(__sync_fetch_and_or),
3074 BUILTIN_ROW(__sync_fetch_and_and),
3075 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003076 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003077
Chris Lattnerdc046542009-05-08 06:58:22 +00003078 BUILTIN_ROW(__sync_add_and_fetch),
3079 BUILTIN_ROW(__sync_sub_and_fetch),
3080 BUILTIN_ROW(__sync_and_and_fetch),
3081 BUILTIN_ROW(__sync_or_and_fetch),
3082 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003083 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003084
Chris Lattnerdc046542009-05-08 06:58:22 +00003085 BUILTIN_ROW(__sync_val_compare_and_swap),
3086 BUILTIN_ROW(__sync_bool_compare_and_swap),
3087 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003088 BUILTIN_ROW(__sync_lock_release),
3089 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003090 };
Mike Stump11289f42009-09-09 15:08:12 +00003091#undef BUILTIN_ROW
3092
Chris Lattnerdc046542009-05-08 06:58:22 +00003093 // Determine the index of the size.
3094 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003095 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003096 case 1: SizeIndex = 0; break;
3097 case 2: SizeIndex = 1; break;
3098 case 4: SizeIndex = 2; break;
3099 case 8: SizeIndex = 3; break;
3100 case 16: SizeIndex = 4; break;
3101 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003102 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3103 << FirstArg->getType() << FirstArg->getSourceRange();
3104 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003105 }
Mike Stump11289f42009-09-09 15:08:12 +00003106
Chris Lattnerdc046542009-05-08 06:58:22 +00003107 // Each of these builtins has one pointer argument, followed by some number of
3108 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3109 // that we ignore. Find out which row of BuiltinIndices to read from as well
3110 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003111 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003112 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003113 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003114 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003115 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003116 case Builtin::BI__sync_fetch_and_add:
3117 case Builtin::BI__sync_fetch_and_add_1:
3118 case Builtin::BI__sync_fetch_and_add_2:
3119 case Builtin::BI__sync_fetch_and_add_4:
3120 case Builtin::BI__sync_fetch_and_add_8:
3121 case Builtin::BI__sync_fetch_and_add_16:
3122 BuiltinIndex = 0;
3123 break;
3124
3125 case Builtin::BI__sync_fetch_and_sub:
3126 case Builtin::BI__sync_fetch_and_sub_1:
3127 case Builtin::BI__sync_fetch_and_sub_2:
3128 case Builtin::BI__sync_fetch_and_sub_4:
3129 case Builtin::BI__sync_fetch_and_sub_8:
3130 case Builtin::BI__sync_fetch_and_sub_16:
3131 BuiltinIndex = 1;
3132 break;
3133
3134 case Builtin::BI__sync_fetch_and_or:
3135 case Builtin::BI__sync_fetch_and_or_1:
3136 case Builtin::BI__sync_fetch_and_or_2:
3137 case Builtin::BI__sync_fetch_and_or_4:
3138 case Builtin::BI__sync_fetch_and_or_8:
3139 case Builtin::BI__sync_fetch_and_or_16:
3140 BuiltinIndex = 2;
3141 break;
3142
3143 case Builtin::BI__sync_fetch_and_and:
3144 case Builtin::BI__sync_fetch_and_and_1:
3145 case Builtin::BI__sync_fetch_and_and_2:
3146 case Builtin::BI__sync_fetch_and_and_4:
3147 case Builtin::BI__sync_fetch_and_and_8:
3148 case Builtin::BI__sync_fetch_and_and_16:
3149 BuiltinIndex = 3;
3150 break;
Mike Stump11289f42009-09-09 15:08:12 +00003151
Douglas Gregor73722482011-11-28 16:30:08 +00003152 case Builtin::BI__sync_fetch_and_xor:
3153 case Builtin::BI__sync_fetch_and_xor_1:
3154 case Builtin::BI__sync_fetch_and_xor_2:
3155 case Builtin::BI__sync_fetch_and_xor_4:
3156 case Builtin::BI__sync_fetch_and_xor_8:
3157 case Builtin::BI__sync_fetch_and_xor_16:
3158 BuiltinIndex = 4;
3159 break;
3160
Hal Finkeld2208b52014-10-02 20:53:50 +00003161 case Builtin::BI__sync_fetch_and_nand:
3162 case Builtin::BI__sync_fetch_and_nand_1:
3163 case Builtin::BI__sync_fetch_and_nand_2:
3164 case Builtin::BI__sync_fetch_and_nand_4:
3165 case Builtin::BI__sync_fetch_and_nand_8:
3166 case Builtin::BI__sync_fetch_and_nand_16:
3167 BuiltinIndex = 5;
3168 WarnAboutSemanticsChange = true;
3169 break;
3170
Douglas Gregor73722482011-11-28 16:30:08 +00003171 case Builtin::BI__sync_add_and_fetch:
3172 case Builtin::BI__sync_add_and_fetch_1:
3173 case Builtin::BI__sync_add_and_fetch_2:
3174 case Builtin::BI__sync_add_and_fetch_4:
3175 case Builtin::BI__sync_add_and_fetch_8:
3176 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003177 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003178 break;
3179
3180 case Builtin::BI__sync_sub_and_fetch:
3181 case Builtin::BI__sync_sub_and_fetch_1:
3182 case Builtin::BI__sync_sub_and_fetch_2:
3183 case Builtin::BI__sync_sub_and_fetch_4:
3184 case Builtin::BI__sync_sub_and_fetch_8:
3185 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003186 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003187 break;
3188
3189 case Builtin::BI__sync_and_and_fetch:
3190 case Builtin::BI__sync_and_and_fetch_1:
3191 case Builtin::BI__sync_and_and_fetch_2:
3192 case Builtin::BI__sync_and_and_fetch_4:
3193 case Builtin::BI__sync_and_and_fetch_8:
3194 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003195 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003196 break;
3197
3198 case Builtin::BI__sync_or_and_fetch:
3199 case Builtin::BI__sync_or_and_fetch_1:
3200 case Builtin::BI__sync_or_and_fetch_2:
3201 case Builtin::BI__sync_or_and_fetch_4:
3202 case Builtin::BI__sync_or_and_fetch_8:
3203 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003204 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003205 break;
3206
3207 case Builtin::BI__sync_xor_and_fetch:
3208 case Builtin::BI__sync_xor_and_fetch_1:
3209 case Builtin::BI__sync_xor_and_fetch_2:
3210 case Builtin::BI__sync_xor_and_fetch_4:
3211 case Builtin::BI__sync_xor_and_fetch_8:
3212 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003213 BuiltinIndex = 10;
3214 break;
3215
3216 case Builtin::BI__sync_nand_and_fetch:
3217 case Builtin::BI__sync_nand_and_fetch_1:
3218 case Builtin::BI__sync_nand_and_fetch_2:
3219 case Builtin::BI__sync_nand_and_fetch_4:
3220 case Builtin::BI__sync_nand_and_fetch_8:
3221 case Builtin::BI__sync_nand_and_fetch_16:
3222 BuiltinIndex = 11;
3223 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003224 break;
Mike Stump11289f42009-09-09 15:08:12 +00003225
Chris Lattnerdc046542009-05-08 06:58:22 +00003226 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003227 case Builtin::BI__sync_val_compare_and_swap_1:
3228 case Builtin::BI__sync_val_compare_and_swap_2:
3229 case Builtin::BI__sync_val_compare_and_swap_4:
3230 case Builtin::BI__sync_val_compare_and_swap_8:
3231 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003232 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003233 NumFixed = 2;
3234 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003235
Chris Lattnerdc046542009-05-08 06:58:22 +00003236 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003237 case Builtin::BI__sync_bool_compare_and_swap_1:
3238 case Builtin::BI__sync_bool_compare_and_swap_2:
3239 case Builtin::BI__sync_bool_compare_and_swap_4:
3240 case Builtin::BI__sync_bool_compare_and_swap_8:
3241 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003242 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003243 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003244 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003245 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003246
3247 case Builtin::BI__sync_lock_test_and_set:
3248 case Builtin::BI__sync_lock_test_and_set_1:
3249 case Builtin::BI__sync_lock_test_and_set_2:
3250 case Builtin::BI__sync_lock_test_and_set_4:
3251 case Builtin::BI__sync_lock_test_and_set_8:
3252 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003253 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003254 break;
3255
Chris Lattnerdc046542009-05-08 06:58:22 +00003256 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003257 case Builtin::BI__sync_lock_release_1:
3258 case Builtin::BI__sync_lock_release_2:
3259 case Builtin::BI__sync_lock_release_4:
3260 case Builtin::BI__sync_lock_release_8:
3261 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003262 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003263 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003264 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003265 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003266
3267 case Builtin::BI__sync_swap:
3268 case Builtin::BI__sync_swap_1:
3269 case Builtin::BI__sync_swap_2:
3270 case Builtin::BI__sync_swap_4:
3271 case Builtin::BI__sync_swap_8:
3272 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003273 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003274 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003275 }
Mike Stump11289f42009-09-09 15:08:12 +00003276
Chris Lattnerdc046542009-05-08 06:58:22 +00003277 // Now that we know how many fixed arguments we expect, first check that we
3278 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003279 if (TheCall->getNumArgs() < 1+NumFixed) {
3280 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3281 << 0 << 1+NumFixed << TheCall->getNumArgs()
3282 << TheCall->getCallee()->getSourceRange();
3283 return ExprError();
3284 }
Mike Stump11289f42009-09-09 15:08:12 +00003285
Hal Finkeld2208b52014-10-02 20:53:50 +00003286 if (WarnAboutSemanticsChange) {
3287 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3288 << TheCall->getCallee()->getSourceRange();
3289 }
3290
Chris Lattner5b9241b2009-05-08 15:36:58 +00003291 // Get the decl for the concrete builtin from this, we can tell what the
3292 // concrete integer type we should convert to is.
3293 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003294 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003295 FunctionDecl *NewBuiltinDecl;
3296 if (NewBuiltinID == BuiltinID)
3297 NewBuiltinDecl = FDecl;
3298 else {
3299 // Perform builtin lookup to avoid redeclaring it.
3300 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3301 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3302 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3303 assert(Res.getFoundDecl());
3304 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003305 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003306 return ExprError();
3307 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003308
John McCallcf142162010-08-07 06:22:56 +00003309 // The first argument --- the pointer --- has a fixed type; we
3310 // deduce the types of the rest of the arguments accordingly. Walk
3311 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003312 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003313 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003314
Chris Lattnerdc046542009-05-08 06:58:22 +00003315 // GCC does an implicit conversion to the pointer or integer ValType. This
3316 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003317 // Initialize the argument.
3318 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3319 ValType, /*consume*/ false);
3320 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003321 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003322 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003323
Chris Lattnerdc046542009-05-08 06:58:22 +00003324 // Okay, we have something that *can* be converted to the right type. Check
3325 // to see if there is a potentially weird extension going on here. This can
3326 // happen when you do an atomic operation on something like an char* and
3327 // pass in 42. The 42 gets converted to char. This is even more strange
3328 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003329 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003330 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003331 }
Mike Stump11289f42009-09-09 15:08:12 +00003332
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003333 ASTContext& Context = this->getASTContext();
3334
3335 // Create a new DeclRefExpr to refer to the new decl.
3336 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3337 Context,
3338 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003339 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003340 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003341 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003342 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003343 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003344 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003345
Chris Lattnerdc046542009-05-08 06:58:22 +00003346 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003347 // FIXME: This loses syntactic information.
3348 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3349 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3350 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003351 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003352
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003353 // Change the result type of the call to match the original value type. This
3354 // is arbitrary, but the codegen for these builtins ins design to handle it
3355 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003356 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003357
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003358 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003359}
3360
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003361/// SemaBuiltinNontemporalOverloaded - We have a call to
3362/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3363/// overloaded function based on the pointer type of its last argument.
3364///
3365/// This function goes through and does final semantic checking for these
3366/// builtins.
3367ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3368 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3369 DeclRefExpr *DRE =
3370 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3371 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3372 unsigned BuiltinID = FDecl->getBuiltinID();
3373 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3374 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3375 "Unexpected nontemporal load/store builtin!");
3376 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3377 unsigned numArgs = isStore ? 2 : 1;
3378
3379 // Ensure that we have the proper number of arguments.
3380 if (checkArgCount(*this, TheCall, numArgs))
3381 return ExprError();
3382
3383 // Inspect the last argument of the nontemporal builtin. This should always
3384 // be a pointer type, from which we imply the type of the memory access.
3385 // Because it is a pointer type, we don't have to worry about any implicit
3386 // casts here.
3387 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3388 ExprResult PointerArgResult =
3389 DefaultFunctionArrayLvalueConversion(PointerArg);
3390
3391 if (PointerArgResult.isInvalid())
3392 return ExprError();
3393 PointerArg = PointerArgResult.get();
3394 TheCall->setArg(numArgs - 1, PointerArg);
3395
3396 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3397 if (!pointerType) {
3398 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3399 << PointerArg->getType() << PointerArg->getSourceRange();
3400 return ExprError();
3401 }
3402
3403 QualType ValType = pointerType->getPointeeType();
3404
3405 // Strip any qualifiers off ValType.
3406 ValType = ValType.getUnqualifiedType();
3407 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3408 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3409 !ValType->isVectorType()) {
3410 Diag(DRE->getLocStart(),
3411 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3412 << PointerArg->getType() << PointerArg->getSourceRange();
3413 return ExprError();
3414 }
3415
3416 if (!isStore) {
3417 TheCall->setType(ValType);
3418 return TheCallResult;
3419 }
3420
3421 ExprResult ValArg = TheCall->getArg(0);
3422 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3423 Context, ValType, /*consume*/ false);
3424 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3425 if (ValArg.isInvalid())
3426 return ExprError();
3427
3428 TheCall->setArg(0, ValArg.get());
3429 TheCall->setType(Context.VoidTy);
3430 return TheCallResult;
3431}
3432
Chris Lattner6436fb62009-02-18 06:01:06 +00003433/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003434/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003435/// Note: It might also make sense to do the UTF-16 conversion here (would
3436/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003437bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003438 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003439 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3440
Douglas Gregorfb65e592011-07-27 05:40:30 +00003441 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003442 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3443 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003444 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003445 }
Mike Stump11289f42009-09-09 15:08:12 +00003446
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003447 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003448 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003449 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00003450 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3451 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3452 llvm::UTF16 *ToPtr = &ToBuf[0];
3453
3454 llvm::ConversionResult Result =
3455 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3456 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003457 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00003458 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003459 Diag(Arg->getLocStart(),
3460 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3461 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003462 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003463}
3464
Mehdi Amini06d367c2016-10-24 20:39:34 +00003465/// CheckObjCString - Checks that the format string argument to the os_log()
3466/// and os_trace() functions is correct, and converts it to const char *.
3467ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3468 Arg = Arg->IgnoreParenCasts();
3469 auto *Literal = dyn_cast<StringLiteral>(Arg);
3470 if (!Literal) {
3471 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3472 Literal = ObjcLiteral->getString();
3473 }
3474 }
3475
3476 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3477 return ExprError(
3478 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3479 << Arg->getSourceRange());
3480 }
3481
3482 ExprResult Result(Literal);
3483 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3484 InitializedEntity Entity =
3485 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3486 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3487 return Result;
3488}
3489
Charles Davisc7d5c942015-09-17 20:55:33 +00003490/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3491/// for validity. Emit an error and return true on failure; return false
3492/// on success.
3493bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003494 Expr *Fn = TheCall->getCallee();
3495 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003496 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003497 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003498 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3499 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003500 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003501 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003502 return true;
3503 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003504
3505 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003506 return Diag(TheCall->getLocEnd(),
3507 diag::err_typecheck_call_too_few_args_at_least)
3508 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003509 }
3510
John McCall29ad95b2011-08-27 01:09:30 +00003511 // Type-check the first argument normally.
3512 if (checkBuiltinArgument(*this, TheCall, 0))
3513 return true;
3514
Chris Lattnere202e6a2007-12-20 00:05:45 +00003515 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00003516 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00003517 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00003518 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00003519 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00003520 else if (FunctionDecl *FD = getCurFunctionDecl())
3521 isVariadic = FD->isVariadic();
3522 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00003523 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00003524
Chris Lattnere202e6a2007-12-20 00:05:45 +00003525 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003526 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3527 return true;
3528 }
Mike Stump11289f42009-09-09 15:08:12 +00003529
Chris Lattner43be2e62007-12-19 23:59:04 +00003530 // Verify that the second argument to the builtin is the last argument of the
3531 // current function or method.
3532 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003533 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003534
Nico Weber9eea7642013-05-24 23:31:57 +00003535 // These are valid if SecondArgIsLastNamedArgument is false after the next
3536 // block.
3537 QualType Type;
3538 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003539 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003540
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003541 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3542 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003543 // FIXME: This isn't correct for methods (results in bogus warning).
3544 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003545 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00003546 if (CurBlock)
David Majnemera3debed2016-06-24 05:33:44 +00003547 LastArg = CurBlock->TheDecl->parameters().back();
Steve Naroff439a3e42009-04-15 19:33:47 +00003548 else if (FunctionDecl *FD = getCurFunctionDecl())
David Majnemera3debed2016-06-24 05:33:44 +00003549 LastArg = FD->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003550 else
David Majnemera3debed2016-06-24 05:33:44 +00003551 LastArg = getCurMethodDecl()->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003552 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00003553
3554 Type = PV->getType();
3555 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003556 IsCRegister =
3557 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003558 }
3559 }
Mike Stump11289f42009-09-09 15:08:12 +00003560
Chris Lattner43be2e62007-12-19 23:59:04 +00003561 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003562 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003563 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003564 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00003565 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3566 // Promotable integers are UB, but enumerations need a bit of
3567 // extra checking to see what their promotable type actually is.
3568 if (!Type->isPromotableIntegerType())
3569 return false;
3570 if (!Type->isEnumeralType())
3571 return true;
3572 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3573 return !(ED &&
3574 Context.typesAreCompatible(ED->getPromotionType(), Type));
3575 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00003576 unsigned Reason = 0;
3577 if (Type->isReferenceType()) Reason = 1;
3578 else if (IsCRegister) Reason = 2;
3579 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003580 Diag(ParamLoc, diag::note_parameter_type) << Type;
3581 }
3582
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003583 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003584 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003585}
Chris Lattner43be2e62007-12-19 23:59:04 +00003586
Charles Davisc7d5c942015-09-17 20:55:33 +00003587/// Check the arguments to '__builtin_va_start' for validity, and that
3588/// it was called from a function of the native ABI.
3589/// Emit an error and return true on failure; return false on success.
3590bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3591 // On x86-64 Unix, don't allow this in Win64 ABI functions.
3592 // On x64 Windows, don't allow this in System V ABI functions.
3593 // (Yes, that means there's no corresponding way to support variadic
3594 // System V ABI functions on Windows.)
3595 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3596 unsigned OS = Context.getTargetInfo().getTriple().getOS();
3597 clang::CallingConv CC = CC_C;
3598 if (const FunctionDecl *FD = getCurFunctionDecl())
3599 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3600 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3601 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3602 return Diag(TheCall->getCallee()->getLocStart(),
3603 diag::err_va_start_used_in_wrong_abi_function)
3604 << (OS != llvm::Triple::Win32);
3605 }
3606 return SemaBuiltinVAStartImpl(TheCall);
3607}
3608
3609/// Check the arguments to '__builtin_ms_va_start' for validity, and that
3610/// it was called from a Win64 ABI function.
3611/// Emit an error and return true on failure; return false on success.
3612bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3613 // This only makes sense for x86-64.
3614 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3615 Expr *Callee = TheCall->getCallee();
3616 if (TT.getArch() != llvm::Triple::x86_64)
3617 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3618 // Don't allow this in System V ABI functions.
3619 clang::CallingConv CC = CC_C;
3620 if (const FunctionDecl *FD = getCurFunctionDecl())
3621 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3622 if (CC == CC_X86_64SysV ||
3623 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3624 return Diag(Callee->getLocStart(),
3625 diag::err_ms_va_start_used_in_sysv_function);
3626 return SemaBuiltinVAStartImpl(TheCall);
3627}
3628
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003629bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3630 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3631 // const char *named_addr);
3632
3633 Expr *Func = Call->getCallee();
3634
3635 if (Call->getNumArgs() < 3)
3636 return Diag(Call->getLocEnd(),
3637 diag::err_typecheck_call_too_few_args_at_least)
3638 << 0 /*function call*/ << 3 << Call->getNumArgs();
3639
3640 // Determine whether the current function is variadic or not.
3641 bool IsVariadic;
3642 if (BlockScopeInfo *CurBlock = getCurBlock())
3643 IsVariadic = CurBlock->TheDecl->isVariadic();
3644 else if (FunctionDecl *FD = getCurFunctionDecl())
3645 IsVariadic = FD->isVariadic();
3646 else if (ObjCMethodDecl *MD = getCurMethodDecl())
3647 IsVariadic = MD->isVariadic();
3648 else
3649 llvm_unreachable("unexpected statement type");
3650
3651 if (!IsVariadic) {
3652 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3653 return true;
3654 }
3655
3656 // Type-check the first argument normally.
3657 if (checkBuiltinArgument(*this, Call, 0))
3658 return true;
3659
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003660 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003661 unsigned ArgNo;
3662 QualType Type;
3663 } ArgumentTypes[] = {
3664 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3665 { 2, Context.getSizeType() },
3666 };
3667
3668 for (const auto &AT : ArgumentTypes) {
3669 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3670 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3671 continue;
3672 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3673 << Arg->getType() << AT.Type << 1 /* different class */
3674 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3675 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3676 }
3677
3678 return false;
3679}
3680
Chris Lattner2da14fb2007-12-20 00:26:33 +00003681/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3682/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003683bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3684 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003685 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003686 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003687 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003688 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003689 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003690 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003691 << SourceRange(TheCall->getArg(2)->getLocStart(),
3692 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003693
John Wiegley01296292011-04-08 18:41:53 +00003694 ExprResult OrigArg0 = TheCall->getArg(0);
3695 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003696
Chris Lattner2da14fb2007-12-20 00:26:33 +00003697 // Do standard promotions between the two arguments, returning their common
3698 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003699 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003700 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3701 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003702
3703 // Make sure any conversions are pushed back into the call; this is
3704 // type safe since unordered compare builtins are declared as "_Bool
3705 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003706 TheCall->setArg(0, OrigArg0.get());
3707 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003708
John Wiegley01296292011-04-08 18:41:53 +00003709 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003710 return false;
3711
Chris Lattner2da14fb2007-12-20 00:26:33 +00003712 // If the common type isn't a real floating type, then the arguments were
3713 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003714 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00003715 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003716 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00003717 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3718 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003719
Chris Lattner2da14fb2007-12-20 00:26:33 +00003720 return false;
3721}
3722
Benjamin Kramer634fc102010-02-15 22:42:31 +00003723/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3724/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00003725/// to check everything. We expect the last argument to be a floating point
3726/// value.
3727bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3728 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00003729 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003730 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00003731 if (TheCall->getNumArgs() > NumArgs)
3732 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003733 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003734 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00003735 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003736 (*(TheCall->arg_end()-1))->getLocEnd());
3737
Benjamin Kramer64aae502010-02-16 10:07:31 +00003738 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00003739
Eli Friedman7e4faac2009-08-31 20:06:00 +00003740 if (OrigArg->isTypeDependent())
3741 return false;
3742
Chris Lattner68784ef2010-05-06 05:50:07 +00003743 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00003744 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00003745 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003746 diag::err_typecheck_call_invalid_unary_fp)
3747 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003748
Chris Lattner68784ef2010-05-06 05:50:07 +00003749 // If this is an implicit conversion from float -> double, remove it.
3750 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3751 Expr *CastArg = Cast->getSubExpr();
3752 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3753 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
3754 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00003755 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00003756 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00003757 }
3758 }
3759
Eli Friedman7e4faac2009-08-31 20:06:00 +00003760 return false;
3761}
3762
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003763/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3764// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00003765ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00003766 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003767 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00003768 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00003769 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3770 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003771
Nate Begemana0110022010-06-08 00:16:34 +00003772 // Determine which of the following types of shufflevector we're checking:
3773 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00003774 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00003775 QualType resType = TheCall->getArg(0)->getType();
3776 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00003777
Douglas Gregorc25f7662009-05-19 22:10:17 +00003778 if (!TheCall->getArg(0)->isTypeDependent() &&
3779 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00003780 QualType LHSType = TheCall->getArg(0)->getType();
3781 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00003782
Craig Topperbaca3892013-07-29 06:47:04 +00003783 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3784 return ExprError(Diag(TheCall->getLocStart(),
3785 diag::err_shufflevector_non_vector)
3786 << SourceRange(TheCall->getArg(0)->getLocStart(),
3787 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003788
Nate Begemana0110022010-06-08 00:16:34 +00003789 numElements = LHSType->getAs<VectorType>()->getNumElements();
3790 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00003791
Nate Begemana0110022010-06-08 00:16:34 +00003792 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3793 // with mask. If so, verify that RHS is an integer vector type with the
3794 // same number of elts as lhs.
3795 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00003796 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00003797 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00003798 return ExprError(Diag(TheCall->getLocStart(),
3799 diag::err_shufflevector_incompatible_vector)
3800 << SourceRange(TheCall->getArg(1)->getLocStart(),
3801 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003802 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00003803 return ExprError(Diag(TheCall->getLocStart(),
3804 diag::err_shufflevector_incompatible_vector)
3805 << SourceRange(TheCall->getArg(0)->getLocStart(),
3806 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00003807 } else if (numElements != numResElements) {
3808 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00003809 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003810 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003811 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003812 }
3813
3814 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00003815 if (TheCall->getArg(i)->isTypeDependent() ||
3816 TheCall->getArg(i)->isValueDependent())
3817 continue;
3818
Nate Begemana0110022010-06-08 00:16:34 +00003819 llvm::APSInt Result(32);
3820 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3821 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003822 diag::err_shufflevector_nonconstant_argument)
3823 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003824
Craig Topper50ad5b72013-08-03 17:40:38 +00003825 // Allow -1 which will be translated to undef in the IR.
3826 if (Result.isSigned() && Result.isAllOnesValue())
3827 continue;
3828
Chris Lattner7ab824e2008-08-10 02:05:13 +00003829 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003830 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003831 diag::err_shufflevector_argument_too_large)
3832 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003833 }
3834
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003835 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003836
Chris Lattner7ab824e2008-08-10 02:05:13 +00003837 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003838 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00003839 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003840 }
3841
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003842 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3843 TheCall->getCallee()->getLocStart(),
3844 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003845}
Chris Lattner43be2e62007-12-19 23:59:04 +00003846
Hal Finkelc4d7c822013-09-18 03:29:45 +00003847/// SemaConvertVectorExpr - Handle __builtin_convertvector
3848ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3849 SourceLocation BuiltinLoc,
3850 SourceLocation RParenLoc) {
3851 ExprValueKind VK = VK_RValue;
3852 ExprObjectKind OK = OK_Ordinary;
3853 QualType DstTy = TInfo->getType();
3854 QualType SrcTy = E->getType();
3855
3856 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3857 return ExprError(Diag(BuiltinLoc,
3858 diag::err_convertvector_non_vector)
3859 << E->getSourceRange());
3860 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3861 return ExprError(Diag(BuiltinLoc,
3862 diag::err_convertvector_non_vector_type));
3863
3864 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3865 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3866 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3867 if (SrcElts != DstElts)
3868 return ExprError(Diag(BuiltinLoc,
3869 diag::err_convertvector_incompatible_vector)
3870 << E->getSourceRange());
3871 }
3872
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003873 return new (Context)
3874 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003875}
3876
Daniel Dunbarb7257262008-07-21 22:59:13 +00003877/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3878// This is declared to take (const void*, ...) and can take two
3879// optional constant int args.
3880bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003881 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003882
Chris Lattner3b054132008-11-19 05:08:23 +00003883 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003884 return Diag(TheCall->getLocEnd(),
3885 diag::err_typecheck_call_too_many_args_at_most)
3886 << 0 /*function call*/ << 3 << NumArgs
3887 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003888
3889 // Argument 0 is checked for us and the remaining arguments must be
3890 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003891 for (unsigned i = 1; i != NumArgs; ++i)
3892 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003893 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003894
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003895 return false;
3896}
3897
Hal Finkelf0417332014-07-17 14:25:55 +00003898/// SemaBuiltinAssume - Handle __assume (MS Extension).
3899// __assume does not evaluate its arguments, and should warn if its argument
3900// has side effects.
3901bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3902 Expr *Arg = TheCall->getArg(0);
3903 if (Arg->isInstantiationDependent()) return false;
3904
3905 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003906 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003907 << Arg->getSourceRange()
3908 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3909
3910 return false;
3911}
3912
David Majnemer86b1bfa2016-10-31 18:07:57 +00003913/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00003914/// as (size_t, size_t) where the second size_t must be a power of 2 greater
3915/// than 8.
3916bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
3917 // The alignment must be a constant integer.
3918 Expr *Arg = TheCall->getArg(1);
3919
3920 // We can't check the value of a dependent argument.
3921 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00003922 if (const auto *UE =
3923 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
3924 if (UE->getKind() == UETT_AlignOf)
3925 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
3926 << Arg->getSourceRange();
3927
David Majnemer51169932016-10-31 05:37:48 +00003928 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
3929
3930 if (!Result.isPowerOf2())
3931 return Diag(TheCall->getLocStart(),
3932 diag::err_alignment_not_power_of_two)
3933 << Arg->getSourceRange();
3934
3935 if (Result < Context.getCharWidth())
3936 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
3937 << (unsigned)Context.getCharWidth()
3938 << Arg->getSourceRange();
3939
3940 if (Result > INT32_MAX)
3941 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
3942 << INT32_MAX
3943 << Arg->getSourceRange();
3944 }
3945
3946 return false;
3947}
3948
3949/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00003950/// as (const void*, size_t, ...) and can take one optional constant int arg.
3951bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3952 unsigned NumArgs = TheCall->getNumArgs();
3953
3954 if (NumArgs > 3)
3955 return Diag(TheCall->getLocEnd(),
3956 diag::err_typecheck_call_too_many_args_at_most)
3957 << 0 /*function call*/ << 3 << NumArgs
3958 << TheCall->getSourceRange();
3959
3960 // The alignment must be a constant integer.
3961 Expr *Arg = TheCall->getArg(1);
3962
3963 // We can't check the value of a dependent argument.
3964 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3965 llvm::APSInt Result;
3966 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3967 return true;
3968
3969 if (!Result.isPowerOf2())
3970 return Diag(TheCall->getLocStart(),
3971 diag::err_alignment_not_power_of_two)
3972 << Arg->getSourceRange();
3973 }
3974
3975 if (NumArgs > 2) {
3976 ExprResult Arg(TheCall->getArg(2));
3977 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3978 Context.getSizeType(), false);
3979 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3980 if (Arg.isInvalid()) return true;
3981 TheCall->setArg(2, Arg.get());
3982 }
Hal Finkelf0417332014-07-17 14:25:55 +00003983
3984 return false;
3985}
3986
Mehdi Amini06d367c2016-10-24 20:39:34 +00003987bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
3988 unsigned BuiltinID =
3989 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
3990 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
3991
3992 unsigned NumArgs = TheCall->getNumArgs();
3993 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
3994 if (NumArgs < NumRequiredArgs) {
3995 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3996 << 0 /* function call */ << NumRequiredArgs << NumArgs
3997 << TheCall->getSourceRange();
3998 }
3999 if (NumArgs >= NumRequiredArgs + 0x100) {
4000 return Diag(TheCall->getLocEnd(),
4001 diag::err_typecheck_call_too_many_args_at_most)
4002 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4003 << TheCall->getSourceRange();
4004 }
4005 unsigned i = 0;
4006
4007 // For formatting call, check buffer arg.
4008 if (!IsSizeCall) {
4009 ExprResult Arg(TheCall->getArg(i));
4010 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4011 Context, Context.VoidPtrTy, false);
4012 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4013 if (Arg.isInvalid())
4014 return true;
4015 TheCall->setArg(i, Arg.get());
4016 i++;
4017 }
4018
4019 // Check string literal arg.
4020 unsigned FormatIdx = i;
4021 {
4022 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4023 if (Arg.isInvalid())
4024 return true;
4025 TheCall->setArg(i, Arg.get());
4026 i++;
4027 }
4028
4029 // Make sure variadic args are scalar.
4030 unsigned FirstDataArg = i;
4031 while (i < NumArgs) {
4032 ExprResult Arg = DefaultVariadicArgumentPromotion(
4033 TheCall->getArg(i), VariadicFunction, nullptr);
4034 if (Arg.isInvalid())
4035 return true;
4036 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4037 if (ArgSize.getQuantity() >= 0x100) {
4038 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4039 << i << (int)ArgSize.getQuantity() << 0xff
4040 << TheCall->getSourceRange();
4041 }
4042 TheCall->setArg(i, Arg.get());
4043 i++;
4044 }
4045
4046 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4047 // call to avoid duplicate diagnostics.
4048 if (!IsSizeCall) {
4049 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4050 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4051 bool Success = CheckFormatArguments(
4052 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4053 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4054 CheckedVarArgs);
4055 if (!Success)
4056 return true;
4057 }
4058
4059 if (IsSizeCall) {
4060 TheCall->setType(Context.getSizeType());
4061 } else {
4062 TheCall->setType(Context.VoidPtrTy);
4063 }
4064 return false;
4065}
4066
Eric Christopher8d0c6212010-04-17 02:26:23 +00004067/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4068/// TheCall is a constant expression.
4069bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4070 llvm::APSInt &Result) {
4071 Expr *Arg = TheCall->getArg(ArgNum);
4072 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4073 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4074
4075 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4076
4077 if (!Arg->isIntegerConstantExpr(Result, Context))
4078 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004079 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004080
Chris Lattnerd545ad12009-09-23 06:06:36 +00004081 return false;
4082}
4083
Richard Sandiford28940af2014-04-16 08:47:51 +00004084/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4085/// TheCall is a constant expression in the range [Low, High].
4086bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4087 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004088 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004089
4090 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004091 Expr *Arg = TheCall->getArg(ArgNum);
4092 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004093 return false;
4094
Eric Christopher8d0c6212010-04-17 02:26:23 +00004095 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004096 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004097 return true;
4098
Richard Sandiford28940af2014-04-16 08:47:51 +00004099 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004100 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004101 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004102
4103 return false;
4104}
4105
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004106/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4107/// TheCall is a constant expression is a multiple of Num..
4108bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4109 unsigned Num) {
4110 llvm::APSInt Result;
4111
4112 // We can't check the value of a dependent argument.
4113 Expr *Arg = TheCall->getArg(ArgNum);
4114 if (Arg->isTypeDependent() || Arg->isValueDependent())
4115 return false;
4116
4117 // Check constant-ness first.
4118 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4119 return true;
4120
4121 if (Result.getSExtValue() % Num != 0)
4122 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4123 << Num << Arg->getSourceRange();
4124
4125 return false;
4126}
4127
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004128/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4129/// TheCall is an ARM/AArch64 special register string literal.
4130bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4131 int ArgNum, unsigned ExpectedFieldNum,
4132 bool AllowName) {
4133 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4134 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4135 BuiltinID == ARM::BI__builtin_arm_rsr ||
4136 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4137 BuiltinID == ARM::BI__builtin_arm_wsr ||
4138 BuiltinID == ARM::BI__builtin_arm_wsrp;
4139 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4140 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4141 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4142 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4143 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4144 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4145 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4146
4147 // We can't check the value of a dependent argument.
4148 Expr *Arg = TheCall->getArg(ArgNum);
4149 if (Arg->isTypeDependent() || Arg->isValueDependent())
4150 return false;
4151
4152 // Check if the argument is a string literal.
4153 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4154 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4155 << Arg->getSourceRange();
4156
4157 // Check the type of special register given.
4158 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4159 SmallVector<StringRef, 6> Fields;
4160 Reg.split(Fields, ":");
4161
4162 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4163 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4164 << Arg->getSourceRange();
4165
4166 // If the string is the name of a register then we cannot check that it is
4167 // valid here but if the string is of one the forms described in ACLE then we
4168 // can check that the supplied fields are integers and within the valid
4169 // ranges.
4170 if (Fields.size() > 1) {
4171 bool FiveFields = Fields.size() == 5;
4172
4173 bool ValidString = true;
4174 if (IsARMBuiltin) {
4175 ValidString &= Fields[0].startswith_lower("cp") ||
4176 Fields[0].startswith_lower("p");
4177 if (ValidString)
4178 Fields[0] =
4179 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4180
4181 ValidString &= Fields[2].startswith_lower("c");
4182 if (ValidString)
4183 Fields[2] = Fields[2].drop_front(1);
4184
4185 if (FiveFields) {
4186 ValidString &= Fields[3].startswith_lower("c");
4187 if (ValidString)
4188 Fields[3] = Fields[3].drop_front(1);
4189 }
4190 }
4191
4192 SmallVector<int, 5> Ranges;
4193 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00004194 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004195 else
4196 Ranges.append({15, 7, 15});
4197
4198 for (unsigned i=0; i<Fields.size(); ++i) {
4199 int IntField;
4200 ValidString &= !Fields[i].getAsInteger(10, IntField);
4201 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4202 }
4203
4204 if (!ValidString)
4205 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4206 << Arg->getSourceRange();
4207
4208 } else if (IsAArch64Builtin && Fields.size() == 1) {
4209 // If the register name is one of those that appear in the condition below
4210 // and the special register builtin being used is one of the write builtins,
4211 // then we require that the argument provided for writing to the register
4212 // is an integer constant expression. This is because it will be lowered to
4213 // an MSR (immediate) instruction, so we need to know the immediate at
4214 // compile time.
4215 if (TheCall->getNumArgs() != 2)
4216 return false;
4217
4218 std::string RegLower = Reg.lower();
4219 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4220 RegLower != "pan" && RegLower != "uao")
4221 return false;
4222
4223 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4224 }
4225
4226 return false;
4227}
4228
Eli Friedmanc97d0142009-05-03 06:04:26 +00004229/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004230/// This checks that the target supports __builtin_longjmp and
4231/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004232bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004233 if (!Context.getTargetInfo().hasSjLjLowering())
4234 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4235 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4236
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004237 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004238 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004239
Eric Christopher8d0c6212010-04-17 02:26:23 +00004240 // TODO: This is less than ideal. Overload this to take a value.
4241 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4242 return true;
4243
4244 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004245 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4246 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4247
4248 return false;
4249}
4250
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004251/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4252/// This checks that the target supports __builtin_setjmp.
4253bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4254 if (!Context.getTargetInfo().hasSjLjLowering())
4255 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4256 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4257 return false;
4258}
4259
Richard Smithd7293d72013-08-05 18:49:43 +00004260namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004261class UncoveredArgHandler {
4262 enum { Unknown = -1, AllCovered = -2 };
4263 signed FirstUncoveredArg;
4264 SmallVector<const Expr *, 4> DiagnosticExprs;
4265
4266public:
4267 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4268
4269 bool hasUncoveredArg() const {
4270 return (FirstUncoveredArg >= 0);
4271 }
4272
4273 unsigned getUncoveredArg() const {
4274 assert(hasUncoveredArg() && "no uncovered argument");
4275 return FirstUncoveredArg;
4276 }
4277
4278 void setAllCovered() {
4279 // A string has been found with all arguments covered, so clear out
4280 // the diagnostics.
4281 DiagnosticExprs.clear();
4282 FirstUncoveredArg = AllCovered;
4283 }
4284
4285 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4286 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4287
4288 // Don't update if a previous string covers all arguments.
4289 if (FirstUncoveredArg == AllCovered)
4290 return;
4291
4292 // UncoveredArgHandler tracks the highest uncovered argument index
4293 // and with it all the strings that match this index.
4294 if (NewFirstUncoveredArg == FirstUncoveredArg)
4295 DiagnosticExprs.push_back(StrExpr);
4296 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4297 DiagnosticExprs.clear();
4298 DiagnosticExprs.push_back(StrExpr);
4299 FirstUncoveredArg = NewFirstUncoveredArg;
4300 }
4301 }
4302
4303 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4304};
4305
Richard Smithd7293d72013-08-05 18:49:43 +00004306enum StringLiteralCheckType {
4307 SLCT_NotALiteral,
4308 SLCT_UncheckedLiteral,
4309 SLCT_CheckedLiteral
4310};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004311} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00004312
Stephen Hines648c3692016-09-16 01:07:04 +00004313static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4314 BinaryOperatorKind BinOpKind,
4315 bool AddendIsRight) {
4316 unsigned BitWidth = Offset.getBitWidth();
4317 unsigned AddendBitWidth = Addend.getBitWidth();
4318 // There might be negative interim results.
4319 if (Addend.isUnsigned()) {
4320 Addend = Addend.zext(++AddendBitWidth);
4321 Addend.setIsSigned(true);
4322 }
4323 // Adjust the bit width of the APSInts.
4324 if (AddendBitWidth > BitWidth) {
4325 Offset = Offset.sext(AddendBitWidth);
4326 BitWidth = AddendBitWidth;
4327 } else if (BitWidth > AddendBitWidth) {
4328 Addend = Addend.sext(BitWidth);
4329 }
4330
4331 bool Ov = false;
4332 llvm::APSInt ResOffset = Offset;
4333 if (BinOpKind == BO_Add)
4334 ResOffset = Offset.sadd_ov(Addend, Ov);
4335 else {
4336 assert(AddendIsRight && BinOpKind == BO_Sub &&
4337 "operator must be add or sub with addend on the right");
4338 ResOffset = Offset.ssub_ov(Addend, Ov);
4339 }
4340
4341 // We add an offset to a pointer here so we should support an offset as big as
4342 // possible.
4343 if (Ov) {
4344 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00004345 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00004346 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4347 return;
4348 }
4349
4350 Offset = ResOffset;
4351}
4352
4353namespace {
4354// This is a wrapper class around StringLiteral to support offsetted string
4355// literals as format strings. It takes the offset into account when returning
4356// the string and its length or the source locations to display notes correctly.
4357class FormatStringLiteral {
4358 const StringLiteral *FExpr;
4359 int64_t Offset;
4360
4361 public:
4362 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4363 : FExpr(fexpr), Offset(Offset) {}
4364
4365 StringRef getString() const {
4366 return FExpr->getString().drop_front(Offset);
4367 }
4368
4369 unsigned getByteLength() const {
4370 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4371 }
4372 unsigned getLength() const { return FExpr->getLength() - Offset; }
4373 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4374
4375 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4376
4377 QualType getType() const { return FExpr->getType(); }
4378
4379 bool isAscii() const { return FExpr->isAscii(); }
4380 bool isWide() const { return FExpr->isWide(); }
4381 bool isUTF8() const { return FExpr->isUTF8(); }
4382 bool isUTF16() const { return FExpr->isUTF16(); }
4383 bool isUTF32() const { return FExpr->isUTF32(); }
4384 bool isPascal() const { return FExpr->isPascal(); }
4385
4386 SourceLocation getLocationOfByte(
4387 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4388 const TargetInfo &Target, unsigned *StartToken = nullptr,
4389 unsigned *StartTokenByteOffset = nullptr) const {
4390 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4391 StartToken, StartTokenByteOffset);
4392 }
4393
4394 SourceLocation getLocStart() const LLVM_READONLY {
4395 return FExpr->getLocStart().getLocWithOffset(Offset);
4396 }
4397 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4398};
4399} // end anonymous namespace
4400
4401static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004402 const Expr *OrigFormatExpr,
4403 ArrayRef<const Expr *> Args,
4404 bool HasVAListArg, unsigned format_idx,
4405 unsigned firstDataArg,
4406 Sema::FormatStringType Type,
4407 bool inFunctionCall,
4408 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004409 llvm::SmallBitVector &CheckedVarArgs,
4410 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004411
Richard Smith55ce3522012-06-25 20:30:08 +00004412// Determine if an expression is a string literal or constant string.
4413// If this function returns false on the arguments to a function expecting a
4414// format string, we will usually need to emit a warning.
4415// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00004416static StringLiteralCheckType
4417checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4418 bool HasVAListArg, unsigned format_idx,
4419 unsigned firstDataArg, Sema::FormatStringType Type,
4420 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004421 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004422 UncoveredArgHandler &UncoveredArg,
4423 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00004424 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00004425 assert(Offset.isSigned() && "invalid offset");
4426
Douglas Gregorc25f7662009-05-19 22:10:17 +00004427 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00004428 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004429
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004430 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00004431
Richard Smithd7293d72013-08-05 18:49:43 +00004432 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00004433 // Technically -Wformat-nonliteral does not warn about this case.
4434 // The behavior of printf and friends in this case is implementation
4435 // dependent. Ideally if the format string cannot be null then
4436 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00004437 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00004438
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004439 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00004440 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004441 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00004442 // The expression is a literal if both sub-expressions were, and it was
4443 // completely checked only if both sub-expressions were checked.
4444 const AbstractConditionalOperator *C =
4445 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004446
4447 // Determine whether it is necessary to check both sub-expressions, for
4448 // example, because the condition expression is a constant that can be
4449 // evaluated at compile time.
4450 bool CheckLeft = true, CheckRight = true;
4451
4452 bool Cond;
4453 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4454 if (Cond)
4455 CheckRight = false;
4456 else
4457 CheckLeft = false;
4458 }
4459
Stephen Hines648c3692016-09-16 01:07:04 +00004460 // We need to maintain the offsets for the right and the left hand side
4461 // separately to check if every possible indexed expression is a valid
4462 // string literal. They might have different offsets for different string
4463 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004464 StringLiteralCheckType Left;
4465 if (!CheckLeft)
4466 Left = SLCT_UncheckedLiteral;
4467 else {
4468 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4469 HasVAListArg, format_idx, firstDataArg,
4470 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004471 CheckedVarArgs, UncoveredArg, Offset);
4472 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004473 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004474 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004475 }
4476
Richard Smith55ce3522012-06-25 20:30:08 +00004477 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004478 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004479 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004480 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004481 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004482
4483 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004484 }
4485
4486 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00004487 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4488 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004489 }
4490
John McCallc07a0c72011-02-17 10:25:35 +00004491 case Stmt::OpaqueValueExprClass:
4492 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4493 E = src;
4494 goto tryAgain;
4495 }
Richard Smith55ce3522012-06-25 20:30:08 +00004496 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004497
Ted Kremeneka8890832011-02-24 23:03:04 +00004498 case Stmt::PredefinedExprClass:
4499 // While __func__, etc., are technically not string literals, they
4500 // cannot contain format specifiers and thus are not a security
4501 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004502 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004503
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004504 case Stmt::DeclRefExprClass: {
4505 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004506
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004507 // As an exception, do not flag errors for variables binding to
4508 // const string literals.
4509 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4510 bool isConstant = false;
4511 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004512
Richard Smithd7293d72013-08-05 18:49:43 +00004513 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4514 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004515 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004516 isConstant = T.isConstant(S.Context) &&
4517 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004518 } else if (T->isObjCObjectPointerType()) {
4519 // In ObjC, there is usually no "const ObjectPointer" type,
4520 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004521 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004522 }
Mike Stump11289f42009-09-09 15:08:12 +00004523
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004524 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004525 if (const Expr *Init = VD->getAnyInitializer()) {
4526 // Look through initializers like const char c[] = { "foo" }
4527 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4528 if (InitList->isStringLiteralInit())
4529 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4530 }
Richard Smithd7293d72013-08-05 18:49:43 +00004531 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004532 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004533 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004534 /*InFunctionCall*/ false, CheckedVarArgs,
4535 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004536 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004537 }
Mike Stump11289f42009-09-09 15:08:12 +00004538
Anders Carlssonb012ca92009-06-28 19:55:58 +00004539 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4540 // special check to see if the format string is a function parameter
4541 // of the function calling the printf function. If the function
4542 // has an attribute indicating it is a printf-like function, then we
4543 // should suppress warnings concerning non-literals being used in a call
4544 // to a vprintf function. For example:
4545 //
4546 // void
4547 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4548 // va_list ap;
4549 // va_start(ap, fmt);
4550 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4551 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00004552 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004553 if (HasVAListArg) {
4554 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4555 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4556 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004557 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004558 // adjust for implicit parameter
4559 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4560 if (MD->isInstance())
4561 ++PVIndex;
4562 // We also check if the formats are compatible.
4563 // We can't pass a 'scanf' string to a 'printf' function.
4564 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00004565 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00004566 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004567 }
4568 }
4569 }
4570 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004571 }
Mike Stump11289f42009-09-09 15:08:12 +00004572
Richard Smith55ce3522012-06-25 20:30:08 +00004573 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004574 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004575
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004576 case Stmt::CallExprClass:
4577 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004578 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004579 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4580 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4581 unsigned ArgIndex = FA->getFormatIdx();
4582 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4583 if (MD->isInstance())
4584 --ArgIndex;
4585 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00004586
Richard Smithd7293d72013-08-05 18:49:43 +00004587 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004588 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00004589 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004590 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004591 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4592 unsigned BuiltinID = FD->getBuiltinID();
4593 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4594 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4595 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00004596 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004597 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004598 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004599 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004600 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004601 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004602 }
4603 }
Mike Stump11289f42009-09-09 15:08:12 +00004604
Richard Smith55ce3522012-06-25 20:30:08 +00004605 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004606 }
Alex Lorenzd9007142016-10-24 09:42:34 +00004607 case Stmt::ObjCMessageExprClass: {
4608 const auto *ME = cast<ObjCMessageExpr>(E);
4609 if (const auto *ND = ME->getMethodDecl()) {
4610 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4611 unsigned ArgIndex = FA->getFormatIdx();
4612 const Expr *Arg = ME->getArg(ArgIndex - 1);
4613 return checkFormatStringExpr(
4614 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4615 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4616 }
4617 }
4618
4619 return SLCT_NotALiteral;
4620 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004621 case Stmt::ObjCStringLiteralClass:
4622 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00004623 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004624
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004625 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004626 StrE = ObjCFExpr->getString();
4627 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004628 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004629
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004630 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00004631 if (Offset.isNegative() || Offset > StrE->getLength()) {
4632 // TODO: It would be better to have an explicit warning for out of
4633 // bounds literals.
4634 return SLCT_NotALiteral;
4635 }
4636 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4637 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004638 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004639 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00004640 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004641 }
Mike Stump11289f42009-09-09 15:08:12 +00004642
Richard Smith55ce3522012-06-25 20:30:08 +00004643 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004644 }
Stephen Hines648c3692016-09-16 01:07:04 +00004645 case Stmt::BinaryOperatorClass: {
4646 llvm::APSInt LResult;
4647 llvm::APSInt RResult;
4648
4649 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4650
4651 // A string literal + an int offset is still a string literal.
4652 if (BinOp->isAdditiveOp()) {
4653 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4654 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4655
4656 if (LIsInt != RIsInt) {
4657 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4658
4659 if (LIsInt) {
4660 if (BinOpKind == BO_Add) {
4661 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4662 E = BinOp->getRHS();
4663 goto tryAgain;
4664 }
4665 } else {
4666 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4667 E = BinOp->getLHS();
4668 goto tryAgain;
4669 }
4670 }
Stephen Hines648c3692016-09-16 01:07:04 +00004671 }
George Burgess IVd273aab2016-09-22 00:00:26 +00004672
4673 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00004674 }
4675 case Stmt::UnaryOperatorClass: {
4676 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4677 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4678 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4679 llvm::APSInt IndexResult;
4680 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4681 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4682 E = ASE->getBase();
4683 goto tryAgain;
4684 }
4685 }
4686
4687 return SLCT_NotALiteral;
4688 }
Mike Stump11289f42009-09-09 15:08:12 +00004689
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004690 default:
Richard Smith55ce3522012-06-25 20:30:08 +00004691 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004692 }
4693}
4694
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004695Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00004696 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00004697 .Case("scanf", FST_Scanf)
4698 .Cases("printf", "printf0", FST_Printf)
4699 .Cases("NSString", "CFString", FST_NSString)
4700 .Case("strftime", FST_Strftime)
4701 .Case("strfmon", FST_Strfmon)
4702 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4703 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4704 .Case("os_trace", FST_OSLog)
4705 .Case("os_log", FST_OSLog)
4706 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004707}
4708
Jordan Rose3e0ec582012-07-19 18:10:23 +00004709/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00004710/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00004711/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004712bool Sema::CheckFormatArguments(const FormatAttr *Format,
4713 ArrayRef<const Expr *> Args,
4714 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004715 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004716 SourceLocation Loc, SourceRange Range,
4717 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00004718 FormatStringInfo FSI;
4719 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004720 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00004721 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00004722 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00004723 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004724}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00004725
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004726bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004727 bool HasVAListArg, unsigned format_idx,
4728 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004729 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004730 SourceLocation Loc, SourceRange Range,
4731 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004732 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004733 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004734 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00004735 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004736 }
Mike Stump11289f42009-09-09 15:08:12 +00004737
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004738 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004739
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004740 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00004741 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004742 // Dynamically generated format strings are difficult to
4743 // automatically vet at compile time. Requiring that format strings
4744 // are string literals: (1) permits the checking of format strings by
4745 // the compiler and thereby (2) can practically remove the source of
4746 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00004747
Mike Stump11289f42009-09-09 15:08:12 +00004748 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00004749 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00004750 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00004751 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004752 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00004753 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00004754 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4755 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004756 /*IsFunctionCall*/ true, CheckedVarArgs,
4757 UncoveredArg,
4758 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004759
4760 // Generate a diagnostic where an uncovered argument is detected.
4761 if (UncoveredArg.hasUncoveredArg()) {
4762 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4763 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4764 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4765 }
4766
Richard Smith55ce3522012-06-25 20:30:08 +00004767 if (CT != SLCT_NotALiteral)
4768 // Literal format string found, check done!
4769 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00004770
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004771 // Strftime is particular as it always uses a single 'time' argument,
4772 // so it is safe to pass a non-literal string.
4773 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00004774 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004775
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004776 // Do not emit diag when the string param is a macro expansion and the
4777 // format is either NSString or CFString. This is a hack to prevent
4778 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4779 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004780 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4781 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00004782 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004783
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004784 // If there are no arguments specified, warn with -Wformat-security, otherwise
4785 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004786 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00004787 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4788 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004789 switch (Type) {
4790 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004791 break;
4792 case FST_Kprintf:
4793 case FST_FreeBSDKPrintf:
4794 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00004795 Diag(FormatLoc, diag::note_format_security_fixit)
4796 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004797 break;
4798 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00004799 Diag(FormatLoc, diag::note_format_security_fixit)
4800 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004801 break;
4802 }
4803 } else {
4804 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004805 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004806 }
Richard Smith55ce3522012-06-25 20:30:08 +00004807 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004808}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004809
Ted Kremenekab278de2010-01-28 23:39:18 +00004810namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00004811class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4812protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00004813 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00004814 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00004815 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00004816 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00004817 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00004818 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00004819 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00004820 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004821 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00004822 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00004823 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00004824 bool usesPositionalArgs;
4825 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004826 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00004827 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00004828 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004829 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004830
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004831public:
Stephen Hines648c3692016-09-16 01:07:04 +00004832 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00004833 const Expr *origFormatExpr,
4834 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004835 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00004836 ArrayRef<const Expr *> Args, unsigned formatIdx,
4837 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004838 llvm::SmallBitVector &CheckedVarArgs,
4839 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00004840 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
4841 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
4842 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
4843 usesPositionalArgs(false), atFirstArg(true),
4844 inFunctionCall(inFunctionCall), CallType(callType),
4845 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00004846 CoveredArgs.resize(numDataArgs);
4847 CoveredArgs.reset();
4848 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004849
Ted Kremenek019d2242010-01-29 01:50:07 +00004850 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004851
Ted Kremenek02087932010-07-16 02:11:22 +00004852 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004853 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004854
Jordan Rose92303592012-09-08 04:00:03 +00004855 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004856 const analyze_format_string::FormatSpecifier &FS,
4857 const analyze_format_string::ConversionSpecifier &CS,
4858 const char *startSpecifier, unsigned specifierLen,
4859 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00004860
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004861 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004862 const analyze_format_string::FormatSpecifier &FS,
4863 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004864
4865 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004866 const analyze_format_string::ConversionSpecifier &CS,
4867 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004868
Craig Toppere14c0f82014-03-12 04:55:44 +00004869 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004870
Craig Toppere14c0f82014-03-12 04:55:44 +00004871 void HandleInvalidPosition(const char *startSpecifier,
4872 unsigned specifierLen,
4873 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004874
Craig Toppere14c0f82014-03-12 04:55:44 +00004875 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004876
Craig Toppere14c0f82014-03-12 04:55:44 +00004877 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004878
Richard Trieu03cf7b72011-10-28 00:41:25 +00004879 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00004880 static void
4881 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4882 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4883 bool IsStringLocation, Range StringRange,
4884 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004885
Ted Kremenek02087932010-07-16 02:11:22 +00004886protected:
Ted Kremenekce815422010-07-19 21:25:57 +00004887 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4888 const char *startSpec,
4889 unsigned specifierLen,
4890 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004891
4892 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4893 const char *startSpec,
4894 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00004895
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004896 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00004897 CharSourceRange getSpecifierRange(const char *startSpecifier,
4898 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00004899 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004900
Ted Kremenek5739de72010-01-29 01:06:55 +00004901 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004902
4903 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4904 const analyze_format_string::ConversionSpecifier &CS,
4905 const char *startSpecifier, unsigned specifierLen,
4906 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004907
4908 template <typename Range>
4909 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4910 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004911 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00004912};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004913} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004914
Ted Kremenek02087932010-07-16 02:11:22 +00004915SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00004916 return OrigFormatExpr->getSourceRange();
4917}
4918
Ted Kremenek02087932010-07-16 02:11:22 +00004919CharSourceRange CheckFormatHandler::
4920getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00004921 SourceLocation Start = getLocationOfByte(startSpecifier);
4922 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
4923
4924 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004925 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00004926
4927 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004928}
4929
Ted Kremenek02087932010-07-16 02:11:22 +00004930SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00004931 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
4932 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00004933}
4934
Ted Kremenek02087932010-07-16 02:11:22 +00004935void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4936 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00004937 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4938 getLocationOfByte(startSpecifier),
4939 /*IsStringLocation*/true,
4940 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00004941}
4942
Jordan Rose92303592012-09-08 04:00:03 +00004943void CheckFormatHandler::HandleInvalidLengthModifier(
4944 const analyze_format_string::FormatSpecifier &FS,
4945 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00004946 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00004947 using namespace analyze_format_string;
4948
4949 const LengthModifier &LM = FS.getLengthModifier();
4950 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4951
4952 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004953 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00004954 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004955 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004956 getLocationOfByte(LM.getStart()),
4957 /*IsStringLocation*/true,
4958 getSpecifierRange(startSpecifier, specifierLen));
4959
4960 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4961 << FixedLM->toString()
4962 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4963
4964 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004965 FixItHint Hint;
4966 if (DiagID == diag::warn_format_nonsensical_length)
4967 Hint = FixItHint::CreateRemoval(LMRange);
4968
4969 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004970 getLocationOfByte(LM.getStart()),
4971 /*IsStringLocation*/true,
4972 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00004973 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00004974 }
4975}
4976
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004977void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00004978 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004979 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004980 using namespace analyze_format_string;
4981
4982 const LengthModifier &LM = FS.getLengthModifier();
4983 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4984
4985 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004986 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00004987 if (FixedLM) {
4988 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4989 << LM.toString() << 0,
4990 getLocationOfByte(LM.getStart()),
4991 /*IsStringLocation*/true,
4992 getSpecifierRange(startSpecifier, specifierLen));
4993
4994 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4995 << FixedLM->toString()
4996 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4997
4998 } else {
4999 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5000 << LM.toString() << 0,
5001 getLocationOfByte(LM.getStart()),
5002 /*IsStringLocation*/true,
5003 getSpecifierRange(startSpecifier, specifierLen));
5004 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005005}
5006
5007void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5008 const analyze_format_string::ConversionSpecifier &CS,
5009 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005010 using namespace analyze_format_string;
5011
5012 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005013 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005014 if (FixedCS) {
5015 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5016 << CS.toString() << /*conversion specifier*/1,
5017 getLocationOfByte(CS.getStart()),
5018 /*IsStringLocation*/true,
5019 getSpecifierRange(startSpecifier, specifierLen));
5020
5021 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5022 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5023 << FixedCS->toString()
5024 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5025 } else {
5026 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5027 << CS.toString() << /*conversion specifier*/1,
5028 getLocationOfByte(CS.getStart()),
5029 /*IsStringLocation*/true,
5030 getSpecifierRange(startSpecifier, specifierLen));
5031 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005032}
5033
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005034void CheckFormatHandler::HandlePosition(const char *startPos,
5035 unsigned posLen) {
5036 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5037 getLocationOfByte(startPos),
5038 /*IsStringLocation*/true,
5039 getSpecifierRange(startPos, posLen));
5040}
5041
Ted Kremenekd1668192010-02-27 01:41:03 +00005042void
Ted Kremenek02087932010-07-16 02:11:22 +00005043CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5044 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005045 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5046 << (unsigned) p,
5047 getLocationOfByte(startPos), /*IsStringLocation*/true,
5048 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005049}
5050
Ted Kremenek02087932010-07-16 02:11:22 +00005051void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005052 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005053 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5054 getLocationOfByte(startPos),
5055 /*IsStringLocation*/true,
5056 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005057}
5058
Ted Kremenek02087932010-07-16 02:11:22 +00005059void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005060 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005061 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005062 EmitFormatDiagnostic(
5063 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5064 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5065 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005066 }
Ted Kremenek02087932010-07-16 02:11:22 +00005067}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005068
Jordan Rose58bbe422012-07-19 18:10:08 +00005069// Note that this may return NULL if there was an error parsing or building
5070// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005071const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005072 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005073}
5074
5075void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005076 // Does the number of data arguments exceed the number of
5077 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005078 if (!HasVAListArg) {
5079 // Find any arguments that weren't covered.
5080 CoveredArgs.flip();
5081 signed notCoveredArg = CoveredArgs.find_first();
5082 if (notCoveredArg >= 0) {
5083 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005084 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5085 } else {
5086 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005087 }
5088 }
5089}
5090
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005091void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5092 const Expr *ArgExpr) {
5093 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5094 "Invalid state");
5095
5096 if (!ArgExpr)
5097 return;
5098
5099 SourceLocation Loc = ArgExpr->getLocStart();
5100
5101 if (S.getSourceManager().isInSystemMacro(Loc))
5102 return;
5103
5104 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5105 for (auto E : DiagnosticExprs)
5106 PDiag << E->getSourceRange();
5107
5108 CheckFormatHandler::EmitFormatDiagnostic(
5109 S, IsFunctionCall, DiagnosticExprs[0],
5110 PDiag, Loc, /*IsStringLocation*/false,
5111 DiagnosticExprs[0]->getSourceRange());
5112}
5113
Ted Kremenekce815422010-07-19 21:25:57 +00005114bool
5115CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5116 SourceLocation Loc,
5117 const char *startSpec,
5118 unsigned specifierLen,
5119 const char *csStart,
5120 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005121 bool keepGoing = true;
5122 if (argIndex < NumDataArgs) {
5123 // Consider the argument coverered, even though the specifier doesn't
5124 // make sense.
5125 CoveredArgs.set(argIndex);
5126 }
5127 else {
5128 // If argIndex exceeds the number of data arguments we
5129 // don't issue a warning because that is just a cascade of warnings (and
5130 // they may have intended '%%' anyway). We don't want to continue processing
5131 // the format string after this point, however, as we will like just get
5132 // gibberish when trying to match arguments.
5133 keepGoing = false;
5134 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005135
5136 StringRef Specifier(csStart, csLen);
5137
5138 // If the specifier in non-printable, it could be the first byte of a UTF-8
5139 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5140 // hex value.
5141 std::string CodePointStr;
5142 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005143 llvm::UTF32 CodePoint;
5144 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5145 const llvm::UTF8 *E =
5146 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5147 llvm::ConversionResult Result =
5148 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005149
Justin Lebar90910552016-09-30 00:38:45 +00005150 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005151 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005152 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005153 }
5154
5155 llvm::raw_string_ostream OS(CodePointStr);
5156 if (CodePoint < 256)
5157 OS << "\\x" << llvm::format("%02x", CodePoint);
5158 else if (CodePoint <= 0xFFFF)
5159 OS << "\\u" << llvm::format("%04x", CodePoint);
5160 else
5161 OS << "\\U" << llvm::format("%08x", CodePoint);
5162 OS.flush();
5163 Specifier = CodePointStr;
5164 }
5165
5166 EmitFormatDiagnostic(
5167 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5168 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5169
Ted Kremenekce815422010-07-19 21:25:57 +00005170 return keepGoing;
5171}
5172
Richard Trieu03cf7b72011-10-28 00:41:25 +00005173void
5174CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5175 const char *startSpec,
5176 unsigned specifierLen) {
5177 EmitFormatDiagnostic(
5178 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5179 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5180}
5181
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005182bool
5183CheckFormatHandler::CheckNumArgs(
5184 const analyze_format_string::FormatSpecifier &FS,
5185 const analyze_format_string::ConversionSpecifier &CS,
5186 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5187
5188 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005189 PartialDiagnostic PDiag = FS.usesPositionalArg()
5190 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5191 << (argIndex+1) << NumDataArgs)
5192 : S.PDiag(diag::warn_printf_insufficient_data_args);
5193 EmitFormatDiagnostic(
5194 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5195 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005196
5197 // Since more arguments than conversion tokens are given, by extension
5198 // all arguments are covered, so mark this as so.
5199 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005200 return false;
5201 }
5202 return true;
5203}
5204
Richard Trieu03cf7b72011-10-28 00:41:25 +00005205template<typename Range>
5206void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5207 SourceLocation Loc,
5208 bool IsStringLocation,
5209 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005210 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005211 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005212 Loc, IsStringLocation, StringRange, FixIt);
5213}
5214
5215/// \brief If the format string is not within the funcion call, emit a note
5216/// so that the function call and string are in diagnostic messages.
5217///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005218/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005219/// call and only one diagnostic message will be produced. Otherwise, an
5220/// extra note will be emitted pointing to location of the format string.
5221///
5222/// \param ArgumentExpr the expression that is passed as the format string
5223/// argument in the function call. Used for getting locations when two
5224/// diagnostics are emitted.
5225///
5226/// \param PDiag the callee should already have provided any strings for the
5227/// diagnostic message. This function only adds locations and fixits
5228/// to diagnostics.
5229///
5230/// \param Loc primary location for diagnostic. If two diagnostics are
5231/// required, one will be at Loc and a new SourceLocation will be created for
5232/// the other one.
5233///
5234/// \param IsStringLocation if true, Loc points to the format string should be
5235/// used for the note. Otherwise, Loc points to the argument list and will
5236/// be used with PDiag.
5237///
5238/// \param StringRange some or all of the string to highlight. This is
5239/// templated so it can accept either a CharSourceRange or a SourceRange.
5240///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005241/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005242template <typename Range>
5243void CheckFormatHandler::EmitFormatDiagnostic(
5244 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5245 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5246 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005247 if (InFunctionCall) {
5248 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5249 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005250 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00005251 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005252 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5253 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00005254
5255 const Sema::SemaDiagnosticBuilder &Note =
5256 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5257 diag::note_format_string_defined);
5258
5259 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005260 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005261 }
5262}
5263
Ted Kremenek02087932010-07-16 02:11:22 +00005264//===--- CHECK: Printf format string checking ------------------------------===//
5265
5266namespace {
5267class CheckPrintfHandler : public CheckFormatHandler {
5268public:
Stephen Hines648c3692016-09-16 01:07:04 +00005269 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005270 const Expr *origFormatExpr,
5271 const Sema::FormatStringType type, unsigned firstDataArg,
5272 unsigned numDataArgs, bool isObjC, const char *beg,
5273 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005274 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005275 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005276 llvm::SmallBitVector &CheckedVarArgs,
5277 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005278 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5279 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5280 inFunctionCall, CallType, CheckedVarArgs,
5281 UncoveredArg) {}
5282
5283 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5284
5285 /// Returns true if '%@' specifiers are allowed in the format string.
5286 bool allowsObjCArg() const {
5287 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5288 FSType == Sema::FST_OSTrace;
5289 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00005290
Ted Kremenek02087932010-07-16 02:11:22 +00005291 bool HandleInvalidPrintfConversionSpecifier(
5292 const analyze_printf::PrintfSpecifier &FS,
5293 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005294 unsigned specifierLen) override;
5295
Ted Kremenek02087932010-07-16 02:11:22 +00005296 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5297 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005298 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005299 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5300 const char *StartSpecifier,
5301 unsigned SpecifierLen,
5302 const Expr *E);
5303
Ted Kremenek02087932010-07-16 02:11:22 +00005304 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5305 const char *startSpecifier, unsigned specifierLen);
5306 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5307 const analyze_printf::OptionalAmount &Amt,
5308 unsigned type,
5309 const char *startSpecifier, unsigned specifierLen);
5310 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5311 const analyze_printf::OptionalFlag &flag,
5312 const char *startSpecifier, unsigned specifierLen);
5313 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5314 const analyze_printf::OptionalFlag &ignoredFlag,
5315 const analyze_printf::OptionalFlag &flag,
5316 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005317 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00005318 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00005319
5320 void HandleEmptyObjCModifierFlag(const char *startFlag,
5321 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005322
Ted Kremenek2b417712015-07-02 05:39:16 +00005323 void HandleInvalidObjCModifierFlag(const char *startFlag,
5324 unsigned flagLen) override;
5325
5326 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5327 const char *flagsEnd,
5328 const char *conversionPosition)
5329 override;
5330};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005331} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00005332
5333bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5334 const analyze_printf::PrintfSpecifier &FS,
5335 const char *startSpecifier,
5336 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005337 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005338 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005339
Ted Kremenekce815422010-07-19 21:25:57 +00005340 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5341 getLocationOfByte(CS.getStart()),
5342 startSpecifier, specifierLen,
5343 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00005344}
5345
Ted Kremenek02087932010-07-16 02:11:22 +00005346bool CheckPrintfHandler::HandleAmount(
5347 const analyze_format_string::OptionalAmount &Amt,
5348 unsigned k, const char *startSpecifier,
5349 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005350 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005351 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00005352 unsigned argIndex = Amt.getArgIndex();
5353 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005354 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5355 << k,
5356 getLocationOfByte(Amt.getStart()),
5357 /*IsStringLocation*/true,
5358 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005359 // Don't do any more checking. We will just emit
5360 // spurious errors.
5361 return false;
5362 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005363
Ted Kremenek5739de72010-01-29 01:06:55 +00005364 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00005365 // Although not in conformance with C99, we also allow the argument to be
5366 // an 'unsigned int' as that is a reasonably safe case. GCC also
5367 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00005368 CoveredArgs.set(argIndex);
5369 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005370 if (!Arg)
5371 return false;
5372
Ted Kremenek5739de72010-01-29 01:06:55 +00005373 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005374
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005375 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5376 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005377
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005378 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005379 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005380 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00005381 << T << Arg->getSourceRange(),
5382 getLocationOfByte(Amt.getStart()),
5383 /*IsStringLocation*/true,
5384 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005385 // Don't do any more checking. We will just emit
5386 // spurious errors.
5387 return false;
5388 }
5389 }
5390 }
5391 return true;
5392}
Ted Kremenek5739de72010-01-29 01:06:55 +00005393
Tom Careb49ec692010-06-17 19:00:27 +00005394void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00005395 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005396 const analyze_printf::OptionalAmount &Amt,
5397 unsigned type,
5398 const char *startSpecifier,
5399 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005400 const analyze_printf::PrintfConversionSpecifier &CS =
5401 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00005402
Richard Trieu03cf7b72011-10-28 00:41:25 +00005403 FixItHint fixit =
5404 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5405 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5406 Amt.getConstantLength()))
5407 : FixItHint();
5408
5409 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5410 << type << CS.toString(),
5411 getLocationOfByte(Amt.getStart()),
5412 /*IsStringLocation*/true,
5413 getSpecifierRange(startSpecifier, specifierLen),
5414 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00005415}
5416
Ted Kremenek02087932010-07-16 02:11:22 +00005417void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005418 const analyze_printf::OptionalFlag &flag,
5419 const char *startSpecifier,
5420 unsigned specifierLen) {
5421 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005422 const analyze_printf::PrintfConversionSpecifier &CS =
5423 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00005424 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5425 << flag.toString() << CS.toString(),
5426 getLocationOfByte(flag.getPosition()),
5427 /*IsStringLocation*/true,
5428 getSpecifierRange(startSpecifier, specifierLen),
5429 FixItHint::CreateRemoval(
5430 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005431}
5432
5433void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00005434 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005435 const analyze_printf::OptionalFlag &ignoredFlag,
5436 const analyze_printf::OptionalFlag &flag,
5437 const char *startSpecifier,
5438 unsigned specifierLen) {
5439 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005440 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5441 << ignoredFlag.toString() << flag.toString(),
5442 getLocationOfByte(ignoredFlag.getPosition()),
5443 /*IsStringLocation*/true,
5444 getSpecifierRange(startSpecifier, specifierLen),
5445 FixItHint::CreateRemoval(
5446 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005447}
5448
Ted Kremenek2b417712015-07-02 05:39:16 +00005449// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5450// bool IsStringLocation, Range StringRange,
5451// ArrayRef<FixItHint> Fixit = None);
5452
5453void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5454 unsigned flagLen) {
5455 // Warn about an empty flag.
5456 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5457 getLocationOfByte(startFlag),
5458 /*IsStringLocation*/true,
5459 getSpecifierRange(startFlag, flagLen));
5460}
5461
5462void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5463 unsigned flagLen) {
5464 // Warn about an invalid flag.
5465 auto Range = getSpecifierRange(startFlag, flagLen);
5466 StringRef flag(startFlag, flagLen);
5467 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5468 getLocationOfByte(startFlag),
5469 /*IsStringLocation*/true,
5470 Range, FixItHint::CreateRemoval(Range));
5471}
5472
5473void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5474 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5475 // Warn about using '[...]' without a '@' conversion.
5476 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5477 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5478 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5479 getLocationOfByte(conversionPosition),
5480 /*IsStringLocation*/true,
5481 Range, FixItHint::CreateRemoval(Range));
5482}
5483
Richard Smith55ce3522012-06-25 20:30:08 +00005484// Determines if the specified is a C++ class or struct containing
5485// a member with the specified name and kind (e.g. a CXXMethodDecl named
5486// "c_str()").
5487template<typename MemberKind>
5488static llvm::SmallPtrSet<MemberKind*, 1>
5489CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5490 const RecordType *RT = Ty->getAs<RecordType>();
5491 llvm::SmallPtrSet<MemberKind*, 1> Results;
5492
5493 if (!RT)
5494 return Results;
5495 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005496 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005497 return Results;
5498
Alp Tokerb6cc5922014-05-03 03:45:55 +00005499 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005500 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005501 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005502
5503 // We just need to include all members of the right kind turned up by the
5504 // filter, at this point.
5505 if (S.LookupQualifiedName(R, RT->getDecl()))
5506 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5507 NamedDecl *decl = (*I)->getUnderlyingDecl();
5508 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5509 Results.insert(FK);
5510 }
5511 return Results;
5512}
5513
Richard Smith2868a732014-02-28 01:36:39 +00005514/// Check if we could call '.c_str()' on an object.
5515///
5516/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5517/// allow the call, or if it would be ambiguous).
5518bool Sema::hasCStrMethod(const Expr *E) {
5519 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5520 MethodSet Results =
5521 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5522 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5523 MI != ME; ++MI)
5524 if ((*MI)->getMinRequiredArguments() == 0)
5525 return true;
5526 return false;
5527}
5528
Richard Smith55ce3522012-06-25 20:30:08 +00005529// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005530// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00005531// Returns true when a c_str() conversion method is found.
5532bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00005533 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00005534 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5535
5536 MethodSet Results =
5537 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5538
5539 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5540 MI != ME; ++MI) {
5541 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00005542 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00005543 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00005544 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00005545 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00005546 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5547 << "c_str()"
5548 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5549 return true;
5550 }
5551 }
5552
5553 return false;
5554}
5555
Ted Kremenekab278de2010-01-28 23:39:18 +00005556bool
Ted Kremenek02087932010-07-16 02:11:22 +00005557CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00005558 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00005559 const char *startSpecifier,
5560 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005561 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00005562 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005563 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00005564
Ted Kremenek6cd69422010-07-19 22:01:06 +00005565 if (FS.consumesDataArgument()) {
5566 if (atFirstArg) {
5567 atFirstArg = false;
5568 usesPositionalArgs = FS.usesPositionalArg();
5569 }
5570 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005571 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5572 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005573 return false;
5574 }
Ted Kremenek5739de72010-01-29 01:06:55 +00005575 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005576
Ted Kremenekd1668192010-02-27 01:41:03 +00005577 // First check if the field width, precision, and conversion specifier
5578 // have matching data arguments.
5579 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5580 startSpecifier, specifierLen)) {
5581 return false;
5582 }
5583
5584 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5585 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005586 return false;
5587 }
5588
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005589 if (!CS.consumesDataArgument()) {
5590 // FIXME: Technically specifying a precision or field width here
5591 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00005592 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005593 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005594
Ted Kremenek4a49d982010-02-26 19:18:41 +00005595 // Consume the argument.
5596 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00005597 if (argIndex < NumDataArgs) {
5598 // The check to see if the argIndex is valid will come later.
5599 // We set the bit here because we may exit early from this
5600 // function if we encounter some other error.
5601 CoveredArgs.set(argIndex);
5602 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00005603
Dimitry Andric6b5ed342015-02-19 22:32:33 +00005604 // FreeBSD kernel extensions.
5605 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5606 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5607 // We need at least two arguments.
5608 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5609 return false;
5610
5611 // Claim the second argument.
5612 CoveredArgs.set(argIndex + 1);
5613
5614 // Type check the first argument (int for %b, pointer for %D)
5615 const Expr *Ex = getDataArg(argIndex);
5616 const analyze_printf::ArgType &AT =
5617 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5618 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5619 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5620 EmitFormatDiagnostic(
5621 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5622 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5623 << false << Ex->getSourceRange(),
5624 Ex->getLocStart(), /*IsStringLocation*/false,
5625 getSpecifierRange(startSpecifier, specifierLen));
5626
5627 // Type check the second argument (char * for both %b and %D)
5628 Ex = getDataArg(argIndex + 1);
5629 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5630 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5631 EmitFormatDiagnostic(
5632 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5633 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5634 << false << Ex->getSourceRange(),
5635 Ex->getLocStart(), /*IsStringLocation*/false,
5636 getSpecifierRange(startSpecifier, specifierLen));
5637
5638 return true;
5639 }
5640
Ted Kremenek4a49d982010-02-26 19:18:41 +00005641 // Check for using an Objective-C specific conversion specifier
5642 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00005643 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00005644 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5645 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00005646 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005647
Mehdi Amini06d367c2016-10-24 20:39:34 +00005648 // %P can only be used with os_log.
5649 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
5650 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5651 specifierLen);
5652 }
5653
5654 // %n is not allowed with os_log.
5655 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
5656 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
5657 getLocationOfByte(CS.getStart()),
5658 /*IsStringLocation*/ false,
5659 getSpecifierRange(startSpecifier, specifierLen));
5660
5661 return true;
5662 }
5663
5664 // Only scalars are allowed for os_trace.
5665 if (FSType == Sema::FST_OSTrace &&
5666 (CS.getKind() == ConversionSpecifier::PArg ||
5667 CS.getKind() == ConversionSpecifier::sArg ||
5668 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
5669 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5670 specifierLen);
5671 }
5672
5673 // Check for use of public/private annotation outside of os_log().
5674 if (FSType != Sema::FST_OSLog) {
5675 if (FS.isPublic().isSet()) {
5676 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5677 << "public",
5678 getLocationOfByte(FS.isPublic().getPosition()),
5679 /*IsStringLocation*/ false,
5680 getSpecifierRange(startSpecifier, specifierLen));
5681 }
5682 if (FS.isPrivate().isSet()) {
5683 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5684 << "private",
5685 getLocationOfByte(FS.isPrivate().getPosition()),
5686 /*IsStringLocation*/ false,
5687 getSpecifierRange(startSpecifier, specifierLen));
5688 }
5689 }
5690
Tom Careb49ec692010-06-17 19:00:27 +00005691 // Check for invalid use of field width
5692 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00005693 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00005694 startSpecifier, specifierLen);
5695 }
5696
5697 // Check for invalid use of precision
5698 if (!FS.hasValidPrecision()) {
5699 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5700 startSpecifier, specifierLen);
5701 }
5702
Mehdi Amini06d367c2016-10-24 20:39:34 +00005703 // Precision is mandatory for %P specifier.
5704 if (CS.getKind() == ConversionSpecifier::PArg &&
5705 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
5706 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
5707 getLocationOfByte(startSpecifier),
5708 /*IsStringLocation*/ false,
5709 getSpecifierRange(startSpecifier, specifierLen));
5710 }
5711
Tom Careb49ec692010-06-17 19:00:27 +00005712 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00005713 if (!FS.hasValidThousandsGroupingPrefix())
5714 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005715 if (!FS.hasValidLeadingZeros())
5716 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5717 if (!FS.hasValidPlusPrefix())
5718 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00005719 if (!FS.hasValidSpacePrefix())
5720 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005721 if (!FS.hasValidAlternativeForm())
5722 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5723 if (!FS.hasValidLeftJustified())
5724 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5725
5726 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00005727 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5728 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5729 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005730 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5731 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5732 startSpecifier, specifierLen);
5733
5734 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005735 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005736 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5737 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005738 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005739 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005740 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005741 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5742 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00005743
Jordan Rose92303592012-09-08 04:00:03 +00005744 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5745 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5746
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005747 // The remaining checks depend on the data arguments.
5748 if (HasVAListArg)
5749 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005750
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005751 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005752 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005753
Jordan Rose58bbe422012-07-19 18:10:08 +00005754 const Expr *Arg = getDataArg(argIndex);
5755 if (!Arg)
5756 return true;
5757
5758 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00005759}
5760
Jordan Roseaee34382012-09-05 22:56:26 +00005761static bool requiresParensToAddCast(const Expr *E) {
5762 // FIXME: We should have a general way to reason about operator
5763 // precedence and whether parens are actually needed here.
5764 // Take care of a few common cases where they aren't.
5765 const Expr *Inside = E->IgnoreImpCasts();
5766 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5767 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5768
5769 switch (Inside->getStmtClass()) {
5770 case Stmt::ArraySubscriptExprClass:
5771 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005772 case Stmt::CharacterLiteralClass:
5773 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005774 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005775 case Stmt::FloatingLiteralClass:
5776 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005777 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005778 case Stmt::ObjCArrayLiteralClass:
5779 case Stmt::ObjCBoolLiteralExprClass:
5780 case Stmt::ObjCBoxedExprClass:
5781 case Stmt::ObjCDictionaryLiteralClass:
5782 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005783 case Stmt::ObjCIvarRefExprClass:
5784 case Stmt::ObjCMessageExprClass:
5785 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005786 case Stmt::ObjCStringLiteralClass:
5787 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005788 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005789 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005790 case Stmt::UnaryOperatorClass:
5791 return false;
5792 default:
5793 return true;
5794 }
5795}
5796
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005797static std::pair<QualType, StringRef>
5798shouldNotPrintDirectly(const ASTContext &Context,
5799 QualType IntendedTy,
5800 const Expr *E) {
5801 // Use a 'while' to peel off layers of typedefs.
5802 QualType TyTy = IntendedTy;
5803 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5804 StringRef Name = UserTy->getDecl()->getName();
5805 QualType CastTy = llvm::StringSwitch<QualType>(Name)
5806 .Case("NSInteger", Context.LongTy)
5807 .Case("NSUInteger", Context.UnsignedLongTy)
5808 .Case("SInt32", Context.IntTy)
5809 .Case("UInt32", Context.UnsignedIntTy)
5810 .Default(QualType());
5811
5812 if (!CastTy.isNull())
5813 return std::make_pair(CastTy, Name);
5814
5815 TyTy = UserTy->desugar();
5816 }
5817
5818 // Strip parens if necessary.
5819 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5820 return shouldNotPrintDirectly(Context,
5821 PE->getSubExpr()->getType(),
5822 PE->getSubExpr());
5823
5824 // If this is a conditional expression, then its result type is constructed
5825 // via usual arithmetic conversions and thus there might be no necessary
5826 // typedef sugar there. Recurse to operands to check for NSInteger &
5827 // Co. usage condition.
5828 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5829 QualType TrueTy, FalseTy;
5830 StringRef TrueName, FalseName;
5831
5832 std::tie(TrueTy, TrueName) =
5833 shouldNotPrintDirectly(Context,
5834 CO->getTrueExpr()->getType(),
5835 CO->getTrueExpr());
5836 std::tie(FalseTy, FalseName) =
5837 shouldNotPrintDirectly(Context,
5838 CO->getFalseExpr()->getType(),
5839 CO->getFalseExpr());
5840
5841 if (TrueTy == FalseTy)
5842 return std::make_pair(TrueTy, TrueName);
5843 else if (TrueTy.isNull())
5844 return std::make_pair(FalseTy, FalseName);
5845 else if (FalseTy.isNull())
5846 return std::make_pair(TrueTy, TrueName);
5847 }
5848
5849 return std::make_pair(QualType(), StringRef());
5850}
5851
Richard Smith55ce3522012-06-25 20:30:08 +00005852bool
5853CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5854 const char *StartSpecifier,
5855 unsigned SpecifierLen,
5856 const Expr *E) {
5857 using namespace analyze_format_string;
5858 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005859 // Now type check the data expression that matches the
5860 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00005861 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00005862 if (!AT.isValid())
5863 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00005864
Jordan Rose598ec092012-12-05 18:44:40 +00005865 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00005866 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5867 ExprTy = TET->getUnderlyingExpr()->getType();
5868 }
5869
Seth Cantrellb4802962015-03-04 03:12:10 +00005870 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5871
5872 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00005873 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005874 }
Jordan Rose98709982012-06-04 22:48:57 +00005875
Jordan Rose22b74712012-09-05 22:56:19 +00005876 // Look through argument promotions for our error message's reported type.
5877 // This includes the integral and floating promotions, but excludes array
5878 // and function pointer decay; seeing that an argument intended to be a
5879 // string has type 'char [6]' is probably more confusing than 'char *'.
5880 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5881 if (ICE->getCastKind() == CK_IntegralCast ||
5882 ICE->getCastKind() == CK_FloatingCast) {
5883 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00005884 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00005885
5886 // Check if we didn't match because of an implicit cast from a 'char'
5887 // or 'short' to an 'int'. This is done because printf is a varargs
5888 // function.
5889 if (ICE->getType() == S.Context.IntTy ||
5890 ICE->getType() == S.Context.UnsignedIntTy) {
5891 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00005892 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00005893 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00005894 }
Jordan Rose98709982012-06-04 22:48:57 +00005895 }
Jordan Rose598ec092012-12-05 18:44:40 +00005896 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5897 // Special case for 'a', which has type 'int' in C.
5898 // Note, however, that we do /not/ want to treat multibyte constants like
5899 // 'MooV' as characters! This form is deprecated but still exists.
5900 if (ExprTy == S.Context.IntTy)
5901 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5902 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00005903 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005904
Jordan Rosebc53ed12014-05-31 04:12:14 +00005905 // Look through enums to their underlying type.
5906 bool IsEnum = false;
5907 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5908 ExprTy = EnumTy->getDecl()->getIntegerType();
5909 IsEnum = true;
5910 }
5911
Jordan Rose0e5badd2012-12-05 18:44:49 +00005912 // %C in an Objective-C context prints a unichar, not a wchar_t.
5913 // If the argument is an integer of some kind, believe the %C and suggest
5914 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00005915 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005916 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00005917 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5918 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5919 !ExprTy->isCharType()) {
5920 // 'unichar' is defined as a typedef of unsigned short, but we should
5921 // prefer using the typedef if it is visible.
5922 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00005923
5924 // While we are here, check if the value is an IntegerLiteral that happens
5925 // to be within the valid range.
5926 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5927 const llvm::APInt &V = IL->getValue();
5928 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5929 return true;
5930 }
5931
Jordan Rose0e5badd2012-12-05 18:44:49 +00005932 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5933 Sema::LookupOrdinaryName);
5934 if (S.LookupName(Result, S.getCurScope())) {
5935 NamedDecl *ND = Result.getFoundDecl();
5936 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5937 if (TD->getUnderlyingType() == IntendedTy)
5938 IntendedTy = S.Context.getTypedefType(TD);
5939 }
5940 }
5941 }
5942
5943 // Special-case some of Darwin's platform-independence types by suggesting
5944 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005945 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00005946 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005947 QualType CastTy;
5948 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5949 if (!CastTy.isNull()) {
5950 IntendedTy = CastTy;
5951 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00005952 }
5953 }
5954
Jordan Rose22b74712012-09-05 22:56:19 +00005955 // We may be able to offer a FixItHint if it is a supported type.
5956 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005957 bool success =
5958 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005959
Jordan Rose22b74712012-09-05 22:56:19 +00005960 if (success) {
5961 // Get the fix string from the fixed format specifier
5962 SmallString<16> buf;
5963 llvm::raw_svector_ostream os(buf);
5964 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005965
Jordan Roseaee34382012-09-05 22:56:26 +00005966 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5967
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005968 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00005969 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5970 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5971 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5972 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00005973 // In this case, the specifier is wrong and should be changed to match
5974 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00005975 EmitFormatDiagnostic(S.PDiag(diag)
5976 << AT.getRepresentativeTypeName(S.Context)
5977 << IntendedTy << IsEnum << E->getSourceRange(),
5978 E->getLocStart(),
5979 /*IsStringLocation*/ false, SpecRange,
5980 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00005981 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00005982 // The canonical type for formatting this value is different from the
5983 // actual type of the expression. (This occurs, for example, with Darwin's
5984 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
5985 // should be printed as 'long' for 64-bit compatibility.)
5986 // Rather than emitting a normal format/argument mismatch, we want to
5987 // add a cast to the recommended type (and correct the format string
5988 // if necessary).
5989 SmallString<16> CastBuf;
5990 llvm::raw_svector_ostream CastFix(CastBuf);
5991 CastFix << "(";
5992 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
5993 CastFix << ")";
5994
5995 SmallVector<FixItHint,4> Hints;
5996 if (!AT.matchesType(S.Context, IntendedTy))
5997 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
5998
5999 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6000 // If there's already a cast present, just replace it.
6001 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6002 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6003
6004 } else if (!requiresParensToAddCast(E)) {
6005 // If the expression has high enough precedence,
6006 // just write the C-style cast.
6007 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6008 CastFix.str()));
6009 } else {
6010 // Otherwise, add parens around the expression as well as the cast.
6011 CastFix << "(";
6012 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6013 CastFix.str()));
6014
Alp Tokerb6cc5922014-05-03 03:45:55 +00006015 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006016 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6017 }
6018
Jordan Rose0e5badd2012-12-05 18:44:49 +00006019 if (ShouldNotPrintDirectly) {
6020 // The expression has a type that should not be printed directly.
6021 // We extract the name from the typedef because we don't want to show
6022 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006023 StringRef Name;
6024 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6025 Name = TypedefTy->getDecl()->getName();
6026 else
6027 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006028 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006029 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006030 << E->getSourceRange(),
6031 E->getLocStart(), /*IsStringLocation=*/false,
6032 SpecRange, Hints);
6033 } else {
6034 // In this case, the expression could be printed using a different
6035 // specifier, but we've decided that the specifier is probably correct
6036 // and we should cast instead. Just use the normal warning message.
6037 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006038 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6039 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006040 << E->getSourceRange(),
6041 E->getLocStart(), /*IsStringLocation*/false,
6042 SpecRange, Hints);
6043 }
Jordan Roseaee34382012-09-05 22:56:26 +00006044 }
Jordan Rose22b74712012-09-05 22:56:19 +00006045 } else {
6046 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6047 SpecifierLen);
6048 // Since the warning for passing non-POD types to variadic functions
6049 // was deferred until now, we emit a warning for non-POD
6050 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006051 switch (S.isValidVarArgType(ExprTy)) {
6052 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006053 case Sema::VAK_ValidInCXX11: {
6054 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6055 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6056 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6057 }
Richard Smithd7293d72013-08-05 18:49:43 +00006058
Seth Cantrellb4802962015-03-04 03:12:10 +00006059 EmitFormatDiagnostic(
6060 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6061 << IsEnum << CSR << E->getSourceRange(),
6062 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6063 break;
6064 }
Richard Smithd7293d72013-08-05 18:49:43 +00006065 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006066 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006067 EmitFormatDiagnostic(
6068 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006069 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006070 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006071 << CallType
6072 << AT.getRepresentativeTypeName(S.Context)
6073 << CSR
6074 << E->getSourceRange(),
6075 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006076 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006077 break;
6078
6079 case Sema::VAK_Invalid:
6080 if (ExprTy->isObjCObjectType())
6081 EmitFormatDiagnostic(
6082 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6083 << S.getLangOpts().CPlusPlus11
6084 << ExprTy
6085 << CallType
6086 << AT.getRepresentativeTypeName(S.Context)
6087 << CSR
6088 << E->getSourceRange(),
6089 E->getLocStart(), /*IsStringLocation*/false, CSR);
6090 else
6091 // FIXME: If this is an initializer list, suggest removing the braces
6092 // or inserting a cast to the target type.
6093 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6094 << isa<InitListExpr>(E) << ExprTy << CallType
6095 << AT.getRepresentativeTypeName(S.Context)
6096 << E->getSourceRange();
6097 break;
6098 }
6099
6100 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6101 "format string specifier index out of range");
6102 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006103 }
6104
Ted Kremenekab278de2010-01-28 23:39:18 +00006105 return true;
6106}
6107
Ted Kremenek02087932010-07-16 02:11:22 +00006108//===--- CHECK: Scanf format string checking ------------------------------===//
6109
6110namespace {
6111class CheckScanfHandler : public CheckFormatHandler {
6112public:
Stephen Hines648c3692016-09-16 01:07:04 +00006113 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006114 const Expr *origFormatExpr, Sema::FormatStringType type,
6115 unsigned firstDataArg, unsigned numDataArgs,
6116 const char *beg, bool hasVAListArg,
6117 ArrayRef<const Expr *> Args, unsigned formatIdx,
6118 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006119 llvm::SmallBitVector &CheckedVarArgs,
6120 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006121 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6122 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6123 inFunctionCall, CallType, CheckedVarArgs,
6124 UncoveredArg) {}
6125
Ted Kremenek02087932010-07-16 02:11:22 +00006126 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6127 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006128 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006129
6130 bool HandleInvalidScanfConversionSpecifier(
6131 const analyze_scanf::ScanfSpecifier &FS,
6132 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006133 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006134
Craig Toppere14c0f82014-03-12 04:55:44 +00006135 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006136};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006137} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006138
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006139void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6140 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006141 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6142 getLocationOfByte(end), /*IsStringLocation*/true,
6143 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006144}
6145
Ted Kremenekce815422010-07-19 21:25:57 +00006146bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6147 const analyze_scanf::ScanfSpecifier &FS,
6148 const char *startSpecifier,
6149 unsigned specifierLen) {
6150
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006151 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006152 FS.getConversionSpecifier();
6153
6154 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6155 getLocationOfByte(CS.getStart()),
6156 startSpecifier, specifierLen,
6157 CS.getStart(), CS.getLength());
6158}
6159
Ted Kremenek02087932010-07-16 02:11:22 +00006160bool CheckScanfHandler::HandleScanfSpecifier(
6161 const analyze_scanf::ScanfSpecifier &FS,
6162 const char *startSpecifier,
6163 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006164 using namespace analyze_scanf;
6165 using namespace analyze_format_string;
6166
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006167 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006168
Ted Kremenek6cd69422010-07-19 22:01:06 +00006169 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6170 // be used to decide if we are using positional arguments consistently.
6171 if (FS.consumesDataArgument()) {
6172 if (atFirstArg) {
6173 atFirstArg = false;
6174 usesPositionalArgs = FS.usesPositionalArg();
6175 }
6176 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006177 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6178 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006179 return false;
6180 }
Ted Kremenek02087932010-07-16 02:11:22 +00006181 }
6182
6183 // Check if the field with is non-zero.
6184 const OptionalAmount &Amt = FS.getFieldWidth();
6185 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6186 if (Amt.getConstantAmount() == 0) {
6187 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6188 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006189 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6190 getLocationOfByte(Amt.getStart()),
6191 /*IsStringLocation*/true, R,
6192 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006193 }
6194 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006195
Ted Kremenek02087932010-07-16 02:11:22 +00006196 if (!FS.consumesDataArgument()) {
6197 // FIXME: Technically specifying a precision or field width here
6198 // makes no sense. Worth issuing a warning at some point.
6199 return true;
6200 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006201
Ted Kremenek02087932010-07-16 02:11:22 +00006202 // Consume the argument.
6203 unsigned argIndex = FS.getArgIndex();
6204 if (argIndex < NumDataArgs) {
6205 // The check to see if the argIndex is valid will come later.
6206 // We set the bit here because we may exit early from this
6207 // function if we encounter some other error.
6208 CoveredArgs.set(argIndex);
6209 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006210
Ted Kremenek4407ea42010-07-20 20:04:47 +00006211 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006212 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006213 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6214 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006215 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006216 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006217 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006218 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6219 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006220
Jordan Rose92303592012-09-08 04:00:03 +00006221 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6222 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6223
Ted Kremenek02087932010-07-16 02:11:22 +00006224 // The remaining checks depend on the data arguments.
6225 if (HasVAListArg)
6226 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006227
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006228 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006229 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006230
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006231 // Check that the argument type matches the format specifier.
6232 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006233 if (!Ex)
6234 return true;
6235
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006236 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006237
6238 if (!AT.isValid()) {
6239 return true;
6240 }
6241
Seth Cantrellb4802962015-03-04 03:12:10 +00006242 analyze_format_string::ArgType::MatchKind match =
6243 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006244 if (match == analyze_format_string::ArgType::Match) {
6245 return true;
6246 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006247
Seth Cantrell79340072015-03-04 05:58:08 +00006248 ScanfSpecifier fixedFS = FS;
6249 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6250 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006251
Seth Cantrell79340072015-03-04 05:58:08 +00006252 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6253 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6254 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6255 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006256
Seth Cantrell79340072015-03-04 05:58:08 +00006257 if (success) {
6258 // Get the fix string from the fixed format specifier.
6259 SmallString<128> buf;
6260 llvm::raw_svector_ostream os(buf);
6261 fixedFS.toString(os);
6262
6263 EmitFormatDiagnostic(
6264 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6265 << Ex->getType() << false << Ex->getSourceRange(),
6266 Ex->getLocStart(),
6267 /*IsStringLocation*/ false,
6268 getSpecifierRange(startSpecifier, specifierLen),
6269 FixItHint::CreateReplacement(
6270 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6271 } else {
6272 EmitFormatDiagnostic(S.PDiag(diag)
6273 << AT.getRepresentativeTypeName(S.Context)
6274 << Ex->getType() << false << Ex->getSourceRange(),
6275 Ex->getLocStart(),
6276 /*IsStringLocation*/ false,
6277 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006278 }
6279
Ted Kremenek02087932010-07-16 02:11:22 +00006280 return true;
6281}
6282
Stephen Hines648c3692016-09-16 01:07:04 +00006283static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006284 const Expr *OrigFormatExpr,
6285 ArrayRef<const Expr *> Args,
6286 bool HasVAListArg, unsigned format_idx,
6287 unsigned firstDataArg,
6288 Sema::FormatStringType Type,
6289 bool inFunctionCall,
6290 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006291 llvm::SmallBitVector &CheckedVarArgs,
6292 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00006293 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00006294 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006295 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006296 S, inFunctionCall, Args[format_idx],
6297 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006298 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006299 return;
6300 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006301
Ted Kremenekab278de2010-01-28 23:39:18 +00006302 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006303 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00006304 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006305 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006306 const ConstantArrayType *T =
6307 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006308 assert(T && "String literal not of constant array type!");
6309 size_t TypeSize = T->getSize().getZExtValue();
6310 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006311 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006312
6313 // Emit a warning if the string literal is truncated and does not contain an
6314 // embedded null character.
6315 if (TypeSize <= StrRef.size() &&
6316 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6317 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006318 S, inFunctionCall, Args[format_idx],
6319 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006320 FExpr->getLocStart(),
6321 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6322 return;
6323 }
6324
Ted Kremenekab278de2010-01-28 23:39:18 +00006325 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006326 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006327 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006328 S, inFunctionCall, Args[format_idx],
6329 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006330 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006331 return;
6332 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006333
6334 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00006335 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6336 Type == Sema::FST_OSTrace) {
6337 CheckPrintfHandler H(
6338 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6339 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6340 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6341 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006342
Hans Wennborg23926bd2011-12-15 10:25:47 +00006343 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006344 S.getLangOpts(),
6345 S.Context.getTargetInfo(),
6346 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006347 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006348 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00006349 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6350 numDataArgs, Str, HasVAListArg, Args, format_idx,
6351 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006352
Hans Wennborg23926bd2011-12-15 10:25:47 +00006353 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006354 S.getLangOpts(),
6355 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006356 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006357 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006358}
6359
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006360bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6361 // Str - The format string. NOTE: this is NOT null-terminated!
6362 StringRef StrRef = FExpr->getString();
6363 const char *Str = StrRef.data();
6364 // Account for cases where the string literal is truncated in a declaration.
6365 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6366 assert(T && "String literal not of constant array type!");
6367 size_t TypeSize = T->getSize().getZExtValue();
6368 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6369 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6370 getLangOpts(),
6371 Context.getTargetInfo());
6372}
6373
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006374//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6375
6376// Returns the related absolute value function that is larger, of 0 if one
6377// does not exist.
6378static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6379 switch (AbsFunction) {
6380 default:
6381 return 0;
6382
6383 case Builtin::BI__builtin_abs:
6384 return Builtin::BI__builtin_labs;
6385 case Builtin::BI__builtin_labs:
6386 return Builtin::BI__builtin_llabs;
6387 case Builtin::BI__builtin_llabs:
6388 return 0;
6389
6390 case Builtin::BI__builtin_fabsf:
6391 return Builtin::BI__builtin_fabs;
6392 case Builtin::BI__builtin_fabs:
6393 return Builtin::BI__builtin_fabsl;
6394 case Builtin::BI__builtin_fabsl:
6395 return 0;
6396
6397 case Builtin::BI__builtin_cabsf:
6398 return Builtin::BI__builtin_cabs;
6399 case Builtin::BI__builtin_cabs:
6400 return Builtin::BI__builtin_cabsl;
6401 case Builtin::BI__builtin_cabsl:
6402 return 0;
6403
6404 case Builtin::BIabs:
6405 return Builtin::BIlabs;
6406 case Builtin::BIlabs:
6407 return Builtin::BIllabs;
6408 case Builtin::BIllabs:
6409 return 0;
6410
6411 case Builtin::BIfabsf:
6412 return Builtin::BIfabs;
6413 case Builtin::BIfabs:
6414 return Builtin::BIfabsl;
6415 case Builtin::BIfabsl:
6416 return 0;
6417
6418 case Builtin::BIcabsf:
6419 return Builtin::BIcabs;
6420 case Builtin::BIcabs:
6421 return Builtin::BIcabsl;
6422 case Builtin::BIcabsl:
6423 return 0;
6424 }
6425}
6426
6427// Returns the argument type of the absolute value function.
6428static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6429 unsigned AbsType) {
6430 if (AbsType == 0)
6431 return QualType();
6432
6433 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6434 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6435 if (Error != ASTContext::GE_None)
6436 return QualType();
6437
6438 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6439 if (!FT)
6440 return QualType();
6441
6442 if (FT->getNumParams() != 1)
6443 return QualType();
6444
6445 return FT->getParamType(0);
6446}
6447
6448// Returns the best absolute value function, or zero, based on type and
6449// current absolute value function.
6450static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6451 unsigned AbsFunctionKind) {
6452 unsigned BestKind = 0;
6453 uint64_t ArgSize = Context.getTypeSize(ArgType);
6454 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6455 Kind = getLargerAbsoluteValueFunction(Kind)) {
6456 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6457 if (Context.getTypeSize(ParamType) >= ArgSize) {
6458 if (BestKind == 0)
6459 BestKind = Kind;
6460 else if (Context.hasSameType(ParamType, ArgType)) {
6461 BestKind = Kind;
6462 break;
6463 }
6464 }
6465 }
6466 return BestKind;
6467}
6468
6469enum AbsoluteValueKind {
6470 AVK_Integer,
6471 AVK_Floating,
6472 AVK_Complex
6473};
6474
6475static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6476 if (T->isIntegralOrEnumerationType())
6477 return AVK_Integer;
6478 if (T->isRealFloatingType())
6479 return AVK_Floating;
6480 if (T->isAnyComplexType())
6481 return AVK_Complex;
6482
6483 llvm_unreachable("Type not integer, floating, or complex");
6484}
6485
6486// Changes the absolute value function to a different type. Preserves whether
6487// the function is a builtin.
6488static unsigned changeAbsFunction(unsigned AbsKind,
6489 AbsoluteValueKind ValueKind) {
6490 switch (ValueKind) {
6491 case AVK_Integer:
6492 switch (AbsKind) {
6493 default:
6494 return 0;
6495 case Builtin::BI__builtin_fabsf:
6496 case Builtin::BI__builtin_fabs:
6497 case Builtin::BI__builtin_fabsl:
6498 case Builtin::BI__builtin_cabsf:
6499 case Builtin::BI__builtin_cabs:
6500 case Builtin::BI__builtin_cabsl:
6501 return Builtin::BI__builtin_abs;
6502 case Builtin::BIfabsf:
6503 case Builtin::BIfabs:
6504 case Builtin::BIfabsl:
6505 case Builtin::BIcabsf:
6506 case Builtin::BIcabs:
6507 case Builtin::BIcabsl:
6508 return Builtin::BIabs;
6509 }
6510 case AVK_Floating:
6511 switch (AbsKind) {
6512 default:
6513 return 0;
6514 case Builtin::BI__builtin_abs:
6515 case Builtin::BI__builtin_labs:
6516 case Builtin::BI__builtin_llabs:
6517 case Builtin::BI__builtin_cabsf:
6518 case Builtin::BI__builtin_cabs:
6519 case Builtin::BI__builtin_cabsl:
6520 return Builtin::BI__builtin_fabsf;
6521 case Builtin::BIabs:
6522 case Builtin::BIlabs:
6523 case Builtin::BIllabs:
6524 case Builtin::BIcabsf:
6525 case Builtin::BIcabs:
6526 case Builtin::BIcabsl:
6527 return Builtin::BIfabsf;
6528 }
6529 case AVK_Complex:
6530 switch (AbsKind) {
6531 default:
6532 return 0;
6533 case Builtin::BI__builtin_abs:
6534 case Builtin::BI__builtin_labs:
6535 case Builtin::BI__builtin_llabs:
6536 case Builtin::BI__builtin_fabsf:
6537 case Builtin::BI__builtin_fabs:
6538 case Builtin::BI__builtin_fabsl:
6539 return Builtin::BI__builtin_cabsf;
6540 case Builtin::BIabs:
6541 case Builtin::BIlabs:
6542 case Builtin::BIllabs:
6543 case Builtin::BIfabsf:
6544 case Builtin::BIfabs:
6545 case Builtin::BIfabsl:
6546 return Builtin::BIcabsf;
6547 }
6548 }
6549 llvm_unreachable("Unable to convert function");
6550}
6551
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006552static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006553 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6554 if (!FnInfo)
6555 return 0;
6556
6557 switch (FDecl->getBuiltinID()) {
6558 default:
6559 return 0;
6560 case Builtin::BI__builtin_abs:
6561 case Builtin::BI__builtin_fabs:
6562 case Builtin::BI__builtin_fabsf:
6563 case Builtin::BI__builtin_fabsl:
6564 case Builtin::BI__builtin_labs:
6565 case Builtin::BI__builtin_llabs:
6566 case Builtin::BI__builtin_cabs:
6567 case Builtin::BI__builtin_cabsf:
6568 case Builtin::BI__builtin_cabsl:
6569 case Builtin::BIabs:
6570 case Builtin::BIlabs:
6571 case Builtin::BIllabs:
6572 case Builtin::BIfabs:
6573 case Builtin::BIfabsf:
6574 case Builtin::BIfabsl:
6575 case Builtin::BIcabs:
6576 case Builtin::BIcabsf:
6577 case Builtin::BIcabsl:
6578 return FDecl->getBuiltinID();
6579 }
6580 llvm_unreachable("Unknown Builtin type");
6581}
6582
6583// If the replacement is valid, emit a note with replacement function.
6584// Additionally, suggest including the proper header if not already included.
6585static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00006586 unsigned AbsKind, QualType ArgType) {
6587 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006588 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00006589 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006590 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6591 FunctionName = "std::abs";
6592 if (ArgType->isIntegralOrEnumerationType()) {
6593 HeaderName = "cstdlib";
6594 } else if (ArgType->isRealFloatingType()) {
6595 HeaderName = "cmath";
6596 } else {
6597 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006598 }
Richard Trieubeffb832014-04-15 23:47:53 +00006599
6600 // Lookup all std::abs
6601 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00006602 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00006603 R.suppressDiagnostics();
6604 S.LookupQualifiedName(R, Std);
6605
6606 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006607 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006608 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6609 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6610 } else {
6611 FDecl = dyn_cast<FunctionDecl>(I);
6612 }
6613 if (!FDecl)
6614 continue;
6615
6616 // Found std::abs(), check that they are the right ones.
6617 if (FDecl->getNumParams() != 1)
6618 continue;
6619
6620 // Check that the parameter type can handle the argument.
6621 QualType ParamType = FDecl->getParamDecl(0)->getType();
6622 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6623 S.Context.getTypeSize(ArgType) <=
6624 S.Context.getTypeSize(ParamType)) {
6625 // Found a function, don't need the header hint.
6626 EmitHeaderHint = false;
6627 break;
6628 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006629 }
Richard Trieubeffb832014-04-15 23:47:53 +00006630 }
6631 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00006632 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00006633 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6634
6635 if (HeaderName) {
6636 DeclarationName DN(&S.Context.Idents.get(FunctionName));
6637 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6638 R.suppressDiagnostics();
6639 S.LookupName(R, S.getCurScope());
6640
6641 if (R.isSingleResult()) {
6642 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6643 if (FD && FD->getBuiltinID() == AbsKind) {
6644 EmitHeaderHint = false;
6645 } else {
6646 return;
6647 }
6648 } else if (!R.empty()) {
6649 return;
6650 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006651 }
6652 }
6653
6654 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00006655 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006656
Richard Trieubeffb832014-04-15 23:47:53 +00006657 if (!HeaderName)
6658 return;
6659
6660 if (!EmitHeaderHint)
6661 return;
6662
Alp Toker5d96e0a2014-07-11 20:53:51 +00006663 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6664 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00006665}
6666
6667static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
6668 if (!FDecl)
6669 return false;
6670
6671 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
6672 return false;
6673
6674 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
6675
6676 while (ND && ND->isInlineNamespace()) {
6677 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006678 }
Richard Trieubeffb832014-04-15 23:47:53 +00006679
6680 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
6681 return false;
6682
6683 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
6684 return false;
6685
6686 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006687}
6688
6689// Warn when using the wrong abs() function.
6690void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
6691 const FunctionDecl *FDecl,
6692 IdentifierInfo *FnInfo) {
6693 if (Call->getNumArgs() != 1)
6694 return;
6695
6696 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00006697 bool IsStdAbs = IsFunctionStdAbs(FDecl);
6698 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006699 return;
6700
6701 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6702 QualType ParamType = Call->getArg(0)->getType();
6703
Alp Toker5d96e0a2014-07-11 20:53:51 +00006704 // Unsigned types cannot be negative. Suggest removing the absolute value
6705 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006706 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00006707 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00006708 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006709 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6710 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00006711 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006712 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6713 return;
6714 }
6715
David Majnemer7f77eb92015-11-15 03:04:34 +00006716 // Taking the absolute value of a pointer is very suspicious, they probably
6717 // wanted to index into an array, dereference a pointer, call a function, etc.
6718 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6719 unsigned DiagType = 0;
6720 if (ArgType->isFunctionType())
6721 DiagType = 1;
6722 else if (ArgType->isArrayType())
6723 DiagType = 2;
6724
6725 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6726 return;
6727 }
6728
Richard Trieubeffb832014-04-15 23:47:53 +00006729 // std::abs has overloads which prevent most of the absolute value problems
6730 // from occurring.
6731 if (IsStdAbs)
6732 return;
6733
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006734 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6735 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6736
6737 // The argument and parameter are the same kind. Check if they are the right
6738 // size.
6739 if (ArgValueKind == ParamValueKind) {
6740 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6741 return;
6742
6743 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6744 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6745 << FDecl << ArgType << ParamType;
6746
6747 if (NewAbsKind == 0)
6748 return;
6749
6750 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006751 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006752 return;
6753 }
6754
6755 // ArgValueKind != ParamValueKind
6756 // The wrong type of absolute value function was used. Attempt to find the
6757 // proper one.
6758 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6759 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6760 if (NewAbsKind == 0)
6761 return;
6762
6763 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6764 << FDecl << ParamValueKind << ArgValueKind;
6765
6766 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006767 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006768}
6769
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006770//===--- CHECK: Standard memory functions ---------------------------------===//
6771
Nico Weber0e6daef2013-12-26 23:38:39 +00006772/// \brief Takes the expression passed to the size_t parameter of functions
6773/// such as memcmp, strncat, etc and warns if it's a comparison.
6774///
6775/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6776static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6777 IdentifierInfo *FnName,
6778 SourceLocation FnLoc,
6779 SourceLocation RParenLoc) {
6780 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6781 if (!Size)
6782 return false;
6783
6784 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6785 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6786 return false;
6787
Nico Weber0e6daef2013-12-26 23:38:39 +00006788 SourceRange SizeRange = Size->getSourceRange();
6789 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6790 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00006791 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006792 << FnName << FixItHint::CreateInsertion(
6793 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00006794 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00006795 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00006796 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00006797 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6798 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00006799
6800 return true;
6801}
6802
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006803/// \brief Determine whether the given type is or contains a dynamic class type
6804/// (e.g., whether it has a vtable).
6805static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6806 bool &IsContained) {
6807 // Look through array types while ignoring qualifiers.
6808 const Type *Ty = T->getBaseElementTypeUnsafe();
6809 IsContained = false;
6810
6811 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6812 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00006813 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006814 return nullptr;
6815
6816 if (RD->isDynamicClass())
6817 return RD;
6818
6819 // Check all the fields. If any bases were dynamic, the class is dynamic.
6820 // It's impossible for a class to transitively contain itself by value, so
6821 // infinite recursion is impossible.
6822 for (auto *FD : RD->fields()) {
6823 bool SubContained;
6824 if (const CXXRecordDecl *ContainedRD =
6825 getContainedDynamicClass(FD->getType(), SubContained)) {
6826 IsContained = true;
6827 return ContainedRD;
6828 }
6829 }
6830
6831 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00006832}
6833
Chandler Carruth889ed862011-06-21 23:04:20 +00006834/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006835/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00006836static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00006837 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006838 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6839 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6840 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006841
Craig Topperc3ec1492014-05-26 06:22:03 +00006842 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006843}
6844
Chandler Carruth889ed862011-06-21 23:04:20 +00006845/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00006846static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006847 if (const UnaryExprOrTypeTraitExpr *SizeOf =
6848 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6849 if (SizeOf->getKind() == clang::UETT_SizeOf)
6850 return SizeOf->getTypeOfArgument();
6851
6852 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00006853}
6854
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006855/// \brief Check for dangerous or invalid arguments to memset().
6856///
Chandler Carruthac687262011-06-03 06:23:57 +00006857/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006858/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6859/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006860///
6861/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006862void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00006863 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006864 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00006865 assert(BId != 0);
6866
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006867 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00006868 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006869 unsigned ExpectedNumArgs =
6870 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00006871 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006872 return;
6873
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006874 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00006875 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006876 unsigned LenArg =
6877 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00006878 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006879
Nico Weber0e6daef2013-12-26 23:38:39 +00006880 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6881 Call->getLocStart(), Call->getRParenLoc()))
6882 return;
6883
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006884 // We have special checking when the length is a sizeof expression.
6885 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6886 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6887 llvm::FoldingSetNodeID SizeOfArgID;
6888
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00006889 // Although widely used, 'bzero' is not a standard function. Be more strict
6890 // with the argument types before allowing diagnostics and only allow the
6891 // form bzero(ptr, sizeof(...)).
6892 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6893 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
6894 return;
6895
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006896 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6897 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006898 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006899
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006900 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00006901 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006902 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00006903 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00006904
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006905 // Never warn about void type pointers. This can be used to suppress
6906 // false positives.
6907 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006908 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006909
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006910 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6911 // actually comparing the expressions for equality. Because computing the
6912 // expression IDs can be expensive, we only do this if the diagnostic is
6913 // enabled.
6914 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006915 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6916 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006917 // We only compute IDs for expressions if the warning is enabled, and
6918 // cache the sizeof arg's ID.
6919 if (SizeOfArgID == llvm::FoldingSetNodeID())
6920 SizeOfArg->Profile(SizeOfArgID, Context, true);
6921 llvm::FoldingSetNodeID DestID;
6922 Dest->Profile(DestID, Context, true);
6923 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00006924 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6925 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006926 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00006927 StringRef ReadableName = FnName->getName();
6928
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006929 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00006930 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006931 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00006932 if (!PointeeTy->isIncompleteType() &&
6933 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006934 ActionIdx = 2; // If the pointee's size is sizeof(char),
6935 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00006936
6937 // If the function is defined as a builtin macro, do not show macro
6938 // expansion.
6939 SourceLocation SL = SizeOfArg->getExprLoc();
6940 SourceRange DSR = Dest->getSourceRange();
6941 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006942 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00006943
6944 if (SM.isMacroArgExpansion(SL)) {
6945 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
6946 SL = SM.getSpellingLoc(SL);
6947 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
6948 SM.getSpellingLoc(DSR.getEnd()));
6949 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
6950 SM.getSpellingLoc(SSR.getEnd()));
6951 }
6952
Anna Zaksd08d9152012-05-30 23:14:52 +00006953 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006954 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00006955 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00006956 << PointeeTy
6957 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00006958 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00006959 << SSR);
6960 DiagRuntimeBehavior(SL, SizeOfArg,
6961 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
6962 << ActionIdx
6963 << SSR);
6964
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006965 break;
6966 }
6967 }
6968
6969 // Also check for cases where the sizeof argument is the exact same
6970 // type as the memory argument, and where it points to a user-defined
6971 // record type.
6972 if (SizeOfArgTy != QualType()) {
6973 if (PointeeTy->isRecordType() &&
6974 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
6975 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
6976 PDiag(diag::warn_sizeof_pointer_type_memaccess)
6977 << FnName << SizeOfArgTy << ArgIdx
6978 << PointeeTy << Dest->getSourceRange()
6979 << LenExpr->getSourceRange());
6980 break;
6981 }
Nico Weberc5e73862011-06-14 16:14:58 +00006982 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00006983 } else if (DestTy->isArrayType()) {
6984 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00006985 }
Nico Weberc5e73862011-06-14 16:14:58 +00006986
Nico Weberc44b35e2015-03-21 17:37:46 +00006987 if (PointeeTy == QualType())
6988 continue;
Anna Zaks22122702012-01-17 00:37:07 +00006989
Nico Weberc44b35e2015-03-21 17:37:46 +00006990 // Always complain about dynamic classes.
6991 bool IsContained;
6992 if (const CXXRecordDecl *ContainedRD =
6993 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00006994
Nico Weberc44b35e2015-03-21 17:37:46 +00006995 unsigned OperationType = 0;
6996 // "overwritten" if we're warning about the destination for any call
6997 // but memcmp; otherwise a verb appropriate to the call.
6998 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
6999 if (BId == Builtin::BImemcpy)
7000 OperationType = 1;
7001 else if(BId == Builtin::BImemmove)
7002 OperationType = 2;
7003 else if (BId == Builtin::BImemcmp)
7004 OperationType = 3;
7005 }
7006
John McCall31168b02011-06-15 23:02:42 +00007007 DiagRuntimeBehavior(
7008 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007009 PDiag(diag::warn_dyn_class_memaccess)
7010 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7011 << FnName << IsContained << ContainedRD << OperationType
7012 << Call->getCallee()->getSourceRange());
7013 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7014 BId != Builtin::BImemset)
7015 DiagRuntimeBehavior(
7016 Dest->getExprLoc(), Dest,
7017 PDiag(diag::warn_arc_object_memaccess)
7018 << ArgIdx << FnName << PointeeTy
7019 << Call->getCallee()->getSourceRange());
7020 else
7021 continue;
7022
7023 DiagRuntimeBehavior(
7024 Dest->getExprLoc(), Dest,
7025 PDiag(diag::note_bad_memaccess_silence)
7026 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7027 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007028 }
7029}
7030
Ted Kremenek6865f772011-08-18 20:55:45 +00007031// A little helper routine: ignore addition and subtraction of integer literals.
7032// This intentionally does not ignore all integer constant expressions because
7033// we don't want to remove sizeof().
7034static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7035 Ex = Ex->IgnoreParenCasts();
7036
7037 for (;;) {
7038 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7039 if (!BO || !BO->isAdditiveOp())
7040 break;
7041
7042 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7043 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7044
7045 if (isa<IntegerLiteral>(RHS))
7046 Ex = LHS;
7047 else if (isa<IntegerLiteral>(LHS))
7048 Ex = RHS;
7049 else
7050 break;
7051 }
7052
7053 return Ex;
7054}
7055
Anna Zaks13b08572012-08-08 21:42:23 +00007056static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7057 ASTContext &Context) {
7058 // Only handle constant-sized or VLAs, but not flexible members.
7059 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7060 // Only issue the FIXIT for arrays of size > 1.
7061 if (CAT->getSize().getSExtValue() <= 1)
7062 return false;
7063 } else if (!Ty->isVariableArrayType()) {
7064 return false;
7065 }
7066 return true;
7067}
7068
Ted Kremenek6865f772011-08-18 20:55:45 +00007069// Warn if the user has made the 'size' argument to strlcpy or strlcat
7070// be the size of the source, instead of the destination.
7071void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7072 IdentifierInfo *FnName) {
7073
7074 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007075 unsigned NumArgs = Call->getNumArgs();
7076 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007077 return;
7078
7079 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7080 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007081 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007082
7083 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7084 Call->getLocStart(), Call->getRParenLoc()))
7085 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00007086
7087 // Look for 'strlcpy(dst, x, sizeof(x))'
7088 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7089 CompareWithSrc = Ex;
7090 else {
7091 // Look for 'strlcpy(dst, x, strlen(x))'
7092 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00007093 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7094 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00007095 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7096 }
7097 }
7098
7099 if (!CompareWithSrc)
7100 return;
7101
7102 // Determine if the argument to sizeof/strlen is equal to the source
7103 // argument. In principle there's all kinds of things you could do
7104 // here, for instance creating an == expression and evaluating it with
7105 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7106 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7107 if (!SrcArgDRE)
7108 return;
7109
7110 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7111 if (!CompareWithSrcDRE ||
7112 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7113 return;
7114
7115 const Expr *OriginalSizeArg = Call->getArg(2);
7116 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7117 << OriginalSizeArg->getSourceRange() << FnName;
7118
7119 // Output a FIXIT hint if the destination is an array (rather than a
7120 // pointer to an array). This could be enhanced to handle some
7121 // pointers if we know the actual size, like if DstArg is 'array+2'
7122 // we could say 'sizeof(array)-2'.
7123 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00007124 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00007125 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007126
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007127 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007128 llvm::raw_svector_ostream OS(sizeString);
7129 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007130 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00007131 OS << ")";
7132
7133 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7134 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7135 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00007136}
7137
Anna Zaks314cd092012-02-01 19:08:57 +00007138/// Check if two expressions refer to the same declaration.
7139static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7140 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7141 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7142 return D1->getDecl() == D2->getDecl();
7143 return false;
7144}
7145
7146static const Expr *getStrlenExprArg(const Expr *E) {
7147 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7148 const FunctionDecl *FD = CE->getDirectCallee();
7149 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00007150 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007151 return CE->getArg(0)->IgnoreParenCasts();
7152 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007153 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007154}
7155
7156// Warn on anti-patterns as the 'size' argument to strncat.
7157// The correct size argument should look like following:
7158// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7159void Sema::CheckStrncatArguments(const CallExpr *CE,
7160 IdentifierInfo *FnName) {
7161 // Don't crash if the user has the wrong number of arguments.
7162 if (CE->getNumArgs() < 3)
7163 return;
7164 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7165 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7166 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7167
Nico Weber0e6daef2013-12-26 23:38:39 +00007168 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7169 CE->getRParenLoc()))
7170 return;
7171
Anna Zaks314cd092012-02-01 19:08:57 +00007172 // Identify common expressions, which are wrongly used as the size argument
7173 // to strncat and may lead to buffer overflows.
7174 unsigned PatternType = 0;
7175 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7176 // - sizeof(dst)
7177 if (referToTheSameDecl(SizeOfArg, DstArg))
7178 PatternType = 1;
7179 // - sizeof(src)
7180 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7181 PatternType = 2;
7182 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7183 if (BE->getOpcode() == BO_Sub) {
7184 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7185 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7186 // - sizeof(dst) - strlen(dst)
7187 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7188 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7189 PatternType = 1;
7190 // - sizeof(src) - (anything)
7191 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7192 PatternType = 2;
7193 }
7194 }
7195
7196 if (PatternType == 0)
7197 return;
7198
Anna Zaks5069aa32012-02-03 01:27:37 +00007199 // Generate the diagnostic.
7200 SourceLocation SL = LenArg->getLocStart();
7201 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007202 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00007203
7204 // If the function is defined as a builtin macro, do not show macro expansion.
7205 if (SM.isMacroArgExpansion(SL)) {
7206 SL = SM.getSpellingLoc(SL);
7207 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7208 SM.getSpellingLoc(SR.getEnd()));
7209 }
7210
Anna Zaks13b08572012-08-08 21:42:23 +00007211 // Check if the destination is an array (rather than a pointer to an array).
7212 QualType DstTy = DstArg->getType();
7213 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7214 Context);
7215 if (!isKnownSizeArray) {
7216 if (PatternType == 1)
7217 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7218 else
7219 Diag(SL, diag::warn_strncat_src_size) << SR;
7220 return;
7221 }
7222
Anna Zaks314cd092012-02-01 19:08:57 +00007223 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00007224 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007225 else
Anna Zaks5069aa32012-02-03 01:27:37 +00007226 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007227
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007228 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00007229 llvm::raw_svector_ostream OS(sizeString);
7230 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007231 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007232 OS << ") - ";
7233 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007234 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007235 OS << ") - 1";
7236
Anna Zaks5069aa32012-02-03 01:27:37 +00007237 Diag(SL, diag::note_strncat_wrong_size)
7238 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00007239}
7240
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007241//===--- CHECK: Return Address of Stack Variable --------------------------===//
7242
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007243static const Expr *EvalVal(const Expr *E,
7244 SmallVectorImpl<const DeclRefExpr *> &refVars,
7245 const Decl *ParentDecl);
7246static const Expr *EvalAddr(const Expr *E,
7247 SmallVectorImpl<const DeclRefExpr *> &refVars,
7248 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007249
7250/// CheckReturnStackAddr - Check if a return statement returns the address
7251/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007252static void
7253CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7254 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00007255
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007256 const Expr *stackE = nullptr;
7257 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007258
7259 // Perform checking for returned stack addresses, local blocks,
7260 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00007261 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007262 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007263 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00007264 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007265 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007266 }
7267
Craig Topperc3ec1492014-05-26 06:22:03 +00007268 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007269 return; // Nothing suspicious was found.
7270
Richard Trieu81b6c562016-08-05 23:24:47 +00007271 // Parameters are initalized in the calling scope, so taking the address
7272 // of a parameter reference doesn't need a warning.
7273 for (auto *DRE : refVars)
7274 if (isa<ParmVarDecl>(DRE->getDecl()))
7275 return;
7276
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007277 SourceLocation diagLoc;
7278 SourceRange diagRange;
7279 if (refVars.empty()) {
7280 diagLoc = stackE->getLocStart();
7281 diagRange = stackE->getSourceRange();
7282 } else {
7283 // We followed through a reference variable. 'stackE' contains the
7284 // problematic expression but we will warn at the return statement pointing
7285 // at the reference variable. We will later display the "trail" of
7286 // reference variables using notes.
7287 diagLoc = refVars[0]->getLocStart();
7288 diagRange = refVars[0]->getSourceRange();
7289 }
7290
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007291 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7292 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00007293 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007294 << DR->getDecl()->getDeclName() << diagRange;
7295 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007296 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007297 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007298 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007299 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00007300 // If there is an LValue->RValue conversion, then the value of the
7301 // reference type is used, not the reference.
7302 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7303 if (ICE->getCastKind() == CK_LValueToRValue) {
7304 return;
7305 }
7306 }
Craig Topperda7b27f2015-11-17 05:40:09 +00007307 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7308 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007309 }
7310
7311 // Display the "trail" of reference variables that we followed until we
7312 // found the problematic expression using notes.
7313 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007314 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007315 // If this var binds to another reference var, show the range of the next
7316 // var, otherwise the var binds to the problematic expression, in which case
7317 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007318 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7319 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007320 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7321 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007322 }
7323}
7324
7325/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7326/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007327/// to a location on the stack, a local block, an address of a label, or a
7328/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007329/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007330/// encounter a subexpression that (1) clearly does not lead to one of the
7331/// above problematic expressions (2) is something we cannot determine leads to
7332/// a problematic expression based on such local checking.
7333///
7334/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7335/// the expression that they point to. Such variables are added to the
7336/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007337///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007338/// EvalAddr processes expressions that are pointers that are used as
7339/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007340/// At the base case of the recursion is a check for the above problematic
7341/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007342///
7343/// This implementation handles:
7344///
7345/// * pointer-to-pointer casts
7346/// * implicit conversions from array references to pointers
7347/// * taking the address of fields
7348/// * arbitrary interplay between "&" and "*" operators
7349/// * pointer arithmetic from an address of a stack variable
7350/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007351static const Expr *EvalAddr(const Expr *E,
7352 SmallVectorImpl<const DeclRefExpr *> &refVars,
7353 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007354 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00007355 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007356
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007357 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00007358 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00007359 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007360 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00007361 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00007362
Peter Collingbourne91147592011-04-15 00:35:48 +00007363 E = E->IgnoreParens();
7364
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007365 // Our "symbolic interpreter" is just a dispatch off the currently
7366 // viewed AST node. We then recursively traverse the AST by calling
7367 // EvalAddr and EvalVal appropriately.
7368 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007369 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007370 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007371
Richard Smith40f08eb2014-01-30 22:05:38 +00007372 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00007373 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00007374 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00007375
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007376 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007377 // If this is a reference variable, follow through to the expression that
7378 // it points to.
7379 if (V->hasLocalStorage() &&
7380 V->getType()->isReferenceType() && V->hasInit()) {
7381 // Add the reference variable to the "trail".
7382 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007383 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007384 }
7385
Craig Topperc3ec1492014-05-26 06:22:03 +00007386 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007387 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007388
Chris Lattner934edb22007-12-28 05:31:15 +00007389 case Stmt::UnaryOperatorClass: {
7390 // The only unary operator that make sense to handle here
7391 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007392 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007393
John McCalle3027922010-08-25 11:45:40 +00007394 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007395 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007396 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007397 }
Mike Stump11289f42009-09-09 15:08:12 +00007398
Chris Lattner934edb22007-12-28 05:31:15 +00007399 case Stmt::BinaryOperatorClass: {
7400 // Handle pointer arithmetic. All other binary operators are not valid
7401 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007402 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00007403 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00007404
John McCalle3027922010-08-25 11:45:40 +00007405 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00007406 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007407
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007408 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00007409
7410 // Determine which argument is the real pointer base. It could be
7411 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007412 if (!Base->getType()->isPointerType())
7413 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00007414
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007415 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007416 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007417 }
Steve Naroff2752a172008-09-10 19:17:48 +00007418
Chris Lattner934edb22007-12-28 05:31:15 +00007419 // For conditional operators we need to see if either the LHS or RHS are
7420 // valid DeclRefExpr*s. If one of them is valid, we return it.
7421 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007422 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007423
Chris Lattner934edb22007-12-28 05:31:15 +00007424 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007425 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007426 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007427 // In C++, we can have a throw-expression, which has 'void' type.
7428 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007429 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007430 return LHS;
7431 }
Chris Lattner934edb22007-12-28 05:31:15 +00007432
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007433 // In C++, we can have a throw-expression, which has 'void' type.
7434 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00007435 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007436
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007437 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007438 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007439
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007440 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00007441 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007442 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00007443 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007444
7445 case Stmt::AddrLabelExprClass:
7446 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00007447
John McCall28fc7092011-11-10 05:35:25 +00007448 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007449 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7450 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00007451
Ted Kremenekc3b4c522008-08-07 00:49:01 +00007452 // For casts, we need to handle conversions from arrays to
7453 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00007454 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00007455 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007456 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00007457 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00007458 case Stmt::CXXStaticCastExprClass:
7459 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00007460 case Stmt::CXXConstCastExprClass:
7461 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007462 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00007463 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00007464 case CK_LValueToRValue:
7465 case CK_NoOp:
7466 case CK_BaseToDerived:
7467 case CK_DerivedToBase:
7468 case CK_UncheckedDerivedToBase:
7469 case CK_Dynamic:
7470 case CK_CPointerToObjCPointerCast:
7471 case CK_BlockPointerToObjCPointerCast:
7472 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007473 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007474
7475 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007476 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007477
Richard Trieudadefde2014-07-02 04:39:38 +00007478 case CK_BitCast:
7479 if (SubExpr->getType()->isAnyPointerType() ||
7480 SubExpr->getType()->isBlockPointerType() ||
7481 SubExpr->getType()->isObjCQualifiedIdType())
7482 return EvalAddr(SubExpr, refVars, ParentDecl);
7483 else
7484 return nullptr;
7485
Eli Friedman8195ad72012-02-23 23:04:32 +00007486 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007487 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00007488 }
Chris Lattner934edb22007-12-28 05:31:15 +00007489 }
Mike Stump11289f42009-09-09 15:08:12 +00007490
Douglas Gregorfe314812011-06-21 17:03:29 +00007491 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007492 if (const Expr *Result =
7493 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7494 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00007495 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00007496 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007497
Chris Lattner934edb22007-12-28 05:31:15 +00007498 // Everything else: we simply don't reason about them.
7499 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007500 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00007501 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007502}
Mike Stump11289f42009-09-09 15:08:12 +00007503
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007504/// EvalVal - This function is complements EvalAddr in the mutual recursion.
7505/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007506static const Expr *EvalVal(const Expr *E,
7507 SmallVectorImpl<const DeclRefExpr *> &refVars,
7508 const Decl *ParentDecl) {
7509 do {
7510 // We should only be called for evaluating non-pointer expressions, or
7511 // expressions with a pointer type that are not used as references but
7512 // instead
7513 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00007514
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007515 // Our "symbolic interpreter" is just a dispatch off the currently
7516 // viewed AST node. We then recursively traverse the AST by calling
7517 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00007518
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007519 E = E->IgnoreParens();
7520 switch (E->getStmtClass()) {
7521 case Stmt::ImplicitCastExprClass: {
7522 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7523 if (IE->getValueKind() == VK_LValue) {
7524 E = IE->getSubExpr();
7525 continue;
7526 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007527 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007528 }
Richard Smith40f08eb2014-01-30 22:05:38 +00007529
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007530 case Stmt::ExprWithCleanupsClass:
7531 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7532 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007533
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007534 case Stmt::DeclRefExprClass: {
7535 // When we hit a DeclRefExpr we are looking at code that refers to a
7536 // variable's name. If it's not a reference variable we check if it has
7537 // local storage within the function, and if so, return the expression.
7538 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7539
7540 // If we leave the immediate function, the lifetime isn't about to end.
7541 if (DR->refersToEnclosingVariableOrCapture())
7542 return nullptr;
7543
7544 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7545 // Check if it refers to itself, e.g. "int& i = i;".
7546 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007547 return DR;
7548
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007549 if (V->hasLocalStorage()) {
7550 if (!V->getType()->isReferenceType())
7551 return DR;
7552
7553 // Reference variable, follow through to the expression that
7554 // it points to.
7555 if (V->hasInit()) {
7556 // Add the reference variable to the "trail".
7557 refVars.push_back(DR);
7558 return EvalVal(V->getInit(), refVars, V);
7559 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007560 }
7561 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007562
7563 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007564 }
Mike Stump11289f42009-09-09 15:08:12 +00007565
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007566 case Stmt::UnaryOperatorClass: {
7567 // The only unary operator that make sense to handle here
7568 // is Deref. All others don't resolve to a "name." This includes
7569 // handling all sorts of rvalues passed to a unary operator.
7570 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007571
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007572 if (U->getOpcode() == UO_Deref)
7573 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007574
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007575 return nullptr;
7576 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007577
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007578 case Stmt::ArraySubscriptExprClass: {
7579 // Array subscripts are potential references to data on the stack. We
7580 // retrieve the DeclRefExpr* for the array variable if it indeed
7581 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00007582 const auto *ASE = cast<ArraySubscriptExpr>(E);
7583 if (ASE->isTypeDependent())
7584 return nullptr;
7585 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007586 }
Mike Stump11289f42009-09-09 15:08:12 +00007587
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007588 case Stmt::OMPArraySectionExprClass: {
7589 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7590 ParentDecl);
7591 }
Mike Stump11289f42009-09-09 15:08:12 +00007592
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007593 case Stmt::ConditionalOperatorClass: {
7594 // For conditional operators we need to see if either the LHS or RHS are
7595 // non-NULL Expr's. If one is non-NULL, we return it.
7596 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007597
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007598 // Handle the GNU extension for missing LHS.
7599 if (const Expr *LHSExpr = C->getLHS()) {
7600 // In C++, we can have a throw-expression, which has 'void' type.
7601 if (!LHSExpr->getType()->isVoidType())
7602 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7603 return LHS;
7604 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007605
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007606 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007607 if (C->getRHS()->getType()->isVoidType())
7608 return nullptr;
7609
7610 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007611 }
7612
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007613 // Accesses to members are potential references to data on the stack.
7614 case Stmt::MemberExprClass: {
7615 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00007616
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007617 // Check for indirect access. We only want direct field accesses.
7618 if (M->isArrow())
7619 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007620
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007621 // Check whether the member type is itself a reference, in which case
7622 // we're not going to refer to the member, but to what the member refers
7623 // to.
7624 if (M->getMemberDecl()->getType()->isReferenceType())
7625 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007626
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007627 return EvalVal(M->getBase(), refVars, ParentDecl);
7628 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00007629
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007630 case Stmt::MaterializeTemporaryExprClass:
7631 if (const Expr *Result =
7632 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7633 refVars, ParentDecl))
7634 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007635 return E;
7636
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007637 default:
7638 // Check that we don't return or take the address of a reference to a
7639 // temporary. This is only useful in C++.
7640 if (!E->isTypeDependent() && E->isRValue())
7641 return E;
7642
7643 // Everything else: we simply don't reason about them.
7644 return nullptr;
7645 }
7646 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007647}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007648
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007649void
7650Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7651 SourceLocation ReturnLoc,
7652 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00007653 const AttrVec *Attrs,
7654 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007655 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7656
7657 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00007658 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7659 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00007660 CheckNonNullExpr(*this, RetValExp))
7661 Diag(ReturnLoc, diag::warn_null_ret)
7662 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00007663
7664 // C++11 [basic.stc.dynamic.allocation]p4:
7665 // If an allocation function declared with a non-throwing
7666 // exception-specification fails to allocate storage, it shall return
7667 // a null pointer. Any other allocation function that fails to allocate
7668 // storage shall indicate failure only by throwing an exception [...]
7669 if (FD) {
7670 OverloadedOperatorKind Op = FD->getOverloadedOperator();
7671 if (Op == OO_New || Op == OO_Array_New) {
7672 const FunctionProtoType *Proto
7673 = FD->getType()->castAs<FunctionProtoType>();
7674 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7675 CheckNonNullExpr(*this, RetValExp))
7676 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7677 << FD << getLangOpts().CPlusPlus11;
7678 }
7679 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007680}
7681
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007682//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7683
7684/// Check for comparisons of floating point operands using != and ==.
7685/// Issue a warning if these are no self-comparisons, as they are not likely
7686/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00007687void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00007688 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7689 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007690
7691 // Special case: check for x == x (which is OK).
7692 // Do not emit warnings for such cases.
7693 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7694 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7695 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00007696 return;
Mike Stump11289f42009-09-09 15:08:12 +00007697
Ted Kremenekeda40e22007-11-29 00:59:04 +00007698 // Special case: check for comparisons against literals that can be exactly
7699 // represented by APFloat. In such cases, do not emit a warning. This
7700 // is a heuristic: often comparison against such literals are used to
7701 // detect if a value in a variable has not changed. This clearly can
7702 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00007703 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7704 if (FLL->isExact())
7705 return;
7706 } else
7707 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7708 if (FLR->isExact())
7709 return;
Mike Stump11289f42009-09-09 15:08:12 +00007710
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007711 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00007712 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007713 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007714 return;
Mike Stump11289f42009-09-09 15:08:12 +00007715
David Blaikie1f4ff152012-07-16 20:47:22 +00007716 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007717 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007718 return;
Mike Stump11289f42009-09-09 15:08:12 +00007719
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007720 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00007721 Diag(Loc, diag::warn_floatingpoint_eq)
7722 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007723}
John McCallca01b222010-01-04 23:21:16 +00007724
John McCall70aa5392010-01-06 05:24:50 +00007725//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7726//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00007727
John McCall70aa5392010-01-06 05:24:50 +00007728namespace {
John McCallca01b222010-01-04 23:21:16 +00007729
John McCall70aa5392010-01-06 05:24:50 +00007730/// Structure recording the 'active' range of an integer-valued
7731/// expression.
7732struct IntRange {
7733 /// The number of bits active in the int.
7734 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00007735
John McCall70aa5392010-01-06 05:24:50 +00007736 /// True if the int is known not to have negative values.
7737 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00007738
John McCall70aa5392010-01-06 05:24:50 +00007739 IntRange(unsigned Width, bool NonNegative)
7740 : Width(Width), NonNegative(NonNegative)
7741 {}
John McCallca01b222010-01-04 23:21:16 +00007742
John McCall817d4af2010-11-10 23:38:19 +00007743 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00007744 static IntRange forBoolType() {
7745 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00007746 }
7747
John McCall817d4af2010-11-10 23:38:19 +00007748 /// Returns the range of an opaque value of the given integral type.
7749 static IntRange forValueOfType(ASTContext &C, QualType T) {
7750 return forValueOfCanonicalType(C,
7751 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00007752 }
7753
John McCall817d4af2010-11-10 23:38:19 +00007754 /// Returns the range of an opaque value of a canonical integral type.
7755 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00007756 assert(T->isCanonicalUnqualified());
7757
7758 if (const VectorType *VT = dyn_cast<VectorType>(T))
7759 T = VT->getElementType().getTypePtr();
7760 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7761 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007762 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7763 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00007764
David Majnemer6a426652013-06-07 22:07:20 +00007765 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00007766 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00007767 EnumDecl *Enum = ET->getDecl();
7768 if (!Enum->isCompleteDefinition())
7769 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00007770
David Majnemer6a426652013-06-07 22:07:20 +00007771 unsigned NumPositive = Enum->getNumPositiveBits();
7772 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00007773
David Majnemer6a426652013-06-07 22:07:20 +00007774 if (NumNegative == 0)
7775 return IntRange(NumPositive, true/*NonNegative*/);
7776 else
7777 return IntRange(std::max(NumPositive + 1, NumNegative),
7778 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00007779 }
John McCall70aa5392010-01-06 05:24:50 +00007780
7781 const BuiltinType *BT = cast<BuiltinType>(T);
7782 assert(BT->isInteger());
7783
7784 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7785 }
7786
John McCall817d4af2010-11-10 23:38:19 +00007787 /// Returns the "target" range of a canonical integral type, i.e.
7788 /// the range of values expressible in the type.
7789 ///
7790 /// This matches forValueOfCanonicalType except that enums have the
7791 /// full range of their type, not the range of their enumerators.
7792 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7793 assert(T->isCanonicalUnqualified());
7794
7795 if (const VectorType *VT = dyn_cast<VectorType>(T))
7796 T = VT->getElementType().getTypePtr();
7797 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7798 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007799 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7800 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007801 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00007802 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007803
7804 const BuiltinType *BT = cast<BuiltinType>(T);
7805 assert(BT->isInteger());
7806
7807 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7808 }
7809
7810 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00007811 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00007812 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00007813 L.NonNegative && R.NonNegative);
7814 }
7815
John McCall817d4af2010-11-10 23:38:19 +00007816 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00007817 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00007818 return IntRange(std::min(L.Width, R.Width),
7819 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00007820 }
7821};
7822
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007823IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007824 if (value.isSigned() && value.isNegative())
7825 return IntRange(value.getMinSignedBits(), false);
7826
7827 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00007828 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007829
7830 // isNonNegative() just checks the sign bit without considering
7831 // signedness.
7832 return IntRange(value.getActiveBits(), true);
7833}
7834
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007835IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7836 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007837 if (result.isInt())
7838 return GetValueRange(C, result.getInt(), MaxWidth);
7839
7840 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00007841 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7842 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7843 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7844 R = IntRange::join(R, El);
7845 }
John McCall70aa5392010-01-06 05:24:50 +00007846 return R;
7847 }
7848
7849 if (result.isComplexInt()) {
7850 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7851 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7852 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00007853 }
7854
7855 // This can happen with lossless casts to intptr_t of "based" lvalues.
7856 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00007857 // FIXME: The only reason we need to pass the type in here is to get
7858 // the sign right on this one case. It would be nice if APValue
7859 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007860 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00007861 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00007862}
John McCall70aa5392010-01-06 05:24:50 +00007863
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007864QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007865 QualType Ty = E->getType();
7866 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7867 Ty = AtomicRHS->getValueType();
7868 return Ty;
7869}
7870
John McCall70aa5392010-01-06 05:24:50 +00007871/// Pseudo-evaluate the given integer expression, estimating the
7872/// range of values it might take.
7873///
7874/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007875IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007876 E = E->IgnoreParens();
7877
7878 // Try a full evaluation first.
7879 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007880 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00007881 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007882
7883 // I think we only want to look through implicit casts here; if the
7884 // user has an explicit widening cast, we should treat the value as
7885 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007886 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00007887 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00007888 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7889
Eli Friedmane6d33952013-07-08 20:20:06 +00007890 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00007891
George Burgess IVdf1ed002016-01-13 01:52:39 +00007892 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7893 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00007894
John McCall70aa5392010-01-06 05:24:50 +00007895 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00007896 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00007897 return OutputTypeRange;
7898
7899 IntRange SubRange
7900 = GetExprRange(C, CE->getSubExpr(),
7901 std::min(MaxWidth, OutputTypeRange.Width));
7902
7903 // Bail out if the subexpr's range is as wide as the cast type.
7904 if (SubRange.Width >= OutputTypeRange.Width)
7905 return OutputTypeRange;
7906
7907 // Otherwise, we take the smaller width, and we're non-negative if
7908 // either the output type or the subexpr is.
7909 return IntRange(SubRange.Width,
7910 SubRange.NonNegative || OutputTypeRange.NonNegative);
7911 }
7912
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007913 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007914 // If we can fold the condition, just take that operand.
7915 bool CondResult;
7916 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7917 return GetExprRange(C, CondResult ? CO->getTrueExpr()
7918 : CO->getFalseExpr(),
7919 MaxWidth);
7920
7921 // Otherwise, conservatively merge.
7922 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7923 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7924 return IntRange::join(L, R);
7925 }
7926
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007927 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007928 switch (BO->getOpcode()) {
7929
7930 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00007931 case BO_LAnd:
7932 case BO_LOr:
7933 case BO_LT:
7934 case BO_GT:
7935 case BO_LE:
7936 case BO_GE:
7937 case BO_EQ:
7938 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00007939 return IntRange::forBoolType();
7940
John McCallc3688382011-07-13 06:35:24 +00007941 // The type of the assignments is the type of the LHS, so the RHS
7942 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00007943 case BO_MulAssign:
7944 case BO_DivAssign:
7945 case BO_RemAssign:
7946 case BO_AddAssign:
7947 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00007948 case BO_XorAssign:
7949 case BO_OrAssign:
7950 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00007951 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00007952
John McCallc3688382011-07-13 06:35:24 +00007953 // Simple assignments just pass through the RHS, which will have
7954 // been coerced to the LHS type.
7955 case BO_Assign:
7956 // TODO: bitfields?
7957 return GetExprRange(C, BO->getRHS(), MaxWidth);
7958
John McCall70aa5392010-01-06 05:24:50 +00007959 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00007960 case BO_PtrMemD:
7961 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00007962 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007963
John McCall2ce81ad2010-01-06 22:07:33 +00007964 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00007965 case BO_And:
7966 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00007967 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
7968 GetExprRange(C, BO->getRHS(), MaxWidth));
7969
John McCall70aa5392010-01-06 05:24:50 +00007970 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00007971 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00007972 // ...except that we want to treat '1 << (blah)' as logically
7973 // positive. It's an important idiom.
7974 if (IntegerLiteral *I
7975 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
7976 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007977 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00007978 return IntRange(R.Width, /*NonNegative*/ true);
7979 }
7980 }
7981 // fallthrough
7982
John McCalle3027922010-08-25 11:45:40 +00007983 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00007984 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007985
John McCall2ce81ad2010-01-06 22:07:33 +00007986 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00007987 case BO_Shr:
7988 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00007989 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7990
7991 // If the shift amount is a positive constant, drop the width by
7992 // that much.
7993 llvm::APSInt shift;
7994 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
7995 shift.isNonNegative()) {
7996 unsigned zext = shift.getZExtValue();
7997 if (zext >= L.Width)
7998 L.Width = (L.NonNegative ? 0 : 1);
7999 else
8000 L.Width -= zext;
8001 }
8002
8003 return L;
8004 }
8005
8006 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008007 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008008 return GetExprRange(C, BO->getRHS(), MaxWidth);
8009
John McCall2ce81ad2010-01-06 22:07:33 +00008010 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008011 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008012 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008013 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008014 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008015
John McCall51431812011-07-14 22:39:48 +00008016 // The width of a division result is mostly determined by the size
8017 // of the LHS.
8018 case BO_Div: {
8019 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008020 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008021 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8022
8023 // If the divisor is constant, use that.
8024 llvm::APSInt divisor;
8025 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8026 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8027 if (log2 >= L.Width)
8028 L.Width = (L.NonNegative ? 0 : 1);
8029 else
8030 L.Width = std::min(L.Width - log2, MaxWidth);
8031 return L;
8032 }
8033
8034 // Otherwise, just use the LHS's width.
8035 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8036 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8037 }
8038
8039 // The result of a remainder can't be larger than the result of
8040 // either side.
8041 case BO_Rem: {
8042 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008043 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008044 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8045 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8046
8047 IntRange meet = IntRange::meet(L, R);
8048 meet.Width = std::min(meet.Width, MaxWidth);
8049 return meet;
8050 }
8051
8052 // The default behavior is okay for these.
8053 case BO_Mul:
8054 case BO_Add:
8055 case BO_Xor:
8056 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008057 break;
8058 }
8059
John McCall51431812011-07-14 22:39:48 +00008060 // The default case is to treat the operation as if it were closed
8061 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008062 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8063 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8064 return IntRange::join(L, R);
8065 }
8066
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008067 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008068 switch (UO->getOpcode()) {
8069 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008070 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008071 return IntRange::forBoolType();
8072
8073 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008074 case UO_Deref:
8075 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00008076 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008077
8078 default:
8079 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8080 }
8081 }
8082
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008083 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00008084 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8085
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008086 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00008087 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00008088 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00008089
Eli Friedmane6d33952013-07-08 20:20:06 +00008090 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008091}
John McCall263a48b2010-01-04 23:31:57 +00008092
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008093IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008094 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00008095}
8096
John McCall263a48b2010-01-04 23:31:57 +00008097/// Checks whether the given value, which currently has the given
8098/// source semantics, has the same value when coerced through the
8099/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008100bool IsSameFloatAfterCast(const llvm::APFloat &value,
8101 const llvm::fltSemantics &Src,
8102 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008103 llvm::APFloat truncated = value;
8104
8105 bool ignored;
8106 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8107 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8108
8109 return truncated.bitwiseIsEqual(value);
8110}
8111
8112/// Checks whether the given value, which currently has the given
8113/// source semantics, has the same value when coerced through the
8114/// target semantics.
8115///
8116/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008117bool IsSameFloatAfterCast(const APValue &value,
8118 const llvm::fltSemantics &Src,
8119 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008120 if (value.isFloat())
8121 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8122
8123 if (value.isVector()) {
8124 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8125 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8126 return false;
8127 return true;
8128 }
8129
8130 assert(value.isComplexFloat());
8131 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8132 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8133}
8134
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008135void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008136
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008137bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00008138 // Suppress cases where we are comparing against an enum constant.
8139 if (const DeclRefExpr *DR =
8140 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8141 if (isa<EnumConstantDecl>(DR->getDecl()))
8142 return false;
8143
8144 // Suppress cases where the '0' value is expanded from a macro.
8145 if (E->getLocStart().isMacroID())
8146 return false;
8147
John McCallcc7e5bf2010-05-06 08:58:33 +00008148 llvm::APSInt Value;
8149 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8150}
8151
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008152bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00008153 // Strip off implicit integral promotions.
8154 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008155 if (ICE->getCastKind() != CK_IntegralCast &&
8156 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00008157 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008158 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00008159 }
8160
8161 return E->getType()->isEnumeralType();
8162}
8163
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008164void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00008165 // Disable warning in template instantiations.
8166 if (!S.ActiveTemplateInstantiations.empty())
8167 return;
8168
John McCalle3027922010-08-25 11:45:40 +00008169 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00008170 if (E->isValueDependent())
8171 return;
8172
John McCalle3027922010-08-25 11:45:40 +00008173 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008174 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008175 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008176 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008177 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008178 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008179 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008180 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008181 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008182 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008183 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008184 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008185 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008186 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008187 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008188 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8189 }
8190}
8191
Benjamin Kramer7320b992016-06-15 14:20:56 +00008192void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8193 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008194 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00008195 // Disable warning in template instantiations.
8196 if (!S.ActiveTemplateInstantiations.empty())
8197 return;
8198
Richard Trieu0f097742014-04-04 04:13:47 +00008199 // TODO: Investigate using GetExprRange() to get tighter bounds
8200 // on the bit ranges.
8201 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00008202 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00008203 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00008204 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8205 unsigned OtherWidth = OtherRange.Width;
8206
8207 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8208
Richard Trieu560910c2012-11-14 22:50:24 +00008209 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00008210 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00008211 return;
8212
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008213 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00008214 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008215
Richard Trieu0f097742014-04-04 04:13:47 +00008216 // Used for diagnostic printout.
8217 enum {
8218 LiteralConstant = 0,
8219 CXXBoolLiteralTrue,
8220 CXXBoolLiteralFalse
8221 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008222
Richard Trieu0f097742014-04-04 04:13:47 +00008223 if (!OtherIsBooleanType) {
8224 QualType ConstantT = Constant->getType();
8225 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00008226
Richard Trieu0f097742014-04-04 04:13:47 +00008227 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8228 return;
8229 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8230 "comparison with non-integer type");
8231
8232 bool ConstantSigned = ConstantT->isSignedIntegerType();
8233 bool CommonSigned = CommonT->isSignedIntegerType();
8234
8235 bool EqualityOnly = false;
8236
8237 if (CommonSigned) {
8238 // The common type is signed, therefore no signed to unsigned conversion.
8239 if (!OtherRange.NonNegative) {
8240 // Check that the constant is representable in type OtherT.
8241 if (ConstantSigned) {
8242 if (OtherWidth >= Value.getMinSignedBits())
8243 return;
8244 } else { // !ConstantSigned
8245 if (OtherWidth >= Value.getActiveBits() + 1)
8246 return;
8247 }
8248 } else { // !OtherSigned
8249 // Check that the constant is representable in type OtherT.
8250 // Negative values are out of range.
8251 if (ConstantSigned) {
8252 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8253 return;
8254 } else { // !ConstantSigned
8255 if (OtherWidth >= Value.getActiveBits())
8256 return;
8257 }
Richard Trieu560910c2012-11-14 22:50:24 +00008258 }
Richard Trieu0f097742014-04-04 04:13:47 +00008259 } else { // !CommonSigned
8260 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00008261 if (OtherWidth >= Value.getActiveBits())
8262 return;
Craig Toppercf360162014-06-18 05:13:11 +00008263 } else { // OtherSigned
8264 assert(!ConstantSigned &&
8265 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00008266 // Check to see if the constant is representable in OtherT.
8267 if (OtherWidth > Value.getActiveBits())
8268 return;
8269 // Check to see if the constant is equivalent to a negative value
8270 // cast to CommonT.
8271 if (S.Context.getIntWidth(ConstantT) ==
8272 S.Context.getIntWidth(CommonT) &&
8273 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8274 return;
8275 // The constant value rests between values that OtherT can represent
8276 // after conversion. Relational comparison still works, but equality
8277 // comparisons will be tautological.
8278 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008279 }
8280 }
Richard Trieu0f097742014-04-04 04:13:47 +00008281
8282 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8283
8284 if (op == BO_EQ || op == BO_NE) {
8285 IsTrue = op == BO_NE;
8286 } else if (EqualityOnly) {
8287 return;
8288 } else if (RhsConstant) {
8289 if (op == BO_GT || op == BO_GE)
8290 IsTrue = !PositiveConstant;
8291 else // op == BO_LT || op == BO_LE
8292 IsTrue = PositiveConstant;
8293 } else {
8294 if (op == BO_LT || op == BO_LE)
8295 IsTrue = !PositiveConstant;
8296 else // op == BO_GT || op == BO_GE
8297 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008298 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008299 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00008300 // Other isKnownToHaveBooleanValue
8301 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8302 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8303 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8304
8305 static const struct LinkedConditions {
8306 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8307 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8308 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8309 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8310 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8311 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8312
8313 } TruthTable = {
8314 // Constant on LHS. | Constant on RHS. |
8315 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
8316 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8317 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8318 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8319 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8320 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8321 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8322 };
8323
8324 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8325
8326 enum ConstantValue ConstVal = Zero;
8327 if (Value.isUnsigned() || Value.isNonNegative()) {
8328 if (Value == 0) {
8329 LiteralOrBoolConstant =
8330 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8331 ConstVal = Zero;
8332 } else if (Value == 1) {
8333 LiteralOrBoolConstant =
8334 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8335 ConstVal = One;
8336 } else {
8337 LiteralOrBoolConstant = LiteralConstant;
8338 ConstVal = GT_One;
8339 }
8340 } else {
8341 ConstVal = LT_Zero;
8342 }
8343
8344 CompareBoolWithConstantResult CmpRes;
8345
8346 switch (op) {
8347 case BO_LT:
8348 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8349 break;
8350 case BO_GT:
8351 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8352 break;
8353 case BO_LE:
8354 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8355 break;
8356 case BO_GE:
8357 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8358 break;
8359 case BO_EQ:
8360 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8361 break;
8362 case BO_NE:
8363 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8364 break;
8365 default:
8366 CmpRes = Unkwn;
8367 break;
8368 }
8369
8370 if (CmpRes == AFals) {
8371 IsTrue = false;
8372 } else if (CmpRes == ATrue) {
8373 IsTrue = true;
8374 } else {
8375 return;
8376 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008377 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008378
8379 // If this is a comparison to an enum constant, include that
8380 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00008381 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008382 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8383 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8384
8385 SmallString<64> PrettySourceValue;
8386 llvm::raw_svector_ostream OS(PrettySourceValue);
8387 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00008388 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008389 else
8390 OS << Value;
8391
Richard Trieu0f097742014-04-04 04:13:47 +00008392 S.DiagRuntimeBehavior(
8393 E->getOperatorLoc(), E,
8394 S.PDiag(diag::warn_out_of_range_compare)
8395 << OS.str() << LiteralOrBoolConstant
8396 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8397 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008398}
8399
John McCallcc7e5bf2010-05-06 08:58:33 +00008400/// Analyze the operands of the given comparison. Implements the
8401/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008402void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00008403 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8404 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008405}
John McCall263a48b2010-01-04 23:31:57 +00008406
John McCallca01b222010-01-04 23:21:16 +00008407/// \brief Implements -Wsign-compare.
8408///
Richard Trieu82402a02011-09-15 21:56:47 +00008409/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008410void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008411 // The type the comparison is being performed in.
8412 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00008413
8414 // Only analyze comparison operators where both sides have been converted to
8415 // the same type.
8416 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8417 return AnalyzeImpConvsInComparison(S, E);
8418
8419 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00008420 if (E->isValueDependent())
8421 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008422
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008423 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8424 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008425
8426 bool IsComparisonConstant = false;
8427
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008428 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008429 // of 'true' or 'false'.
8430 if (T->isIntegralType(S.Context)) {
8431 llvm::APSInt RHSValue;
8432 bool IsRHSIntegralLiteral =
8433 RHS->isIntegerConstantExpr(RHSValue, S.Context);
8434 llvm::APSInt LHSValue;
8435 bool IsLHSIntegralLiteral =
8436 LHS->isIntegerConstantExpr(LHSValue, S.Context);
8437 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8438 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8439 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8440 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8441 else
8442 IsComparisonConstant =
8443 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008444 } else if (!T->hasUnsignedIntegerRepresentation())
8445 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008446
John McCallcc7e5bf2010-05-06 08:58:33 +00008447 // We don't do anything special if this isn't an unsigned integral
8448 // comparison: we're only interested in integral comparisons, and
8449 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00008450 //
8451 // We also don't care about value-dependent expressions or expressions
8452 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008453 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00008454 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008455
John McCallcc7e5bf2010-05-06 08:58:33 +00008456 // Check to see if one of the (unmodified) operands is of different
8457 // signedness.
8458 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00008459 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8460 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00008461 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00008462 signedOperand = LHS;
8463 unsignedOperand = RHS;
8464 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8465 signedOperand = RHS;
8466 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00008467 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00008468 CheckTrivialUnsignedComparison(S, E);
8469 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008470 }
8471
John McCallcc7e5bf2010-05-06 08:58:33 +00008472 // Otherwise, calculate the effective range of the signed operand.
8473 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00008474
John McCallcc7e5bf2010-05-06 08:58:33 +00008475 // Go ahead and analyze implicit conversions in the operands. Note
8476 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00008477 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8478 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00008479
John McCallcc7e5bf2010-05-06 08:58:33 +00008480 // If the signed range is non-negative, -Wsign-compare won't fire,
8481 // but we should still check for comparisons which are always true
8482 // or false.
8483 if (signedRange.NonNegative)
8484 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008485
8486 // For (in)equality comparisons, if the unsigned operand is a
8487 // constant which cannot collide with a overflowed signed operand,
8488 // then reinterpreting the signed operand as unsigned will not
8489 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00008490 if (E->isEqualityOp()) {
8491 unsigned comparisonWidth = S.Context.getIntWidth(T);
8492 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00008493
John McCallcc7e5bf2010-05-06 08:58:33 +00008494 // We should never be unable to prove that the unsigned operand is
8495 // non-negative.
8496 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8497
8498 if (unsignedRange.Width < comparisonWidth)
8499 return;
8500 }
8501
Douglas Gregorbfb4a212012-05-01 01:53:49 +00008502 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8503 S.PDiag(diag::warn_mixed_sign_comparison)
8504 << LHS->getType() << RHS->getType()
8505 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00008506}
8507
John McCall1f425642010-11-11 03:21:53 +00008508/// Analyzes an attempt to assign the given value to a bitfield.
8509///
8510/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008511bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8512 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00008513 assert(Bitfield->isBitField());
8514 if (Bitfield->isInvalidDecl())
8515 return false;
8516
John McCalldeebbcf2010-11-11 05:33:51 +00008517 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00008518 QualType BitfieldType = Bitfield->getType();
8519 if (BitfieldType->isBooleanType())
8520 return false;
8521
8522 if (BitfieldType->isEnumeralType()) {
8523 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
8524 // If the underlying enum type was not explicitly specified as an unsigned
8525 // type and the enum contain only positive values, MSVC++ will cause an
8526 // inconsistency by storing this as a signed type.
8527 if (S.getLangOpts().CPlusPlus11 &&
8528 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
8529 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
8530 BitfieldEnumDecl->getNumNegativeBits() == 0) {
8531 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
8532 << BitfieldEnumDecl->getNameAsString();
8533 }
8534 }
8535
John McCalldeebbcf2010-11-11 05:33:51 +00008536 if (Bitfield->getType()->isBooleanType())
8537 return false;
8538
Douglas Gregor789adec2011-02-04 13:09:01 +00008539 // Ignore value- or type-dependent expressions.
8540 if (Bitfield->getBitWidth()->isValueDependent() ||
8541 Bitfield->getBitWidth()->isTypeDependent() ||
8542 Init->isValueDependent() ||
8543 Init->isTypeDependent())
8544 return false;
8545
John McCall1f425642010-11-11 03:21:53 +00008546 Expr *OriginalInit = Init->IgnoreParenImpCasts();
8547
Richard Smith5fab0c92011-12-28 19:48:30 +00008548 llvm::APSInt Value;
8549 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00008550 return false;
8551
John McCall1f425642010-11-11 03:21:53 +00008552 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00008553 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00008554
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008555 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00008556 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008557 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8558 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00008559
John McCall1f425642010-11-11 03:21:53 +00008560 if (OriginalWidth <= FieldWidth)
8561 return false;
8562
Eli Friedmanc267a322012-01-26 23:11:39 +00008563 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00008564 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00008565 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00008566
Eli Friedmanc267a322012-01-26 23:11:39 +00008567 // Check whether the stored value is equal to the original value.
8568 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00008569 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00008570 return false;
8571
Eli Friedmanc267a322012-01-26 23:11:39 +00008572 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00008573 // therefore don't strictly fit into a signed bitfield of width 1.
8574 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00008575 return false;
8576
John McCall1f425642010-11-11 03:21:53 +00008577 std::string PrettyValue = Value.toString(10);
8578 std::string PrettyTrunc = TruncatedValue.toString(10);
8579
8580 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8581 << PrettyValue << PrettyTrunc << OriginalInit->getType()
8582 << Init->getSourceRange();
8583
8584 return true;
8585}
8586
John McCalld2a53122010-11-09 23:24:47 +00008587/// Analyze the given simple or compound assignment for warning-worthy
8588/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008589void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00008590 // Just recurse on the LHS.
8591 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8592
8593 // We want to recurse on the RHS as normal unless we're assigning to
8594 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00008595 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008596 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00008597 E->getOperatorLoc())) {
8598 // Recurse, ignoring any implicit conversions on the RHS.
8599 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8600 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00008601 }
8602 }
8603
8604 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8605}
8606
John McCall263a48b2010-01-04 23:31:57 +00008607/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008608void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8609 SourceLocation CContext, unsigned diag,
8610 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008611 if (pruneControlFlow) {
8612 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8613 S.PDiag(diag)
8614 << SourceType << T << E->getSourceRange()
8615 << SourceRange(CContext));
8616 return;
8617 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00008618 S.Diag(E->getExprLoc(), diag)
8619 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8620}
8621
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008622/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008623void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8624 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008625 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008626}
8627
Richard Trieube234c32016-04-21 21:04:55 +00008628
8629/// Diagnose an implicit cast from a floating point value to an integer value.
8630void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8631
8632 SourceLocation CContext) {
8633 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
8634 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
8635
8636 Expr *InnerE = E->IgnoreParenImpCasts();
8637 // We also want to warn on, e.g., "int i = -1.234"
8638 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8639 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8640 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8641
8642 const bool IsLiteral =
8643 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8644
8645 llvm::APFloat Value(0.0);
8646 bool IsConstant =
8647 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8648 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00008649 return DiagnoseImpCast(S, E, T, CContext,
8650 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00008651 }
8652
Chandler Carruth016ef402011-04-10 08:36:24 +00008653 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00008654
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00008655 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8656 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00008657 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8658 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00008659 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00008660 if (IsLiteral) return;
8661 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8662 PruneWarnings);
8663 }
8664
8665 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00008666 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00008667 // Warn on floating point literal to integer.
8668 DiagID = diag::warn_impcast_literal_float_to_integer;
8669 } else if (IntegerValue == 0) {
8670 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
8671 return DiagnoseImpCast(S, E, T, CContext,
8672 diag::warn_impcast_float_integer, PruneWarnings);
8673 }
8674 // Warn on non-zero to zero conversion.
8675 DiagID = diag::warn_impcast_float_to_integer_zero;
8676 } else {
8677 if (IntegerValue.isUnsigned()) {
8678 if (!IntegerValue.isMaxValue()) {
8679 return DiagnoseImpCast(S, E, T, CContext,
8680 diag::warn_impcast_float_integer, PruneWarnings);
8681 }
8682 } else { // IntegerValue.isSigned()
8683 if (!IntegerValue.isMaxSignedValue() &&
8684 !IntegerValue.isMinSignedValue()) {
8685 return DiagnoseImpCast(S, E, T, CContext,
8686 diag::warn_impcast_float_integer, PruneWarnings);
8687 }
8688 }
8689 // Warn on evaluatable floating point expression to integer conversion.
8690 DiagID = diag::warn_impcast_float_to_integer;
8691 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008692
Eli Friedman07185912013-08-29 23:44:43 +00008693 // FIXME: Force the precision of the source value down so we don't print
8694 // digits which are usually useless (we don't really care here if we
8695 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
8696 // would automatically print the shortest representation, but it's a bit
8697 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00008698 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00008699 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
8700 precision = (precision * 59 + 195) / 196;
8701 Value.toString(PrettySourceValue, precision);
8702
David Blaikie9b88cc02012-05-15 17:18:27 +00008703 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00008704 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00008705 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00008706 else
David Blaikie9b88cc02012-05-15 17:18:27 +00008707 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00008708
Richard Trieube234c32016-04-21 21:04:55 +00008709 if (PruneWarnings) {
8710 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8711 S.PDiag(DiagID)
8712 << E->getType() << T.getUnqualifiedType()
8713 << PrettySourceValue << PrettyTargetValue
8714 << E->getSourceRange() << SourceRange(CContext));
8715 } else {
8716 S.Diag(E->getExprLoc(), DiagID)
8717 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8718 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8719 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008720}
8721
John McCall18a2c2c2010-11-09 22:22:12 +00008722std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8723 if (!Range.Width) return "0";
8724
8725 llvm::APSInt ValueInRange = Value;
8726 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00008727 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00008728 return ValueInRange.toString(10);
8729}
8730
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008731bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008732 if (!isa<ImplicitCastExpr>(Ex))
8733 return false;
8734
8735 Expr *InnerE = Ex->IgnoreParenImpCasts();
8736 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8737 const Type *Source =
8738 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8739 if (Target->isDependentType())
8740 return false;
8741
8742 const BuiltinType *FloatCandidateBT =
8743 dyn_cast<BuiltinType>(ToBool ? Source : Target);
8744 const Type *BoolCandidateType = ToBool ? Target : Source;
8745
8746 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8747 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8748}
8749
8750void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8751 SourceLocation CC) {
8752 unsigned NumArgs = TheCall->getNumArgs();
8753 for (unsigned i = 0; i < NumArgs; ++i) {
8754 Expr *CurrA = TheCall->getArg(i);
8755 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8756 continue;
8757
8758 bool IsSwapped = ((i > 0) &&
8759 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8760 IsSwapped |= ((i < (NumArgs - 1)) &&
8761 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8762 if (IsSwapped) {
8763 // Warn on this floating-point to bool conversion.
8764 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8765 CurrA->getType(), CC,
8766 diag::warn_impcast_floating_point_to_bool);
8767 }
8768 }
8769}
8770
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008771void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00008772 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
8773 E->getExprLoc()))
8774 return;
8775
Richard Trieu09d6b802016-01-08 23:35:06 +00008776 // Don't warn on functions which have return type nullptr_t.
8777 if (isa<CallExpr>(E))
8778 return;
8779
Richard Trieu5b993502014-10-15 03:42:06 +00008780 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
8781 const Expr::NullPointerConstantKind NullKind =
8782 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
8783 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
8784 return;
8785
8786 // Return if target type is a safe conversion.
8787 if (T->isAnyPointerType() || T->isBlockPointerType() ||
8788 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8789 return;
8790
8791 SourceLocation Loc = E->getSourceRange().getBegin();
8792
Richard Trieu0a5e1662016-02-13 00:58:53 +00008793 // Venture through the macro stacks to get to the source of macro arguments.
8794 // The new location is a better location than the complete location that was
8795 // passed in.
8796 while (S.SourceMgr.isMacroArgExpansion(Loc))
8797 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8798
8799 while (S.SourceMgr.isMacroArgExpansion(CC))
8800 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8801
Richard Trieu5b993502014-10-15 03:42:06 +00008802 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00008803 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8804 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8805 Loc, S.SourceMgr, S.getLangOpts());
8806 if (MacroName == "NULL")
8807 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00008808 }
8809
8810 // Only warn if the null and context location are in the same macro expansion.
8811 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8812 return;
8813
8814 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8815 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8816 << FixItHint::CreateReplacement(Loc,
8817 S.getFixItZeroLiteralForType(T, Loc));
8818}
8819
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008820void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8821 ObjCArrayLiteral *ArrayLiteral);
8822void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8823 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00008824
8825/// Check a single element within a collection literal against the
8826/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008827void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8828 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008829 // Skip a bitcast to 'id' or qualified 'id'.
8830 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8831 if (ICE->getCastKind() == CK_BitCast &&
8832 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8833 Element = ICE->getSubExpr();
8834 }
8835
8836 QualType ElementType = Element->getType();
8837 ExprResult ElementResult(Element);
8838 if (ElementType->getAs<ObjCObjectPointerType>() &&
8839 S.CheckSingleAssignmentConstraints(TargetElementType,
8840 ElementResult,
8841 false, false)
8842 != Sema::Compatible) {
8843 S.Diag(Element->getLocStart(),
8844 diag::warn_objc_collection_literal_element)
8845 << ElementType << ElementKind << TargetElementType
8846 << Element->getSourceRange();
8847 }
8848
8849 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8850 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8851 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8852 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8853}
8854
8855/// Check an Objective-C array literal being converted to the given
8856/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008857void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8858 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008859 if (!S.NSArrayDecl)
8860 return;
8861
8862 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8863 if (!TargetObjCPtr)
8864 return;
8865
8866 if (TargetObjCPtr->isUnspecialized() ||
8867 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8868 != S.NSArrayDecl->getCanonicalDecl())
8869 return;
8870
8871 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8872 if (TypeArgs.size() != 1)
8873 return;
8874
8875 QualType TargetElementType = TypeArgs[0];
8876 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8877 checkObjCCollectionLiteralElement(S, TargetElementType,
8878 ArrayLiteral->getElement(I),
8879 0);
8880 }
8881}
8882
8883/// Check an Objective-C dictionary literal being converted to the given
8884/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008885void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8886 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008887 if (!S.NSDictionaryDecl)
8888 return;
8889
8890 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8891 if (!TargetObjCPtr)
8892 return;
8893
8894 if (TargetObjCPtr->isUnspecialized() ||
8895 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8896 != S.NSDictionaryDecl->getCanonicalDecl())
8897 return;
8898
8899 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8900 if (TypeArgs.size() != 2)
8901 return;
8902
8903 QualType TargetKeyType = TypeArgs[0];
8904 QualType TargetObjectType = TypeArgs[1];
8905 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8906 auto Element = DictionaryLiteral->getKeyValueElement(I);
8907 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8908 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8909 }
8910}
8911
Richard Trieufc404c72016-02-05 23:02:38 +00008912// Helper function to filter out cases for constant width constant conversion.
8913// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008914bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8915 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00008916 // If initializing from a constant, and the constant starts with '0',
8917 // then it is a binary, octal, or hexadecimal. Allow these constants
8918 // to fill all the bits, even if there is a sign change.
8919 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8920 const char FirstLiteralCharacter =
8921 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8922 if (FirstLiteralCharacter == '0')
8923 return false;
8924 }
8925
8926 // If the CC location points to a '{', and the type is char, then assume
8927 // assume it is an array initialization.
8928 if (CC.isValid() && T->isCharType()) {
8929 const char FirstContextCharacter =
8930 S.getSourceManager().getCharacterData(CC)[0];
8931 if (FirstContextCharacter == '{')
8932 return false;
8933 }
8934
8935 return true;
8936}
8937
John McCallcc7e5bf2010-05-06 08:58:33 +00008938void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00008939 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008940 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00008941
John McCallcc7e5bf2010-05-06 08:58:33 +00008942 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
8943 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
8944 if (Source == Target) return;
8945 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00008946
Chandler Carruthc22845a2011-07-26 05:40:03 +00008947 // If the conversion context location is invalid don't complain. We also
8948 // don't want to emit a warning if the issue occurs from the expansion of
8949 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
8950 // delay this check as long as possible. Once we detect we are in that
8951 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008952 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00008953 return;
8954
Richard Trieu021baa32011-09-23 20:10:00 +00008955 // Diagnose implicit casts to bool.
8956 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
8957 if (isa<StringLiteral>(E))
8958 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00008959 // and expressions, for instance, assert(0 && "error here"), are
8960 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00008961 return DiagnoseImpCast(S, E, T, CC,
8962 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00008963 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
8964 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
8965 // This covers the literal expressions that evaluate to Objective-C
8966 // objects.
8967 return DiagnoseImpCast(S, E, T, CC,
8968 diag::warn_impcast_objective_c_literal_to_bool);
8969 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008970 if (Source->isPointerType() || Source->canDecayToPointerType()) {
8971 // Warn on pointer to bool conversion that is always true.
8972 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
8973 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00008974 }
Richard Trieu021baa32011-09-23 20:10:00 +00008975 }
John McCall263a48b2010-01-04 23:31:57 +00008976
Douglas Gregor5054cb02015-07-07 03:58:22 +00008977 // Check implicit casts from Objective-C collection literals to specialized
8978 // collection types, e.g., NSArray<NSString *> *.
8979 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
8980 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
8981 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
8982 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
8983
John McCall263a48b2010-01-04 23:31:57 +00008984 // Strip vector types.
8985 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008986 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008987 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008988 return;
John McCallacf0ee52010-10-08 02:01:28 +00008989 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008990 }
Chris Lattneree7286f2011-06-14 04:51:15 +00008991
8992 // If the vector cast is cast between two vectors of the same size, it is
8993 // a bitcast, not a conversion.
8994 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
8995 return;
John McCall263a48b2010-01-04 23:31:57 +00008996
8997 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
8998 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
8999 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00009000 if (auto VecTy = dyn_cast<VectorType>(Target))
9001 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00009002
9003 // Strip complex types.
9004 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009005 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009006 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009007 return;
9008
John McCallacf0ee52010-10-08 02:01:28 +00009009 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009010 }
John McCall263a48b2010-01-04 23:31:57 +00009011
9012 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9013 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9014 }
9015
9016 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9017 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9018
9019 // If the source is floating point...
9020 if (SourceBT && SourceBT->isFloatingPoint()) {
9021 // ...and the target is floating point...
9022 if (TargetBT && TargetBT->isFloatingPoint()) {
9023 // ...then warn if we're dropping FP rank.
9024
9025 // Builtin FP kinds are ordered by increasing FP rank.
9026 if (SourceBT->getKind() > TargetBT->getKind()) {
9027 // Don't warn about float constants that are precisely
9028 // representable in the target type.
9029 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009030 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00009031 // Value might be a float, a float vector, or a float complex.
9032 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00009033 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9034 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00009035 return;
9036 }
9037
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009038 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009039 return;
9040
John McCallacf0ee52010-10-08 02:01:28 +00009041 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00009042 }
9043 // ... or possibly if we're increasing rank, too
9044 else if (TargetBT->getKind() > SourceBT->getKind()) {
9045 if (S.SourceMgr.isInSystemMacro(CC))
9046 return;
9047
9048 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00009049 }
9050 return;
9051 }
9052
Richard Trieube234c32016-04-21 21:04:55 +00009053 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00009054 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009055 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009056 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00009057
Richard Trieube234c32016-04-21 21:04:55 +00009058 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00009059 }
John McCall263a48b2010-01-04 23:31:57 +00009060
Richard Smith54894fd2015-12-30 01:06:52 +00009061 // Detect the case where a call result is converted from floating-point to
9062 // to bool, and the final argument to the call is converted from bool, to
9063 // discover this typo:
9064 //
9065 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9066 //
9067 // FIXME: This is an incredibly special case; is there some more general
9068 // way to detect this class of misplaced-parentheses bug?
9069 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009070 // Check last argument of function call to see if it is an
9071 // implicit cast from a type matching the type the result
9072 // is being cast to.
9073 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00009074 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009075 Expr *LastA = CEx->getArg(NumArgs - 1);
9076 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00009077 if (isa<ImplicitCastExpr>(LastA) &&
9078 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009079 // Warn on this floating-point to bool conversion
9080 DiagnoseImpCast(S, E, T, CC,
9081 diag::warn_impcast_floating_point_to_bool);
9082 }
9083 }
9084 }
John McCall263a48b2010-01-04 23:31:57 +00009085 return;
9086 }
9087
Richard Trieu5b993502014-10-15 03:42:06 +00009088 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00009089
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009090 S.DiscardMisalignedMemberAddress(Target, E);
9091
David Blaikie9366d2b2012-06-19 21:19:06 +00009092 if (!Source->isIntegerType() || !Target->isIntegerType())
9093 return;
9094
David Blaikie7555b6a2012-05-15 16:56:36 +00009095 // TODO: remove this early return once the false positives for constant->bool
9096 // in templates, macros, etc, are reduced or removed.
9097 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9098 return;
9099
John McCallcc7e5bf2010-05-06 08:58:33 +00009100 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00009101 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00009102
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009103 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00009104 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009105 // TODO: this should happen for bitfield stores, too.
9106 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00009107 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009108 if (S.SourceMgr.isInSystemMacro(CC))
9109 return;
9110
John McCall18a2c2c2010-11-09 22:22:12 +00009111 std::string PrettySourceValue = Value.toString(10);
9112 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009113
Ted Kremenek33ba9952011-10-22 02:37:33 +00009114 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9115 S.PDiag(diag::warn_impcast_integer_precision_constant)
9116 << PrettySourceValue << PrettyTargetValue
9117 << E->getType() << T << E->getSourceRange()
9118 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00009119 return;
9120 }
9121
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009122 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9123 if (S.SourceMgr.isInSystemMacro(CC))
9124 return;
9125
David Blaikie9455da02012-04-12 22:40:54 +00009126 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00009127 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9128 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00009129 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00009130 }
9131
Richard Trieudcb55572016-01-29 23:51:16 +00009132 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9133 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9134 // Warn when doing a signed to signed conversion, warn if the positive
9135 // source value is exactly the width of the target type, which will
9136 // cause a negative value to be stored.
9137
9138 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00009139 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9140 !S.SourceMgr.isInSystemMacro(CC)) {
9141 if (isSameWidthConstantConversion(S, E, T, CC)) {
9142 std::string PrettySourceValue = Value.toString(10);
9143 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00009144
Richard Trieufc404c72016-02-05 23:02:38 +00009145 S.DiagRuntimeBehavior(
9146 E->getExprLoc(), E,
9147 S.PDiag(diag::warn_impcast_integer_precision_constant)
9148 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9149 << E->getSourceRange() << clang::SourceRange(CC));
9150 return;
Richard Trieudcb55572016-01-29 23:51:16 +00009151 }
9152 }
Richard Trieufc404c72016-02-05 23:02:38 +00009153
Richard Trieudcb55572016-01-29 23:51:16 +00009154 // Fall through for non-constants to give a sign conversion warning.
9155 }
9156
John McCallcc7e5bf2010-05-06 08:58:33 +00009157 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9158 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9159 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009160 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009161 return;
9162
John McCallcc7e5bf2010-05-06 08:58:33 +00009163 unsigned DiagID = diag::warn_impcast_integer_sign;
9164
9165 // Traditionally, gcc has warned about this under -Wsign-compare.
9166 // We also want to warn about it in -Wconversion.
9167 // So if -Wconversion is off, use a completely identical diagnostic
9168 // in the sign-compare group.
9169 // The conditional-checking code will
9170 if (ICContext) {
9171 DiagID = diag::warn_impcast_integer_sign_conditional;
9172 *ICContext = true;
9173 }
9174
John McCallacf0ee52010-10-08 02:01:28 +00009175 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00009176 }
9177
Douglas Gregora78f1932011-02-22 02:45:07 +00009178 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00009179 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9180 // type, to give us better diagnostics.
9181 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009182 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00009183 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9184 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9185 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9186 SourceType = S.Context.getTypeDeclType(Enum);
9187 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9188 }
9189 }
9190
Douglas Gregora78f1932011-02-22 02:45:07 +00009191 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9192 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00009193 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9194 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009195 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009196 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009197 return;
9198
Douglas Gregor364f7db2011-03-12 00:14:31 +00009199 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00009200 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009201 }
John McCall263a48b2010-01-04 23:31:57 +00009202}
9203
David Blaikie18e9ac72012-05-15 21:57:38 +00009204void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9205 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009206
9207void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00009208 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009209 E = E->IgnoreParenImpCasts();
9210
9211 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00009212 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009213
John McCallacf0ee52010-10-08 02:01:28 +00009214 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009215 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009216 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00009217}
9218
David Blaikie18e9ac72012-05-15 21:57:38 +00009219void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9220 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00009221 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009222
9223 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00009224 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9225 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009226
9227 // If -Wconversion would have warned about either of the candidates
9228 // for a signedness conversion to the context type...
9229 if (!Suspicious) return;
9230
9231 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009232 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00009233 return;
9234
John McCallcc7e5bf2010-05-06 08:58:33 +00009235 // ...then check whether it would have warned about either of the
9236 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00009237 if (E->getType() == T) return;
9238
9239 Suspicious = false;
9240 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9241 E->getType(), CC, &Suspicious);
9242 if (!Suspicious)
9243 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00009244 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009245}
9246
Richard Trieu65724892014-11-15 06:37:39 +00009247/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9248/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009249void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00009250 if (S.getLangOpts().Bool)
9251 return;
9252 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9253}
9254
John McCallcc7e5bf2010-05-06 08:58:33 +00009255/// AnalyzeImplicitConversions - Find and report any interesting
9256/// implicit conversions in the given expression. There are a couple
9257/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009258void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00009259 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00009260 Expr *E = OrigE->IgnoreParenImpCasts();
9261
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00009262 if (E->isTypeDependent() || E->isValueDependent())
9263 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00009264
John McCallcc7e5bf2010-05-06 08:58:33 +00009265 // For conditional operators, we analyze the arguments as if they
9266 // were being fed directly into the output.
9267 if (isa<ConditionalOperator>(E)) {
9268 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00009269 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009270 return;
9271 }
9272
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009273 // Check implicit argument conversions for function calls.
9274 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9275 CheckImplicitArgumentConversions(S, Call, CC);
9276
John McCallcc7e5bf2010-05-06 08:58:33 +00009277 // Go ahead and check any implicit conversions we might have skipped.
9278 // The non-canonical typecheck is just an optimization;
9279 // CheckImplicitConversion will filter out dead implicit conversions.
9280 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009281 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009282
9283 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00009284
9285 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9286 // The bound subexpressions in a PseudoObjectExpr are not reachable
9287 // as transitive children.
9288 // FIXME: Use a more uniform representation for this.
9289 for (auto *SE : POE->semantics())
9290 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9291 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00009292 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00009293
John McCallcc7e5bf2010-05-06 08:58:33 +00009294 // Skip past explicit casts.
9295 if (isa<ExplicitCastExpr>(E)) {
9296 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00009297 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009298 }
9299
John McCalld2a53122010-11-09 23:24:47 +00009300 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9301 // Do a somewhat different check with comparison operators.
9302 if (BO->isComparisonOp())
9303 return AnalyzeComparison(S, BO);
9304
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009305 // And with simple assignments.
9306 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00009307 return AnalyzeAssignment(S, BO);
9308 }
John McCallcc7e5bf2010-05-06 08:58:33 +00009309
9310 // These break the otherwise-useful invariant below. Fortunately,
9311 // we don't really need to recurse into them, because any internal
9312 // expressions should have been analyzed already when they were
9313 // built into statements.
9314 if (isa<StmtExpr>(E)) return;
9315
9316 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00009317 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00009318
9319 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00009320 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00009321 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00009322 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00009323 for (Stmt *SubStmt : E->children()) {
9324 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00009325 if (!ChildExpr)
9326 continue;
9327
Richard Trieu955231d2014-01-25 01:10:35 +00009328 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00009329 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00009330 // Ignore checking string literals that are in logical and operators.
9331 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00009332 continue;
9333 AnalyzeImplicitConversions(S, ChildExpr, CC);
9334 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009335
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009336 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00009337 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9338 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009339 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00009340
9341 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9342 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009343 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009344 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009345
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009346 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9347 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00009348 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009349}
9350
9351} // end anonymous namespace
9352
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009353/// Diagnose integer type and any valid implicit convertion to it.
9354static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9355 // Taking into account implicit conversions,
9356 // allow any integer.
9357 if (!E->getType()->isIntegerType()) {
9358 S.Diag(E->getLocStart(),
9359 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9360 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009361 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009362 // Potentially emit standard warnings for implicit conversions if enabled
9363 // using -Wconversion.
9364 CheckImplicitConversion(S, E, IntT, E->getLocStart());
9365 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009366}
9367
Richard Trieuc1888e02014-06-28 23:25:37 +00009368// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9369// Returns true when emitting a warning about taking the address of a reference.
9370static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00009371 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00009372 E = E->IgnoreParenImpCasts();
9373
9374 const FunctionDecl *FD = nullptr;
9375
9376 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9377 if (!DRE->getDecl()->getType()->isReferenceType())
9378 return false;
9379 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9380 if (!M->getMemberDecl()->getType()->isReferenceType())
9381 return false;
9382 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00009383 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00009384 return false;
9385 FD = Call->getDirectCallee();
9386 } else {
9387 return false;
9388 }
9389
9390 SemaRef.Diag(E->getExprLoc(), PD);
9391
9392 // If possible, point to location of function.
9393 if (FD) {
9394 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9395 }
9396
9397 return true;
9398}
9399
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009400// Returns true if the SourceLocation is expanded from any macro body.
9401// Returns false if the SourceLocation is invalid, is from not in a macro
9402// expansion, or is from expanded from a top-level macro argument.
9403static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9404 if (Loc.isInvalid())
9405 return false;
9406
9407 while (Loc.isMacroID()) {
9408 if (SM.isMacroBodyExpansion(Loc))
9409 return true;
9410 Loc = SM.getImmediateMacroCallerLoc(Loc);
9411 }
9412
9413 return false;
9414}
9415
Richard Trieu3bb8b562014-02-26 02:36:06 +00009416/// \brief Diagnose pointers that are always non-null.
9417/// \param E the expression containing the pointer
9418/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9419/// compared to a null pointer
9420/// \param IsEqual True when the comparison is equal to a null pointer
9421/// \param Range Extra SourceRange to highlight in the diagnostic
9422void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9423 Expr::NullPointerConstantKind NullKind,
9424 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00009425 if (!E)
9426 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009427
9428 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009429 if (E->getExprLoc().isMacroID()) {
9430 const SourceManager &SM = getSourceManager();
9431 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9432 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00009433 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009434 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009435 E = E->IgnoreImpCasts();
9436
9437 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9438
Richard Trieuf7432752014-06-06 21:39:26 +00009439 if (isa<CXXThisExpr>(E)) {
9440 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9441 : diag::warn_this_bool_conversion;
9442 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9443 return;
9444 }
9445
Richard Trieu3bb8b562014-02-26 02:36:06 +00009446 bool IsAddressOf = false;
9447
9448 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9449 if (UO->getOpcode() != UO_AddrOf)
9450 return;
9451 IsAddressOf = true;
9452 E = UO->getSubExpr();
9453 }
9454
Richard Trieuc1888e02014-06-28 23:25:37 +00009455 if (IsAddressOf) {
9456 unsigned DiagID = IsCompare
9457 ? diag::warn_address_of_reference_null_compare
9458 : diag::warn_address_of_reference_bool_conversion;
9459 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9460 << IsEqual;
9461 if (CheckForReference(*this, E, PD)) {
9462 return;
9463 }
9464 }
9465
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009466 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9467 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00009468 std::string Str;
9469 llvm::raw_string_ostream S(Str);
9470 E->printPretty(S, nullptr, getPrintingPolicy());
9471 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9472 : diag::warn_cast_nonnull_to_bool;
9473 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9474 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009475 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00009476 };
9477
9478 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9479 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9480 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009481 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9482 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009483 return;
9484 }
9485 }
9486 }
9487
Richard Trieu3bb8b562014-02-26 02:36:06 +00009488 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00009489 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009490 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9491 D = R->getDecl();
9492 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9493 D = M->getMemberDecl();
9494 }
9495
9496 // Weak Decls can be null.
9497 if (!D || D->isWeak())
9498 return;
George Burgess IV850269a2015-12-08 22:02:00 +00009499
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009500 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00009501 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9502 if (getCurFunction() &&
9503 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009504 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9505 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009506 return;
9507 }
9508
9509 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +00009510 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +00009511 assert(ParamIter != FD->param_end());
9512 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9513
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009514 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9515 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009516 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +00009517 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009518 }
George Burgess IV850269a2015-12-08 22:02:00 +00009519
9520 for (unsigned ArgNo : NonNull->args()) {
9521 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009522 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009523 return;
9524 }
George Burgess IV850269a2015-12-08 22:02:00 +00009525 }
9526 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009527 }
9528 }
George Burgess IV850269a2015-12-08 22:02:00 +00009529 }
9530
Richard Trieu3bb8b562014-02-26 02:36:06 +00009531 QualType T = D->getType();
9532 const bool IsArray = T->isArrayType();
9533 const bool IsFunction = T->isFunctionType();
9534
Richard Trieuc1888e02014-06-28 23:25:37 +00009535 // Address of function is used to silence the function warning.
9536 if (IsAddressOf && IsFunction) {
9537 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009538 }
9539
9540 // Found nothing.
9541 if (!IsAddressOf && !IsFunction && !IsArray)
9542 return;
9543
9544 // Pretty print the expression for the diagnostic.
9545 std::string Str;
9546 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00009547 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00009548
9549 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9550 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00009551 enum {
9552 AddressOf,
9553 FunctionPointer,
9554 ArrayPointer
9555 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009556 if (IsAddressOf)
9557 DiagType = AddressOf;
9558 else if (IsFunction)
9559 DiagType = FunctionPointer;
9560 else if (IsArray)
9561 DiagType = ArrayPointer;
9562 else
9563 llvm_unreachable("Could not determine diagnostic.");
9564 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9565 << Range << IsEqual;
9566
9567 if (!IsFunction)
9568 return;
9569
9570 // Suggest '&' to silence the function warning.
9571 Diag(E->getExprLoc(), diag::note_function_warning_silence)
9572 << FixItHint::CreateInsertion(E->getLocStart(), "&");
9573
9574 // Check to see if '()' fixit should be emitted.
9575 QualType ReturnType;
9576 UnresolvedSet<4> NonTemplateOverloads;
9577 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9578 if (ReturnType.isNull())
9579 return;
9580
9581 if (IsCompare) {
9582 // There are two cases here. If there is null constant, the only suggest
9583 // for a pointer return type. If the null is 0, then suggest if the return
9584 // type is a pointer or an integer type.
9585 if (!ReturnType->isPointerType()) {
9586 if (NullKind == Expr::NPCK_ZeroExpression ||
9587 NullKind == Expr::NPCK_ZeroLiteral) {
9588 if (!ReturnType->isIntegerType())
9589 return;
9590 } else {
9591 return;
9592 }
9593 }
9594 } else { // !IsCompare
9595 // For function to bool, only suggest if the function pointer has bool
9596 // return type.
9597 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9598 return;
9599 }
9600 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00009601 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00009602}
9603
John McCallcc7e5bf2010-05-06 08:58:33 +00009604/// Diagnoses "dangerous" implicit conversions within the given
9605/// expression (which is a full expression). Implements -Wconversion
9606/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009607///
9608/// \param CC the "context" location of the implicit conversion, i.e.
9609/// the most location of the syntactic entity requiring the implicit
9610/// conversion
9611void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009612 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00009613 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00009614 return;
9615
9616 // Don't diagnose for value- or type-dependent expressions.
9617 if (E->isTypeDependent() || E->isValueDependent())
9618 return;
9619
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009620 // Check for array bounds violations in cases where the check isn't triggered
9621 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9622 // ArraySubscriptExpr is on the RHS of a variable initialization.
9623 CheckArrayAccess(E);
9624
John McCallacf0ee52010-10-08 02:01:28 +00009625 // This is not the right CC for (e.g.) a variable initialization.
9626 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009627}
9628
Richard Trieu65724892014-11-15 06:37:39 +00009629/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9630/// Input argument E is a logical expression.
9631void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9632 ::CheckBoolLikeConversion(*this, E, CC);
9633}
9634
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009635/// Diagnose when expression is an integer constant expression and its evaluation
9636/// results in integer overflow
9637void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00009638 // Use a work list to deal with nested struct initializers.
9639 SmallVector<Expr *, 2> Exprs(1, E);
9640
9641 do {
9642 Expr *E = Exprs.pop_back_val();
9643
9644 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9645 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9646 continue;
9647 }
9648
9649 if (auto InitList = dyn_cast<InitListExpr>(E))
9650 Exprs.append(InitList->inits().begin(), InitList->inits().end());
9651 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009652}
9653
Richard Smithc406cb72013-01-17 01:17:56 +00009654namespace {
9655/// \brief Visitor for expressions which looks for unsequenced operations on the
9656/// same object.
9657class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009658 typedef EvaluatedExprVisitor<SequenceChecker> Base;
9659
Richard Smithc406cb72013-01-17 01:17:56 +00009660 /// \brief A tree of sequenced regions within an expression. Two regions are
9661 /// unsequenced if one is an ancestor or a descendent of the other. When we
9662 /// finish processing an expression with sequencing, such as a comma
9663 /// expression, we fold its tree nodes into its parent, since they are
9664 /// unsequenced with respect to nodes we will visit later.
9665 class SequenceTree {
9666 struct Value {
9667 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9668 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +00009669 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +00009670 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009671 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00009672
9673 public:
9674 /// \brief A region within an expression which may be sequenced with respect
9675 /// to some other region.
9676 class Seq {
9677 explicit Seq(unsigned N) : Index(N) {}
9678 unsigned Index;
9679 friend class SequenceTree;
9680 public:
9681 Seq() : Index(0) {}
9682 };
9683
9684 SequenceTree() { Values.push_back(Value(0)); }
9685 Seq root() const { return Seq(0); }
9686
9687 /// \brief Create a new sequence of operations, which is an unsequenced
9688 /// subset of \p Parent. This sequence of operations is sequenced with
9689 /// respect to other children of \p Parent.
9690 Seq allocate(Seq Parent) {
9691 Values.push_back(Value(Parent.Index));
9692 return Seq(Values.size() - 1);
9693 }
9694
9695 /// \brief Merge a sequence of operations into its parent.
9696 void merge(Seq S) {
9697 Values[S.Index].Merged = true;
9698 }
9699
9700 /// \brief Determine whether two operations are unsequenced. This operation
9701 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9702 /// should have been merged into its parent as appropriate.
9703 bool isUnsequenced(Seq Cur, Seq Old) {
9704 unsigned C = representative(Cur.Index);
9705 unsigned Target = representative(Old.Index);
9706 while (C >= Target) {
9707 if (C == Target)
9708 return true;
9709 C = Values[C].Parent;
9710 }
9711 return false;
9712 }
9713
9714 private:
9715 /// \brief Pick a representative for a sequence.
9716 unsigned representative(unsigned K) {
9717 if (Values[K].Merged)
9718 // Perform path compression as we go.
9719 return Values[K].Parent = representative(Values[K].Parent);
9720 return K;
9721 }
9722 };
9723
9724 /// An object for which we can track unsequenced uses.
9725 typedef NamedDecl *Object;
9726
9727 /// Different flavors of object usage which we track. We only track the
9728 /// least-sequenced usage of each kind.
9729 enum UsageKind {
9730 /// A read of an object. Multiple unsequenced reads are OK.
9731 UK_Use,
9732 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00009733 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00009734 UK_ModAsValue,
9735 /// A modification of an object which is not sequenced before the value
9736 /// computation of the expression, such as n++.
9737 UK_ModAsSideEffect,
9738
9739 UK_Count = UK_ModAsSideEffect + 1
9740 };
9741
9742 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00009743 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00009744 Expr *Use;
9745 SequenceTree::Seq Seq;
9746 };
9747
9748 struct UsageInfo {
9749 UsageInfo() : Diagnosed(false) {}
9750 Usage Uses[UK_Count];
9751 /// Have we issued a diagnostic for this variable already?
9752 bool Diagnosed;
9753 };
9754 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9755
9756 Sema &SemaRef;
9757 /// Sequenced regions within the expression.
9758 SequenceTree Tree;
9759 /// Declaration modifications and references which we have seen.
9760 UsageInfoMap UsageMap;
9761 /// The region we are currently within.
9762 SequenceTree::Seq Region;
9763 /// Filled in with declarations which were modified as a side-effect
9764 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009765 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00009766 /// Expressions to check later. We defer checking these to reduce
9767 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009768 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00009769
9770 /// RAII object wrapping the visitation of a sequenced subexpression of an
9771 /// expression. At the end of this process, the side-effects of the evaluation
9772 /// become sequenced with respect to the value computation of the result, so
9773 /// we downgrade any UK_ModAsSideEffect within the evaluation to
9774 /// UK_ModAsValue.
9775 struct SequencedSubexpression {
9776 SequencedSubexpression(SequenceChecker &Self)
9777 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9778 Self.ModAsSideEffect = &ModAsSideEffect;
9779 }
9780 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +00009781 for (auto &M : llvm::reverse(ModAsSideEffect)) {
9782 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +00009783 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +00009784 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9785 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +00009786 }
9787 Self.ModAsSideEffect = OldModAsSideEffect;
9788 }
9789
9790 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009791 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9792 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00009793 };
9794
Richard Smith40238f02013-06-20 22:21:56 +00009795 /// RAII object wrapping the visitation of a subexpression which we might
9796 /// choose to evaluate as a constant. If any subexpression is evaluated and
9797 /// found to be non-constant, this allows us to suppress the evaluation of
9798 /// the outer expression.
9799 class EvaluationTracker {
9800 public:
9801 EvaluationTracker(SequenceChecker &Self)
9802 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9803 Self.EvalTracker = this;
9804 }
9805 ~EvaluationTracker() {
9806 Self.EvalTracker = Prev;
9807 if (Prev)
9808 Prev->EvalOK &= EvalOK;
9809 }
9810
9811 bool evaluate(const Expr *E, bool &Result) {
9812 if (!EvalOK || E->isValueDependent())
9813 return false;
9814 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9815 return EvalOK;
9816 }
9817
9818 private:
9819 SequenceChecker &Self;
9820 EvaluationTracker *Prev;
9821 bool EvalOK;
9822 } *EvalTracker;
9823
Richard Smithc406cb72013-01-17 01:17:56 +00009824 /// \brief Find the object which is produced by the specified expression,
9825 /// if any.
9826 Object getObject(Expr *E, bool Mod) const {
9827 E = E->IgnoreParenCasts();
9828 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9829 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9830 return getObject(UO->getSubExpr(), Mod);
9831 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9832 if (BO->getOpcode() == BO_Comma)
9833 return getObject(BO->getRHS(), Mod);
9834 if (Mod && BO->isAssignmentOp())
9835 return getObject(BO->getLHS(), Mod);
9836 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9837 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9838 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9839 return ME->getMemberDecl();
9840 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9841 // FIXME: If this is a reference, map through to its value.
9842 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00009843 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00009844 }
9845
9846 /// \brief Note that an object was modified or used by an expression.
9847 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9848 Usage &U = UI.Uses[UK];
9849 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9850 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9851 ModAsSideEffect->push_back(std::make_pair(O, U));
9852 U.Use = Ref;
9853 U.Seq = Region;
9854 }
9855 }
9856 /// \brief Check whether a modification or use conflicts with a prior usage.
9857 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9858 bool IsModMod) {
9859 if (UI.Diagnosed)
9860 return;
9861
9862 const Usage &U = UI.Uses[OtherKind];
9863 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9864 return;
9865
9866 Expr *Mod = U.Use;
9867 Expr *ModOrUse = Ref;
9868 if (OtherKind == UK_Use)
9869 std::swap(Mod, ModOrUse);
9870
9871 SemaRef.Diag(Mod->getExprLoc(),
9872 IsModMod ? diag::warn_unsequenced_mod_mod
9873 : diag::warn_unsequenced_mod_use)
9874 << O << SourceRange(ModOrUse->getExprLoc());
9875 UI.Diagnosed = true;
9876 }
9877
9878 void notePreUse(Object O, Expr *Use) {
9879 UsageInfo &U = UsageMap[O];
9880 // Uses conflict with other modifications.
9881 checkUsage(O, U, Use, UK_ModAsValue, false);
9882 }
9883 void notePostUse(Object O, Expr *Use) {
9884 UsageInfo &U = UsageMap[O];
9885 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9886 addUsage(U, O, Use, UK_Use);
9887 }
9888
9889 void notePreMod(Object O, Expr *Mod) {
9890 UsageInfo &U = UsageMap[O];
9891 // Modifications conflict with other modifications and with uses.
9892 checkUsage(O, U, Mod, UK_ModAsValue, true);
9893 checkUsage(O, U, Mod, UK_Use, false);
9894 }
9895 void notePostMod(Object O, Expr *Use, UsageKind UK) {
9896 UsageInfo &U = UsageMap[O];
9897 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9898 addUsage(U, O, Use, UK);
9899 }
9900
9901public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009902 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00009903 : Base(S.Context), SemaRef(S), Region(Tree.root()),
9904 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009905 Visit(E);
9906 }
9907
9908 void VisitStmt(Stmt *S) {
9909 // Skip all statements which aren't expressions for now.
9910 }
9911
9912 void VisitExpr(Expr *E) {
9913 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00009914 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00009915 }
9916
9917 void VisitCastExpr(CastExpr *E) {
9918 Object O = Object();
9919 if (E->getCastKind() == CK_LValueToRValue)
9920 O = getObject(E->getSubExpr(), false);
9921
9922 if (O)
9923 notePreUse(O, E);
9924 VisitExpr(E);
9925 if (O)
9926 notePostUse(O, E);
9927 }
9928
9929 void VisitBinComma(BinaryOperator *BO) {
9930 // C++11 [expr.comma]p1:
9931 // Every value computation and side effect associated with the left
9932 // expression is sequenced before every value computation and side
9933 // effect associated with the right expression.
9934 SequenceTree::Seq LHS = Tree.allocate(Region);
9935 SequenceTree::Seq RHS = Tree.allocate(Region);
9936 SequenceTree::Seq OldRegion = Region;
9937
9938 {
9939 SequencedSubexpression SeqLHS(*this);
9940 Region = LHS;
9941 Visit(BO->getLHS());
9942 }
9943
9944 Region = RHS;
9945 Visit(BO->getRHS());
9946
9947 Region = OldRegion;
9948
9949 // Forget that LHS and RHS are sequenced. They are both unsequenced
9950 // with respect to other stuff.
9951 Tree.merge(LHS);
9952 Tree.merge(RHS);
9953 }
9954
9955 void VisitBinAssign(BinaryOperator *BO) {
9956 // The modification is sequenced after the value computation of the LHS
9957 // and RHS, so check it before inspecting the operands and update the
9958 // map afterwards.
9959 Object O = getObject(BO->getLHS(), true);
9960 if (!O)
9961 return VisitExpr(BO);
9962
9963 notePreMod(O, BO);
9964
9965 // C++11 [expr.ass]p7:
9966 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
9967 // only once.
9968 //
9969 // Therefore, for a compound assignment operator, O is considered used
9970 // everywhere except within the evaluation of E1 itself.
9971 if (isa<CompoundAssignOperator>(BO))
9972 notePreUse(O, BO);
9973
9974 Visit(BO->getLHS());
9975
9976 if (isa<CompoundAssignOperator>(BO))
9977 notePostUse(O, BO);
9978
9979 Visit(BO->getRHS());
9980
Richard Smith83e37bee2013-06-26 23:16:51 +00009981 // C++11 [expr.ass]p1:
9982 // the assignment is sequenced [...] before the value computation of the
9983 // assignment expression.
9984 // C11 6.5.16/3 has no such rule.
9985 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9986 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00009987 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009988
Richard Smithc406cb72013-01-17 01:17:56 +00009989 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
9990 VisitBinAssign(CAO);
9991 }
9992
9993 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9994 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9995 void VisitUnaryPreIncDec(UnaryOperator *UO) {
9996 Object O = getObject(UO->getSubExpr(), true);
9997 if (!O)
9998 return VisitExpr(UO);
9999
10000 notePreMod(O, UO);
10001 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000010002 // C++11 [expr.pre.incr]p1:
10003 // the expression ++x is equivalent to x+=1
10004 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10005 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010006 }
10007
10008 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10009 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10010 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10011 Object O = getObject(UO->getSubExpr(), true);
10012 if (!O)
10013 return VisitExpr(UO);
10014
10015 notePreMod(O, UO);
10016 Visit(UO->getSubExpr());
10017 notePostMod(O, UO, UK_ModAsSideEffect);
10018 }
10019
10020 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10021 void VisitBinLOr(BinaryOperator *BO) {
10022 // The side-effects of the LHS of an '&&' are sequenced before the
10023 // value computation of the RHS, and hence before the value computation
10024 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10025 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000010026 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010027 {
10028 SequencedSubexpression Sequenced(*this);
10029 Visit(BO->getLHS());
10030 }
10031
10032 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010033 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010034 if (!Result)
10035 Visit(BO->getRHS());
10036 } else {
10037 // Check for unsequenced operations in the RHS, treating it as an
10038 // entirely separate evaluation.
10039 //
10040 // FIXME: If there are operations in the RHS which are unsequenced
10041 // with respect to operations outside the RHS, and those operations
10042 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000010043 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010044 }
Richard Smithc406cb72013-01-17 01:17:56 +000010045 }
10046 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000010047 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010048 {
10049 SequencedSubexpression Sequenced(*this);
10050 Visit(BO->getLHS());
10051 }
10052
10053 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010054 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010055 if (Result)
10056 Visit(BO->getRHS());
10057 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000010058 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010059 }
Richard Smithc406cb72013-01-17 01:17:56 +000010060 }
10061
10062 // Only visit the condition, unless we can be sure which subexpression will
10063 // be chosen.
10064 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000010065 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000010066 {
10067 SequencedSubexpression Sequenced(*this);
10068 Visit(CO->getCond());
10069 }
Richard Smithc406cb72013-01-17 01:17:56 +000010070
10071 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010072 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000010073 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010074 else {
Richard Smithd33f5202013-01-17 23:18:09 +000010075 WorkList.push_back(CO->getTrueExpr());
10076 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010077 }
Richard Smithc406cb72013-01-17 01:17:56 +000010078 }
10079
Richard Smithe3dbfe02013-06-30 10:40:20 +000010080 void VisitCallExpr(CallExpr *CE) {
10081 // C++11 [intro.execution]p15:
10082 // When calling a function [...], every value computation and side effect
10083 // associated with any argument expression, or with the postfix expression
10084 // designating the called function, is sequenced before execution of every
10085 // expression or statement in the body of the function [and thus before
10086 // the value computation of its result].
10087 SequencedSubexpression Sequenced(*this);
10088 Base::VisitCallExpr(CE);
10089
10090 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10091 }
10092
Richard Smithc406cb72013-01-17 01:17:56 +000010093 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010094 // This is a call, so all subexpressions are sequenced before the result.
10095 SequencedSubexpression Sequenced(*this);
10096
Richard Smithc406cb72013-01-17 01:17:56 +000010097 if (!CCE->isListInitialization())
10098 return VisitExpr(CCE);
10099
10100 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010101 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010102 SequenceTree::Seq Parent = Region;
10103 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10104 E = CCE->arg_end();
10105 I != E; ++I) {
10106 Region = Tree.allocate(Parent);
10107 Elts.push_back(Region);
10108 Visit(*I);
10109 }
10110
10111 // Forget that the initializers are sequenced.
10112 Region = Parent;
10113 for (unsigned I = 0; I < Elts.size(); ++I)
10114 Tree.merge(Elts[I]);
10115 }
10116
10117 void VisitInitListExpr(InitListExpr *ILE) {
10118 if (!SemaRef.getLangOpts().CPlusPlus11)
10119 return VisitExpr(ILE);
10120
10121 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010122 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010123 SequenceTree::Seq Parent = Region;
10124 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10125 Expr *E = ILE->getInit(I);
10126 if (!E) continue;
10127 Region = Tree.allocate(Parent);
10128 Elts.push_back(Region);
10129 Visit(E);
10130 }
10131
10132 // Forget that the initializers are sequenced.
10133 Region = Parent;
10134 for (unsigned I = 0; I < Elts.size(); ++I)
10135 Tree.merge(Elts[I]);
10136 }
10137};
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010138} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +000010139
10140void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010141 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000010142 WorkList.push_back(E);
10143 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000010144 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000010145 SequenceChecker(*this, Item, WorkList);
10146 }
Richard Smithc406cb72013-01-17 01:17:56 +000010147}
10148
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010149void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10150 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010151 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000010152 if (!E->isInstantiationDependent())
10153 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010154 if (!IsConstexpr && !E->isValueDependent())
10155 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010156 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000010157}
10158
John McCall1f425642010-11-11 03:21:53 +000010159void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10160 FieldDecl *BitField,
10161 Expr *Init) {
10162 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10163}
10164
David Majnemer61a5bbf2015-04-07 22:08:51 +000010165static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10166 SourceLocation Loc) {
10167 if (!PType->isVariablyModifiedType())
10168 return;
10169 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10170 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10171 return;
10172 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000010173 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10174 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10175 return;
10176 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000010177 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10178 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10179 return;
10180 }
10181
10182 const ArrayType *AT = S.Context.getAsArrayType(PType);
10183 if (!AT)
10184 return;
10185
10186 if (AT->getSizeModifier() != ArrayType::Star) {
10187 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10188 return;
10189 }
10190
10191 S.Diag(Loc, diag::err_array_star_in_function_definition);
10192}
10193
Mike Stump0c2ec772010-01-21 03:59:47 +000010194/// CheckParmsForFunctionDef - Check that the parameters of the given
10195/// function are appropriate for the definition of a function. This
10196/// takes care of any checks that cannot be performed on the
10197/// declaration itself, e.g., that the types of each of the function
10198/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000010199bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000010200 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010201 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000010202 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010203 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10204 // function declarator that is part of a function definition of
10205 // that function shall not have incomplete type.
10206 //
10207 // This is also C++ [dcl.fct]p6.
10208 if (!Param->isInvalidDecl() &&
10209 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010210 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010211 Param->setInvalidDecl();
10212 HasInvalidParm = true;
10213 }
10214
10215 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10216 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000010217 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000010218 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000010219 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000010220 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000010221 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000010222
10223 // C99 6.7.5.3p12:
10224 // If the function declarator is not part of a definition of that
10225 // function, parameters may have incomplete type and may use the [*]
10226 // notation in their sequences of declarator specifiers to specify
10227 // variable length array types.
10228 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000010229 // FIXME: This diagnostic should point the '[*]' if source-location
10230 // information is added for it.
10231 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010232
10233 // MSVC destroys objects passed by value in the callee. Therefore a
10234 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010235 // object's destructor. However, we don't perform any direct access check
10236 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +000010237 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10238 .getCXXABI()
10239 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +000010240 if (!Param->isInvalidDecl()) {
10241 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10242 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10243 if (!ClassDecl->isInvalidDecl() &&
10244 !ClassDecl->hasIrrelevantDestructor() &&
10245 !ClassDecl->isDependentContext()) {
10246 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10247 MarkFunctionReferenced(Param->getLocation(), Destructor);
10248 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10249 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010250 }
10251 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010252 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010253
10254 // Parameters with the pass_object_size attribute only need to be marked
10255 // constant at function definitions. Because we lack information about
10256 // whether we're on a declaration or definition when we're instantiating the
10257 // attribute, we need to check for constness here.
10258 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10259 if (!Param->getType().isConstQualified())
10260 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10261 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000010262 }
10263
10264 return HasInvalidParm;
10265}
John McCall2b5c1b22010-08-12 21:44:57 +000010266
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010267/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10268/// or MemberExpr.
10269static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10270 ASTContext &Context) {
10271 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10272 return Context.getDeclAlign(DRE->getDecl());
10273
10274 if (const auto *ME = dyn_cast<MemberExpr>(E))
10275 return Context.getDeclAlign(ME->getMemberDecl());
10276
10277 return TypeAlign;
10278}
10279
John McCall2b5c1b22010-08-12 21:44:57 +000010280/// CheckCastAlign - Implements -Wcast-align, which warns when a
10281/// pointer cast increases the alignment requirements.
10282void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10283 // This is actually a lot of work to potentially be doing on every
10284 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010285 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000010286 return;
10287
10288 // Ignore dependent types.
10289 if (T->isDependentType() || Op->getType()->isDependentType())
10290 return;
10291
10292 // Require that the destination be a pointer type.
10293 const PointerType *DestPtr = T->getAs<PointerType>();
10294 if (!DestPtr) return;
10295
10296 // If the destination has alignment 1, we're done.
10297 QualType DestPointee = DestPtr->getPointeeType();
10298 if (DestPointee->isIncompleteType()) return;
10299 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10300 if (DestAlign.isOne()) return;
10301
10302 // Require that the source be a pointer type.
10303 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10304 if (!SrcPtr) return;
10305 QualType SrcPointee = SrcPtr->getPointeeType();
10306
10307 // Whitelist casts from cv void*. We already implicitly
10308 // whitelisted casts to cv void*, since they have alignment 1.
10309 // Also whitelist casts involving incomplete types, which implicitly
10310 // includes 'void'.
10311 if (SrcPointee->isIncompleteType()) return;
10312
10313 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010314
10315 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10316 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10317 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10318 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10319 if (UO->getOpcode() == UO_AddrOf)
10320 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10321 }
10322
John McCall2b5c1b22010-08-12 21:44:57 +000010323 if (SrcAlign >= DestAlign) return;
10324
10325 Diag(TRange.getBegin(), diag::warn_cast_align)
10326 << Op->getType() << T
10327 << static_cast<unsigned>(SrcAlign.getQuantity())
10328 << static_cast<unsigned>(DestAlign.getQuantity())
10329 << TRange << Op->getSourceRange();
10330}
10331
Chandler Carruth28389f02011-08-05 09:10:50 +000010332/// \brief Check whether this array fits the idiom of a size-one tail padded
10333/// array member of a struct.
10334///
10335/// We avoid emitting out-of-bounds access warnings for such arrays as they are
10336/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000010337static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000010338 const NamedDecl *ND) {
10339 if (Size != 1 || !ND) return false;
10340
10341 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10342 if (!FD) return false;
10343
10344 // Don't consider sizes resulting from macro expansions or template argument
10345 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000010346
10347 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010348 while (TInfo) {
10349 TypeLoc TL = TInfo->getTypeLoc();
10350 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000010351 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10352 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010353 TInfo = TDL->getTypeSourceInfo();
10354 continue;
10355 }
David Blaikie6adc78e2013-02-18 22:06:02 +000010356 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10357 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000010358 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10359 return false;
10360 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010361 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000010362 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010363
10364 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000010365 if (!RD) return false;
10366 if (RD->isUnion()) return false;
10367 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10368 if (!CRD->isStandardLayout()) return false;
10369 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010370
Benjamin Kramer8c543672011-08-06 03:04:42 +000010371 // See if this is the last field decl in the record.
10372 const Decl *D = FD;
10373 while ((D = D->getNextDeclInContext()))
10374 if (isa<FieldDecl>(D))
10375 return false;
10376 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000010377}
10378
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010379void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010380 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000010381 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010382 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010383 if (IndexExpr->isValueDependent())
10384 return;
10385
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010386 const Type *EffectiveType =
10387 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010388 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010389 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010390 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010391 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000010392 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000010393
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010394 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000010395 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000010396 return;
Richard Smith13f67182011-12-16 19:31:14 +000010397 if (IndexNegated)
10398 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000010399
Craig Topperc3ec1492014-05-26 06:22:03 +000010400 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000010401 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10402 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +000010403 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +000010404 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +000010405
Ted Kremeneke4b316c2011-02-23 23:06:04 +000010406 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010407 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000010408 if (!size.isStrictlyPositive())
10409 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010410
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010411 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000010412 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010413 // Make sure we're comparing apples to apples when comparing index to size
10414 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10415 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000010416 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000010417 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010418 if (ptrarith_typesize != array_typesize) {
10419 // There's a cast to a different size type involved
10420 uint64_t ratio = array_typesize / ptrarith_typesize;
10421 // TODO: Be smarter about handling cases where array_typesize is not a
10422 // multiple of ptrarith_typesize
10423 if (ptrarith_typesize * ratio == array_typesize)
10424 size *= llvm::APInt(size.getBitWidth(), ratio);
10425 }
10426 }
10427
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010428 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010429 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010430 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010431 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010432
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010433 // For array subscripting the index must be less than size, but for pointer
10434 // arithmetic also allow the index (offset) to be equal to size since
10435 // computing the next address after the end of the array is legal and
10436 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010437 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000010438 return;
10439
10440 // Also don't warn for arrays of size 1 which are members of some
10441 // structure. These are often used to approximate flexible arrays in C89
10442 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010443 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000010444 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010445
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010446 // Suppress the warning if the subscript expression (as identified by the
10447 // ']' location) and the index expression are both from macro expansions
10448 // within a system header.
10449 if (ASE) {
10450 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10451 ASE->getRBracketLoc());
10452 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10453 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10454 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000010455 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010456 return;
10457 }
10458 }
10459
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010460 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010461 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010462 DiagID = diag::warn_array_index_exceeds_bounds;
10463
10464 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10465 PDiag(DiagID) << index.toString(10, true)
10466 << size.toString(10, true)
10467 << (unsigned)size.getLimitedValue(~0U)
10468 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010469 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010470 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010471 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010472 DiagID = diag::warn_ptr_arith_precedes_bounds;
10473 if (index.isNegative()) index = -index;
10474 }
10475
10476 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10477 PDiag(DiagID) << index.toString(10, true)
10478 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000010479 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000010480
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000010481 if (!ND) {
10482 // Try harder to find a NamedDecl to point at in the note.
10483 while (const ArraySubscriptExpr *ASE =
10484 dyn_cast<ArraySubscriptExpr>(BaseExpr))
10485 BaseExpr = ASE->getBase()->IgnoreParenCasts();
10486 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10487 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10488 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10489 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10490 }
10491
Chandler Carruth1af88f12011-02-17 21:10:52 +000010492 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010493 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10494 PDiag(diag::note_array_index_out_of_bounds)
10495 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000010496}
10497
Ted Kremenekdf26df72011-03-01 18:41:00 +000010498void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010499 int AllowOnePastEnd = 0;
10500 while (expr) {
10501 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000010502 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010503 case Stmt::ArraySubscriptExprClass: {
10504 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010505 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010506 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +000010507 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010508 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010509 case Stmt::OMPArraySectionExprClass: {
10510 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10511 if (ASE->getLowerBound())
10512 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10513 /*ASE=*/nullptr, AllowOnePastEnd > 0);
10514 return;
10515 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010516 case Stmt::UnaryOperatorClass: {
10517 // Only unwrap the * and & unary operators
10518 const UnaryOperator *UO = cast<UnaryOperator>(expr);
10519 expr = UO->getSubExpr();
10520 switch (UO->getOpcode()) {
10521 case UO_AddrOf:
10522 AllowOnePastEnd++;
10523 break;
10524 case UO_Deref:
10525 AllowOnePastEnd--;
10526 break;
10527 default:
10528 return;
10529 }
10530 break;
10531 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010532 case Stmt::ConditionalOperatorClass: {
10533 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10534 if (const Expr *lhs = cond->getLHS())
10535 CheckArrayAccess(lhs);
10536 if (const Expr *rhs = cond->getRHS())
10537 CheckArrayAccess(rhs);
10538 return;
10539 }
10540 default:
10541 return;
10542 }
Peter Collingbourne91147592011-04-15 00:35:48 +000010543 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010544}
John McCall31168b02011-06-15 23:02:42 +000010545
10546//===--- CHECK: Objective-C retain cycles ----------------------------------//
10547
10548namespace {
10549 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +000010550 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +000010551 VarDecl *Variable;
10552 SourceRange Range;
10553 SourceLocation Loc;
10554 bool Indirect;
10555
10556 void setLocsFrom(Expr *e) {
10557 Loc = e->getExprLoc();
10558 Range = e->getSourceRange();
10559 }
10560 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010561} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010562
10563/// Consider whether capturing the given variable can possibly lead to
10564/// a retain cycle.
10565static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010566 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000010567 // lifetime. In MRR, it's captured strongly if the variable is
10568 // __block and has an appropriate type.
10569 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10570 return false;
10571
10572 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010573 if (ref)
10574 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000010575 return true;
10576}
10577
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010578static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000010579 while (true) {
10580 e = e->IgnoreParens();
10581 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10582 switch (cast->getCastKind()) {
10583 case CK_BitCast:
10584 case CK_LValueBitCast:
10585 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000010586 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000010587 e = cast->getSubExpr();
10588 continue;
10589
John McCall31168b02011-06-15 23:02:42 +000010590 default:
10591 return false;
10592 }
10593 }
10594
10595 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10596 ObjCIvarDecl *ivar = ref->getDecl();
10597 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10598 return false;
10599
10600 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010601 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000010602 return false;
10603
10604 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10605 owner.Indirect = true;
10606 return true;
10607 }
10608
10609 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10610 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10611 if (!var) return false;
10612 return considerVariable(var, ref, owner);
10613 }
10614
John McCall31168b02011-06-15 23:02:42 +000010615 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10616 if (member->isArrow()) return false;
10617
10618 // Don't count this as an indirect ownership.
10619 e = member->getBase();
10620 continue;
10621 }
10622
John McCallfe96e0b2011-11-06 09:01:30 +000010623 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10624 // Only pay attention to pseudo-objects on property references.
10625 ObjCPropertyRefExpr *pre
10626 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10627 ->IgnoreParens());
10628 if (!pre) return false;
10629 if (pre->isImplicitProperty()) return false;
10630 ObjCPropertyDecl *property = pre->getExplicitProperty();
10631 if (!property->isRetaining() &&
10632 !(property->getPropertyIvarDecl() &&
10633 property->getPropertyIvarDecl()->getType()
10634 .getObjCLifetime() == Qualifiers::OCL_Strong))
10635 return false;
10636
10637 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010638 if (pre->isSuperReceiver()) {
10639 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10640 if (!owner.Variable)
10641 return false;
10642 owner.Loc = pre->getLocation();
10643 owner.Range = pre->getSourceRange();
10644 return true;
10645 }
John McCallfe96e0b2011-11-06 09:01:30 +000010646 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10647 ->getSourceExpr());
10648 continue;
10649 }
10650
John McCall31168b02011-06-15 23:02:42 +000010651 // Array ivars?
10652
10653 return false;
10654 }
10655}
10656
10657namespace {
10658 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10659 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10660 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010661 Context(Context), Variable(variable), Capturer(nullptr),
10662 VarWillBeReased(false) {}
10663 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000010664 VarDecl *Variable;
10665 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010666 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +000010667
10668 void VisitDeclRefExpr(DeclRefExpr *ref) {
10669 if (ref->getDecl() == Variable && !Capturer)
10670 Capturer = ref;
10671 }
10672
John McCall31168b02011-06-15 23:02:42 +000010673 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10674 if (Capturer) return;
10675 Visit(ref->getBase());
10676 if (Capturer && ref->isFreeIvar())
10677 Capturer = ref;
10678 }
10679
10680 void VisitBlockExpr(BlockExpr *block) {
10681 // Look inside nested blocks
10682 if (block->getBlockDecl()->capturesVariable(Variable))
10683 Visit(block->getBlockDecl()->getBody());
10684 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000010685
10686 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
10687 if (Capturer) return;
10688 if (OVE->getSourceExpr())
10689 Visit(OVE->getSourceExpr());
10690 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010691 void VisitBinaryOperator(BinaryOperator *BinOp) {
10692 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
10693 return;
10694 Expr *LHS = BinOp->getLHS();
10695 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
10696 if (DRE->getDecl() != Variable)
10697 return;
10698 if (Expr *RHS = BinOp->getRHS()) {
10699 RHS = RHS->IgnoreParenCasts();
10700 llvm::APSInt Value;
10701 VarWillBeReased =
10702 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
10703 }
10704 }
10705 }
John McCall31168b02011-06-15 23:02:42 +000010706 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010707} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010708
10709/// Check whether the given argument is a block which captures a
10710/// variable.
10711static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
10712 assert(owner.Variable && owner.Loc.isValid());
10713
10714 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000010715
10716 // Look through [^{...} copy] and Block_copy(^{...}).
10717 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
10718 Selector Cmd = ME->getSelector();
10719 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
10720 e = ME->getInstanceReceiver();
10721 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000010722 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000010723 e = e->IgnoreParenCasts();
10724 }
10725 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
10726 if (CE->getNumArgs() == 1) {
10727 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000010728 if (Fn) {
10729 const IdentifierInfo *FnI = Fn->getIdentifier();
10730 if (FnI && FnI->isStr("_Block_copy")) {
10731 e = CE->getArg(0)->IgnoreParenCasts();
10732 }
10733 }
Jordan Rose67e887c2012-09-17 17:54:30 +000010734 }
10735 }
10736
John McCall31168b02011-06-15 23:02:42 +000010737 BlockExpr *block = dyn_cast<BlockExpr>(e);
10738 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000010739 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000010740
10741 FindCaptureVisitor visitor(S.Context, owner.Variable);
10742 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010743 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000010744}
10745
10746static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10747 RetainCycleOwner &owner) {
10748 assert(capturer);
10749 assert(owner.Variable && owner.Loc.isValid());
10750
10751 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10752 << owner.Variable << capturer->getSourceRange();
10753 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10754 << owner.Indirect << owner.Range;
10755}
10756
10757/// Check for a keyword selector that starts with the word 'add' or
10758/// 'set'.
10759static bool isSetterLikeSelector(Selector sel) {
10760 if (sel.isUnarySelector()) return false;
10761
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010762 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000010763 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010764 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000010765 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010766 else if (str.startswith("add")) {
10767 // Specially whitelist 'addOperationWithBlock:'.
10768 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
10769 return false;
10770 str = str.substr(3);
10771 }
John McCall31168b02011-06-15 23:02:42 +000010772 else
10773 return false;
10774
10775 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000010776 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000010777}
10778
Benjamin Kramer3a743452015-03-09 15:03:32 +000010779static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
10780 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010781 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
10782 Message->getReceiverInterface(),
10783 NSAPI::ClassId_NSMutableArray);
10784 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010785 return None;
10786 }
10787
10788 Selector Sel = Message->getSelector();
10789
10790 Optional<NSAPI::NSArrayMethodKind> MKOpt =
10791 S.NSAPIObj->getNSArrayMethodKind(Sel);
10792 if (!MKOpt) {
10793 return None;
10794 }
10795
10796 NSAPI::NSArrayMethodKind MK = *MKOpt;
10797
10798 switch (MK) {
10799 case NSAPI::NSMutableArr_addObject:
10800 case NSAPI::NSMutableArr_insertObjectAtIndex:
10801 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
10802 return 0;
10803 case NSAPI::NSMutableArr_replaceObjectAtIndex:
10804 return 1;
10805
10806 default:
10807 return None;
10808 }
10809
10810 return None;
10811}
10812
10813static
10814Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10815 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010816 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10817 Message->getReceiverInterface(),
10818 NSAPI::ClassId_NSMutableDictionary);
10819 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010820 return None;
10821 }
10822
10823 Selector Sel = Message->getSelector();
10824
10825 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10826 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10827 if (!MKOpt) {
10828 return None;
10829 }
10830
10831 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10832
10833 switch (MK) {
10834 case NSAPI::NSMutableDict_setObjectForKey:
10835 case NSAPI::NSMutableDict_setValueForKey:
10836 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10837 return 0;
10838
10839 default:
10840 return None;
10841 }
10842
10843 return None;
10844}
10845
10846static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010847 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10848 Message->getReceiverInterface(),
10849 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000010850
Alex Denisov5dfac812015-08-06 04:51:14 +000010851 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10852 Message->getReceiverInterface(),
10853 NSAPI::ClassId_NSMutableOrderedSet);
10854 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010855 return None;
10856 }
10857
10858 Selector Sel = Message->getSelector();
10859
10860 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10861 if (!MKOpt) {
10862 return None;
10863 }
10864
10865 NSAPI::NSSetMethodKind MK = *MKOpt;
10866
10867 switch (MK) {
10868 case NSAPI::NSMutableSet_addObject:
10869 case NSAPI::NSOrderedSet_setObjectAtIndex:
10870 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10871 case NSAPI::NSOrderedSet_insertObjectAtIndex:
10872 return 0;
10873 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10874 return 1;
10875 }
10876
10877 return None;
10878}
10879
10880void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10881 if (!Message->isInstanceMessage()) {
10882 return;
10883 }
10884
10885 Optional<int> ArgOpt;
10886
10887 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10888 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10889 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10890 return;
10891 }
10892
10893 int ArgIndex = *ArgOpt;
10894
Alex Denisove1d882c2015-03-04 17:55:52 +000010895 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10896 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10897 Arg = OE->getSourceExpr()->IgnoreImpCasts();
10898 }
10899
Alex Denisov5dfac812015-08-06 04:51:14 +000010900 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010901 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010902 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010903 Diag(Message->getSourceRange().getBegin(),
10904 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000010905 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000010906 }
10907 }
Alex Denisov5dfac812015-08-06 04:51:14 +000010908 } else {
10909 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10910
10911 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10912 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10913 }
10914
10915 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10916 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10917 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10918 ValueDecl *Decl = ReceiverRE->getDecl();
10919 Diag(Message->getSourceRange().getBegin(),
10920 diag::warn_objc_circular_container)
10921 << Decl->getName() << Decl->getName();
10922 if (!ArgRE->isObjCSelfExpr()) {
10923 Diag(Decl->getLocation(),
10924 diag::note_objc_circular_container_declared_here)
10925 << Decl->getName();
10926 }
10927 }
10928 }
10929 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
10930 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
10931 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
10932 ObjCIvarDecl *Decl = IvarRE->getDecl();
10933 Diag(Message->getSourceRange().getBegin(),
10934 diag::warn_objc_circular_container)
10935 << Decl->getName() << Decl->getName();
10936 Diag(Decl->getLocation(),
10937 diag::note_objc_circular_container_declared_here)
10938 << Decl->getName();
10939 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010940 }
10941 }
10942 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010943}
10944
John McCall31168b02011-06-15 23:02:42 +000010945/// Check a message send to see if it's likely to cause a retain cycle.
10946void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
10947 // Only check instance methods whose selector looks like a setter.
10948 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
10949 return;
10950
10951 // Try to find a variable that the receiver is strongly owned by.
10952 RetainCycleOwner owner;
10953 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010954 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000010955 return;
10956 } else {
10957 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
10958 owner.Variable = getCurMethodDecl()->getSelfDecl();
10959 owner.Loc = msg->getSuperLoc();
10960 owner.Range = msg->getSuperLoc();
10961 }
10962
10963 // Check whether the receiver is captured by any of the arguments.
10964 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
10965 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
10966 return diagnoseRetainCycle(*this, capturer, owner);
10967}
10968
10969/// Check a property assign to see if it's likely to cause a retain cycle.
10970void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
10971 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010972 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000010973 return;
10974
10975 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
10976 diagnoseRetainCycle(*this, capturer, owner);
10977}
10978
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010979void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
10980 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000010981 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010982 return;
10983
10984 // Because we don't have an expression for the variable, we have to set the
10985 // location explicitly here.
10986 Owner.Loc = Var->getLocation();
10987 Owner.Range = Var->getSourceRange();
10988
10989 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
10990 diagnoseRetainCycle(*this, Capturer, Owner);
10991}
10992
Ted Kremenek9304da92012-12-21 08:04:28 +000010993static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
10994 Expr *RHS, bool isProperty) {
10995 // Check if RHS is an Objective-C object literal, which also can get
10996 // immediately zapped in a weak reference. Note that we explicitly
10997 // allow ObjCStringLiterals, since those are designed to never really die.
10998 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010999
Ted Kremenek64873352012-12-21 22:46:35 +000011000 // This enum needs to match with the 'select' in
11001 // warn_objc_arc_literal_assign (off-by-1).
11002 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11003 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11004 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011005
11006 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000011007 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000011008 << (isProperty ? 0 : 1)
11009 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011010
11011 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000011012}
11013
Ted Kremenekc1f014a2012-12-21 19:45:30 +000011014static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11015 Qualifiers::ObjCLifetime LT,
11016 Expr *RHS, bool isProperty) {
11017 // Strip off any implicit cast added to get to the one ARC-specific.
11018 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11019 if (cast->getCastKind() == CK_ARCConsumeObject) {
11020 S.Diag(Loc, diag::warn_arc_retained_assign)
11021 << (LT == Qualifiers::OCL_ExplicitNone)
11022 << (isProperty ? 0 : 1)
11023 << RHS->getSourceRange();
11024 return true;
11025 }
11026 RHS = cast->getSubExpr();
11027 }
11028
11029 if (LT == Qualifiers::OCL_Weak &&
11030 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11031 return true;
11032
11033 return false;
11034}
11035
Ted Kremenekb36234d2012-12-21 08:04:20 +000011036bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11037 QualType LHS, Expr *RHS) {
11038 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11039
11040 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11041 return false;
11042
11043 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11044 return true;
11045
11046 return false;
11047}
11048
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011049void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11050 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011051 QualType LHSType;
11052 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011053 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011054 ObjCPropertyRefExpr *PRE
11055 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11056 if (PRE && !PRE->isImplicitProperty()) {
11057 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11058 if (PD)
11059 LHSType = PD->getType();
11060 }
11061
11062 if (LHSType.isNull())
11063 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000011064
11065 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11066
11067 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011068 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000011069 getCurFunction()->markSafeWeakUse(LHS);
11070 }
11071
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011072 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11073 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000011074
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011075 // FIXME. Check for other life times.
11076 if (LT != Qualifiers::OCL_None)
11077 return;
11078
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011079 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011080 if (PRE->isImplicitProperty())
11081 return;
11082 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11083 if (!PD)
11084 return;
11085
Bill Wendling44426052012-12-20 19:22:21 +000011086 unsigned Attributes = PD->getPropertyAttributes();
11087 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011088 // when 'assign' attribute was not explicitly specified
11089 // by user, ignore it and rely on property type itself
11090 // for lifetime info.
11091 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11092 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11093 LHSType->isObjCRetainableType())
11094 return;
11095
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011096 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000011097 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011098 Diag(Loc, diag::warn_arc_retained_property_assign)
11099 << RHS->getSourceRange();
11100 return;
11101 }
11102 RHS = cast->getSubExpr();
11103 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011104 }
Bill Wendling44426052012-12-20 19:22:21 +000011105 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000011106 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11107 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000011108 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011109 }
11110}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011111
11112//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11113
11114namespace {
11115bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11116 SourceLocation StmtLoc,
11117 const NullStmt *Body) {
11118 // Do not warn if the body is a macro that expands to nothing, e.g:
11119 //
11120 // #define CALL(x)
11121 // if (condition)
11122 // CALL(0);
11123 //
11124 if (Body->hasLeadingEmptyMacro())
11125 return false;
11126
11127 // Get line numbers of statement and body.
11128 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000011129 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011130 &StmtLineInvalid);
11131 if (StmtLineInvalid)
11132 return false;
11133
11134 bool BodyLineInvalid;
11135 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11136 &BodyLineInvalid);
11137 if (BodyLineInvalid)
11138 return false;
11139
11140 // Warn if null statement and body are on the same line.
11141 if (StmtLine != BodyLine)
11142 return false;
11143
11144 return true;
11145}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011146} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011147
11148void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11149 const Stmt *Body,
11150 unsigned DiagID) {
11151 // Since this is a syntactic check, don't emit diagnostic for template
11152 // instantiations, this just adds noise.
11153 if (CurrentInstantiationScope)
11154 return;
11155
11156 // The body should be a null statement.
11157 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11158 if (!NBody)
11159 return;
11160
11161 // Do the usual checks.
11162 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11163 return;
11164
11165 Diag(NBody->getSemiLoc(), DiagID);
11166 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11167}
11168
11169void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11170 const Stmt *PossibleBody) {
11171 assert(!CurrentInstantiationScope); // Ensured by caller
11172
11173 SourceLocation StmtLoc;
11174 const Stmt *Body;
11175 unsigned DiagID;
11176 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11177 StmtLoc = FS->getRParenLoc();
11178 Body = FS->getBody();
11179 DiagID = diag::warn_empty_for_body;
11180 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11181 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11182 Body = WS->getBody();
11183 DiagID = diag::warn_empty_while_body;
11184 } else
11185 return; // Neither `for' nor `while'.
11186
11187 // The body should be a null statement.
11188 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11189 if (!NBody)
11190 return;
11191
11192 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011193 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011194 return;
11195
11196 // Do the usual checks.
11197 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11198 return;
11199
11200 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11201 // noise level low, emit diagnostics only if for/while is followed by a
11202 // CompoundStmt, e.g.:
11203 // for (int i = 0; i < n; i++);
11204 // {
11205 // a(i);
11206 // }
11207 // or if for/while is followed by a statement with more indentation
11208 // than for/while itself:
11209 // for (int i = 0; i < n; i++);
11210 // a(i);
11211 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11212 if (!ProbableTypo) {
11213 bool BodyColInvalid;
11214 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11215 PossibleBody->getLocStart(),
11216 &BodyColInvalid);
11217 if (BodyColInvalid)
11218 return;
11219
11220 bool StmtColInvalid;
11221 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11222 S->getLocStart(),
11223 &StmtColInvalid);
11224 if (StmtColInvalid)
11225 return;
11226
11227 if (BodyCol > StmtCol)
11228 ProbableTypo = true;
11229 }
11230
11231 if (ProbableTypo) {
11232 Diag(NBody->getSemiLoc(), DiagID);
11233 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11234 }
11235}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011236
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011237//===--- CHECK: Warn on self move with std::move. -------------------------===//
11238
11239/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11240void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11241 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011242 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11243 return;
11244
11245 if (!ActiveTemplateInstantiations.empty())
11246 return;
11247
11248 // Strip parens and casts away.
11249 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11250 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11251
11252 // Check for a call expression
11253 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11254 if (!CE || CE->getNumArgs() != 1)
11255 return;
11256
11257 // Check for a call to std::move
11258 const FunctionDecl *FD = CE->getDirectCallee();
11259 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11260 !FD->getIdentifier()->isStr("move"))
11261 return;
11262
11263 // Get argument from std::move
11264 RHSExpr = CE->getArg(0);
11265
11266 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11267 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11268
11269 // Two DeclRefExpr's, check that the decls are the same.
11270 if (LHSDeclRef && RHSDeclRef) {
11271 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11272 return;
11273 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11274 RHSDeclRef->getDecl()->getCanonicalDecl())
11275 return;
11276
11277 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11278 << LHSExpr->getSourceRange()
11279 << RHSExpr->getSourceRange();
11280 return;
11281 }
11282
11283 // Member variables require a different approach to check for self moves.
11284 // MemberExpr's are the same if every nested MemberExpr refers to the same
11285 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11286 // the base Expr's are CXXThisExpr's.
11287 const Expr *LHSBase = LHSExpr;
11288 const Expr *RHSBase = RHSExpr;
11289 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11290 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11291 if (!LHSME || !RHSME)
11292 return;
11293
11294 while (LHSME && RHSME) {
11295 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11296 RHSME->getMemberDecl()->getCanonicalDecl())
11297 return;
11298
11299 LHSBase = LHSME->getBase();
11300 RHSBase = RHSME->getBase();
11301 LHSME = dyn_cast<MemberExpr>(LHSBase);
11302 RHSME = dyn_cast<MemberExpr>(RHSBase);
11303 }
11304
11305 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11306 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11307 if (LHSDeclRef && RHSDeclRef) {
11308 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11309 return;
11310 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11311 RHSDeclRef->getDecl()->getCanonicalDecl())
11312 return;
11313
11314 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11315 << LHSExpr->getSourceRange()
11316 << RHSExpr->getSourceRange();
11317 return;
11318 }
11319
11320 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11321 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11322 << LHSExpr->getSourceRange()
11323 << RHSExpr->getSourceRange();
11324}
11325
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011326//===--- Layout compatibility ----------------------------------------------//
11327
11328namespace {
11329
11330bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11331
11332/// \brief Check if two enumeration types are layout-compatible.
11333bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11334 // C++11 [dcl.enum] p8:
11335 // Two enumeration types are layout-compatible if they have the same
11336 // underlying type.
11337 return ED1->isComplete() && ED2->isComplete() &&
11338 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11339}
11340
11341/// \brief Check if two fields are layout-compatible.
11342bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11343 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11344 return false;
11345
11346 if (Field1->isBitField() != Field2->isBitField())
11347 return false;
11348
11349 if (Field1->isBitField()) {
11350 // Make sure that the bit-fields are the same length.
11351 unsigned Bits1 = Field1->getBitWidthValue(C);
11352 unsigned Bits2 = Field2->getBitWidthValue(C);
11353
11354 if (Bits1 != Bits2)
11355 return false;
11356 }
11357
11358 return true;
11359}
11360
11361/// \brief Check if two standard-layout structs are layout-compatible.
11362/// (C++11 [class.mem] p17)
11363bool isLayoutCompatibleStruct(ASTContext &C,
11364 RecordDecl *RD1,
11365 RecordDecl *RD2) {
11366 // If both records are C++ classes, check that base classes match.
11367 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11368 // If one of records is a CXXRecordDecl we are in C++ mode,
11369 // thus the other one is a CXXRecordDecl, too.
11370 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11371 // Check number of base classes.
11372 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11373 return false;
11374
11375 // Check the base classes.
11376 for (CXXRecordDecl::base_class_const_iterator
11377 Base1 = D1CXX->bases_begin(),
11378 BaseEnd1 = D1CXX->bases_end(),
11379 Base2 = D2CXX->bases_begin();
11380 Base1 != BaseEnd1;
11381 ++Base1, ++Base2) {
11382 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11383 return false;
11384 }
11385 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11386 // If only RD2 is a C++ class, it should have zero base classes.
11387 if (D2CXX->getNumBases() > 0)
11388 return false;
11389 }
11390
11391 // Check the fields.
11392 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11393 Field2End = RD2->field_end(),
11394 Field1 = RD1->field_begin(),
11395 Field1End = RD1->field_end();
11396 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11397 if (!isLayoutCompatible(C, *Field1, *Field2))
11398 return false;
11399 }
11400 if (Field1 != Field1End || Field2 != Field2End)
11401 return false;
11402
11403 return true;
11404}
11405
11406/// \brief Check if two standard-layout unions are layout-compatible.
11407/// (C++11 [class.mem] p18)
11408bool isLayoutCompatibleUnion(ASTContext &C,
11409 RecordDecl *RD1,
11410 RecordDecl *RD2) {
11411 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011412 for (auto *Field2 : RD2->fields())
11413 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011414
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011415 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011416 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11417 I = UnmatchedFields.begin(),
11418 E = UnmatchedFields.end();
11419
11420 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011421 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011422 bool Result = UnmatchedFields.erase(*I);
11423 (void) Result;
11424 assert(Result);
11425 break;
11426 }
11427 }
11428 if (I == E)
11429 return false;
11430 }
11431
11432 return UnmatchedFields.empty();
11433}
11434
11435bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11436 if (RD1->isUnion() != RD2->isUnion())
11437 return false;
11438
11439 if (RD1->isUnion())
11440 return isLayoutCompatibleUnion(C, RD1, RD2);
11441 else
11442 return isLayoutCompatibleStruct(C, RD1, RD2);
11443}
11444
11445/// \brief Check if two types are layout-compatible in C++11 sense.
11446bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11447 if (T1.isNull() || T2.isNull())
11448 return false;
11449
11450 // C++11 [basic.types] p11:
11451 // If two types T1 and T2 are the same type, then T1 and T2 are
11452 // layout-compatible types.
11453 if (C.hasSameType(T1, T2))
11454 return true;
11455
11456 T1 = T1.getCanonicalType().getUnqualifiedType();
11457 T2 = T2.getCanonicalType().getUnqualifiedType();
11458
11459 const Type::TypeClass TC1 = T1->getTypeClass();
11460 const Type::TypeClass TC2 = T2->getTypeClass();
11461
11462 if (TC1 != TC2)
11463 return false;
11464
11465 if (TC1 == Type::Enum) {
11466 return isLayoutCompatible(C,
11467 cast<EnumType>(T1)->getDecl(),
11468 cast<EnumType>(T2)->getDecl());
11469 } else if (TC1 == Type::Record) {
11470 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11471 return false;
11472
11473 return isLayoutCompatible(C,
11474 cast<RecordType>(T1)->getDecl(),
11475 cast<RecordType>(T2)->getDecl());
11476 }
11477
11478 return false;
11479}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011480} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011481
11482//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11483
11484namespace {
11485/// \brief Given a type tag expression find the type tag itself.
11486///
11487/// \param TypeExpr Type tag expression, as it appears in user's code.
11488///
11489/// \param VD Declaration of an identifier that appears in a type tag.
11490///
11491/// \param MagicValue Type tag magic value.
11492bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11493 const ValueDecl **VD, uint64_t *MagicValue) {
11494 while(true) {
11495 if (!TypeExpr)
11496 return false;
11497
11498 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11499
11500 switch (TypeExpr->getStmtClass()) {
11501 case Stmt::UnaryOperatorClass: {
11502 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11503 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11504 TypeExpr = UO->getSubExpr();
11505 continue;
11506 }
11507 return false;
11508 }
11509
11510 case Stmt::DeclRefExprClass: {
11511 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11512 *VD = DRE->getDecl();
11513 return true;
11514 }
11515
11516 case Stmt::IntegerLiteralClass: {
11517 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11518 llvm::APInt MagicValueAPInt = IL->getValue();
11519 if (MagicValueAPInt.getActiveBits() <= 64) {
11520 *MagicValue = MagicValueAPInt.getZExtValue();
11521 return true;
11522 } else
11523 return false;
11524 }
11525
11526 case Stmt::BinaryConditionalOperatorClass:
11527 case Stmt::ConditionalOperatorClass: {
11528 const AbstractConditionalOperator *ACO =
11529 cast<AbstractConditionalOperator>(TypeExpr);
11530 bool Result;
11531 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11532 if (Result)
11533 TypeExpr = ACO->getTrueExpr();
11534 else
11535 TypeExpr = ACO->getFalseExpr();
11536 continue;
11537 }
11538 return false;
11539 }
11540
11541 case Stmt::BinaryOperatorClass: {
11542 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11543 if (BO->getOpcode() == BO_Comma) {
11544 TypeExpr = BO->getRHS();
11545 continue;
11546 }
11547 return false;
11548 }
11549
11550 default:
11551 return false;
11552 }
11553 }
11554}
11555
11556/// \brief Retrieve the C type corresponding to type tag TypeExpr.
11557///
11558/// \param TypeExpr Expression that specifies a type tag.
11559///
11560/// \param MagicValues Registered magic values.
11561///
11562/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11563/// kind.
11564///
11565/// \param TypeInfo Information about the corresponding C type.
11566///
11567/// \returns true if the corresponding C type was found.
11568bool GetMatchingCType(
11569 const IdentifierInfo *ArgumentKind,
11570 const Expr *TypeExpr, const ASTContext &Ctx,
11571 const llvm::DenseMap<Sema::TypeTagMagicValue,
11572 Sema::TypeTagData> *MagicValues,
11573 bool &FoundWrongKind,
11574 Sema::TypeTagData &TypeInfo) {
11575 FoundWrongKind = false;
11576
11577 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000011578 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011579
11580 uint64_t MagicValue;
11581
11582 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11583 return false;
11584
11585 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000011586 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011587 if (I->getArgumentKind() != ArgumentKind) {
11588 FoundWrongKind = true;
11589 return false;
11590 }
11591 TypeInfo.Type = I->getMatchingCType();
11592 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11593 TypeInfo.MustBeNull = I->getMustBeNull();
11594 return true;
11595 }
11596 return false;
11597 }
11598
11599 if (!MagicValues)
11600 return false;
11601
11602 llvm::DenseMap<Sema::TypeTagMagicValue,
11603 Sema::TypeTagData>::const_iterator I =
11604 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11605 if (I == MagicValues->end())
11606 return false;
11607
11608 TypeInfo = I->second;
11609 return true;
11610}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011611} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011612
11613void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11614 uint64_t MagicValue, QualType Type,
11615 bool LayoutCompatible,
11616 bool MustBeNull) {
11617 if (!TypeTagForDatatypeMagicValues)
11618 TypeTagForDatatypeMagicValues.reset(
11619 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11620
11621 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11622 (*TypeTagForDatatypeMagicValues)[Magic] =
11623 TypeTagData(Type, LayoutCompatible, MustBeNull);
11624}
11625
11626namespace {
11627bool IsSameCharType(QualType T1, QualType T2) {
11628 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11629 if (!BT1)
11630 return false;
11631
11632 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11633 if (!BT2)
11634 return false;
11635
11636 BuiltinType::Kind T1Kind = BT1->getKind();
11637 BuiltinType::Kind T2Kind = BT2->getKind();
11638
11639 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
11640 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
11641 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11642 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11643}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011644} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011645
11646void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11647 const Expr * const *ExprArgs) {
11648 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11649 bool IsPointerAttr = Attr->getIsPointer();
11650
11651 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11652 bool FoundWrongKind;
11653 TypeTagData TypeInfo;
11654 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11655 TypeTagForDatatypeMagicValues.get(),
11656 FoundWrongKind, TypeInfo)) {
11657 if (FoundWrongKind)
11658 Diag(TypeTagExpr->getExprLoc(),
11659 diag::warn_type_tag_for_datatype_wrong_kind)
11660 << TypeTagExpr->getSourceRange();
11661 return;
11662 }
11663
11664 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11665 if (IsPointerAttr) {
11666 // Skip implicit cast of pointer to `void *' (as a function argument).
11667 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000011668 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000011669 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011670 ArgumentExpr = ICE->getSubExpr();
11671 }
11672 QualType ArgumentType = ArgumentExpr->getType();
11673
11674 // Passing a `void*' pointer shouldn't trigger a warning.
11675 if (IsPointerAttr && ArgumentType->isVoidPointerType())
11676 return;
11677
11678 if (TypeInfo.MustBeNull) {
11679 // Type tag with matching void type requires a null pointer.
11680 if (!ArgumentExpr->isNullPointerConstant(Context,
11681 Expr::NPC_ValueDependentIsNotNull)) {
11682 Diag(ArgumentExpr->getExprLoc(),
11683 diag::warn_type_safety_null_pointer_required)
11684 << ArgumentKind->getName()
11685 << ArgumentExpr->getSourceRange()
11686 << TypeTagExpr->getSourceRange();
11687 }
11688 return;
11689 }
11690
11691 QualType RequiredType = TypeInfo.Type;
11692 if (IsPointerAttr)
11693 RequiredType = Context.getPointerType(RequiredType);
11694
11695 bool mismatch = false;
11696 if (!TypeInfo.LayoutCompatible) {
11697 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
11698
11699 // C++11 [basic.fundamental] p1:
11700 // Plain char, signed char, and unsigned char are three distinct types.
11701 //
11702 // But we treat plain `char' as equivalent to `signed char' or `unsigned
11703 // char' depending on the current char signedness mode.
11704 if (mismatch)
11705 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
11706 RequiredType->getPointeeType())) ||
11707 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
11708 mismatch = false;
11709 } else
11710 if (IsPointerAttr)
11711 mismatch = !isLayoutCompatible(Context,
11712 ArgumentType->getPointeeType(),
11713 RequiredType->getPointeeType());
11714 else
11715 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
11716
11717 if (mismatch)
11718 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000011719 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011720 << TypeInfo.LayoutCompatible << RequiredType
11721 << ArgumentExpr->getSourceRange()
11722 << TypeTagExpr->getSourceRange();
11723}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011724
11725void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11726 CharUnits Alignment) {
11727 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
11728}
11729
11730void Sema::DiagnoseMisalignedMembers() {
11731 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000011732 const NamedDecl *ND = m.RD;
11733 if (ND->getName().empty()) {
11734 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
11735 ND = TD;
11736 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011737 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000011738 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011739 }
11740 MisalignedMembers.clear();
11741}
11742
11743void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011744 E = E->IgnoreParens();
11745 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011746 return;
11747 if (isa<UnaryOperator>(E) &&
11748 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
11749 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11750 if (isa<MemberExpr>(Op)) {
11751 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
11752 MisalignedMember(Op));
11753 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011754 (T->isIntegerType() ||
11755 (T->isPointerType() &&
11756 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011757 MisalignedMembers.erase(MA);
11758 }
11759 }
11760}
11761
11762void Sema::RefersToMemberWithReducedAlignment(
11763 Expr *E,
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011764 std::function<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011765 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011766 if (!ME)
11767 return;
11768
11769 // For a chain of MemberExpr like "a.b.c.d" this list
11770 // will keep FieldDecl's like [d, c, b].
11771 SmallVector<FieldDecl *, 4> ReverseMemberChain;
11772 const MemberExpr *TopME = nullptr;
11773 bool AnyIsPacked = false;
11774 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011775 QualType BaseType = ME->getBase()->getType();
11776 if (ME->isArrow())
11777 BaseType = BaseType->getPointeeType();
11778 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
11779
11780 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011781 auto *FD = dyn_cast<FieldDecl>(MD);
11782 // We do not care about non-data members.
11783 if (!FD || FD->isInvalidDecl())
11784 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011785
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011786 AnyIsPacked =
11787 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
11788 ReverseMemberChain.push_back(FD);
11789
11790 TopME = ME;
11791 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
11792 } while (ME);
11793 assert(TopME && "We did not compute a topmost MemberExpr!");
11794
11795 // Not the scope of this diagnostic.
11796 if (!AnyIsPacked)
11797 return;
11798
11799 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
11800 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
11801 // TODO: The innermost base of the member expression may be too complicated.
11802 // For now, just disregard these cases. This is left for future
11803 // improvement.
11804 if (!DRE && !isa<CXXThisExpr>(TopBase))
11805 return;
11806
11807 // Alignment expected by the whole expression.
11808 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
11809
11810 // No need to do anything else with this case.
11811 if (ExpectedAlignment.isOne())
11812 return;
11813
11814 // Synthesize offset of the whole access.
11815 CharUnits Offset;
11816 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
11817 I++) {
11818 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
11819 }
11820
11821 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
11822 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
11823 ReverseMemberChain.back()->getParent()->getTypeForDecl());
11824
11825 // The base expression of the innermost MemberExpr may give
11826 // stronger guarantees than the class containing the member.
11827 if (DRE && !TopME->isArrow()) {
11828 const ValueDecl *VD = DRE->getDecl();
11829 if (!VD->getType()->isReferenceType())
11830 CompleteObjectAlignment =
11831 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
11832 }
11833
11834 // Check if the synthesized offset fulfills the alignment.
11835 if (Offset % ExpectedAlignment != 0 ||
11836 // It may fulfill the offset it but the effective alignment may still be
11837 // lower than the expected expression alignment.
11838 CompleteObjectAlignment < ExpectedAlignment) {
11839 // If this happens, we want to determine a sensible culprit of this.
11840 // Intuitively, watching the chain of member expressions from right to
11841 // left, we start with the required alignment (as required by the field
11842 // type) but some packed attribute in that chain has reduced the alignment.
11843 // It may happen that another packed structure increases it again. But if
11844 // we are here such increase has not been enough. So pointing the first
11845 // FieldDecl that either is packed or else its RecordDecl is,
11846 // seems reasonable.
11847 FieldDecl *FD = nullptr;
11848 CharUnits Alignment;
11849 for (FieldDecl *FDI : ReverseMemberChain) {
11850 if (FDI->hasAttr<PackedAttr>() ||
11851 FDI->getParent()->hasAttr<PackedAttr>()) {
11852 FD = FDI;
11853 Alignment = std::min(
11854 Context.getTypeAlignInChars(FD->getType()),
11855 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
11856 break;
11857 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011858 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011859 assert(FD && "We did not find a packed FieldDecl!");
11860 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011861 }
11862}
11863
11864void Sema::CheckAddressOfPackedMember(Expr *rhs) {
11865 using namespace std::placeholders;
11866 RefersToMemberWithReducedAlignment(
11867 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
11868 _2, _3, _4));
11869}
11870