blob: 57d765de688f79dd4a4a5d187676a9e1d517f976 [file] [log] [blame]
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattnerb87b1b32007-08-10 20:18:51 +000015#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000017#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000020#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000021#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000022#include "clang/AST/ExprObjC.h"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000023#include "clang/AST/ExprOpenMP.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000030#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000035#include "clang/Sema/SemaInternal.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000036#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000037#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "llvm/ADT/SmallString.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000039#include "llvm/Support/ConvertUTF.h"
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +000040#include "llvm/Support/Format.h"
41#include "llvm/Support/Locale.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000042#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000043
Chris Lattnerb87b1b32007-08-10 20:18:51 +000044using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000045using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000046
Chris Lattnera26fb342009-02-18 17:49:48 +000047SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
48 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000049 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
50 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000051}
52
John McCallbebede42011-02-26 05:39:39 +000053/// Checks that a call expression's argument count is the desired number.
54/// This is useful when doing custom type-checking. Returns true on error.
55static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
56 unsigned argCount = call->getNumArgs();
57 if (argCount == desiredArgCount) return false;
58
59 if (argCount < desiredArgCount)
60 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
61 << 0 /*function call*/ << desiredArgCount << argCount
62 << call->getSourceRange();
63
64 // Highlight all the excess arguments.
65 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
66 call->getArg(argCount - 1)->getLocEnd());
67
68 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
69 << 0 /*function call*/ << desiredArgCount << argCount
70 << call->getArg(1)->getSourceRange();
71}
72
Julien Lerouge4a5b4442012-04-28 17:39:16 +000073/// Check that the first argument to __builtin_annotation is an integer
74/// and the second argument is a non-wide string literal.
75static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
76 if (checkArgCount(S, TheCall, 2))
77 return true;
78
79 // First argument should be an integer.
80 Expr *ValArg = TheCall->getArg(0);
81 QualType Ty = ValArg->getType();
82 if (!Ty->isIntegerType()) {
83 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
84 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000085 return true;
86 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000087
88 // Second argument should be a constant string.
89 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
90 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
91 if (!Literal || !Literal->isAscii()) {
92 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
93 << StrArg->getSourceRange();
94 return true;
95 }
96
97 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000098 return false;
99}
100
Richard Smith6cbd65d2013-07-11 02:27:57 +0000101/// Check that the argument to __builtin_addressof is a glvalue, and set the
102/// result type to the corresponding pointer type.
103static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
104 if (checkArgCount(S, TheCall, 1))
105 return true;
106
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000107 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000108 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
109 if (ResultType.isNull())
110 return true;
111
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000112 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000113 TheCall->setType(ResultType);
114 return false;
115}
116
John McCall03107a42015-10-29 20:48:01 +0000117static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
118 if (checkArgCount(S, TheCall, 3))
119 return true;
120
121 // First two arguments should be integers.
122 for (unsigned I = 0; I < 2; ++I) {
123 Expr *Arg = TheCall->getArg(I);
124 QualType Ty = Arg->getType();
125 if (!Ty->isIntegerType()) {
126 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
127 << Ty << Arg->getSourceRange();
128 return true;
129 }
130 }
131
132 // Third argument should be a pointer to a non-const integer.
133 // IRGen correctly handles volatile, restrict, and address spaces, and
134 // the other qualifiers aren't possible.
135 {
136 Expr *Arg = TheCall->getArg(2);
137 QualType Ty = Arg->getType();
138 const auto *PtrTy = Ty->getAs<PointerType>();
139 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
140 !PtrTy->getPointeeType().isConstQualified())) {
141 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
142 << Ty << Arg->getSourceRange();
143 return true;
144 }
145 }
146
147 return false;
148}
149
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000150static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
151 CallExpr *TheCall, unsigned SizeIdx,
152 unsigned DstSizeIdx) {
153 if (TheCall->getNumArgs() <= SizeIdx ||
154 TheCall->getNumArgs() <= DstSizeIdx)
155 return;
156
157 const Expr *SizeArg = TheCall->getArg(SizeIdx);
158 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
159
160 llvm::APSInt Size, DstSize;
161
162 // find out if both sizes are known at compile time
163 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
164 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
165 return;
166
167 if (Size.ule(DstSize))
168 return;
169
170 // confirmed overflow so generate the diagnostic.
171 IdentifierInfo *FnName = FDecl->getIdentifier();
172 SourceLocation SL = TheCall->getLocStart();
173 SourceRange SR = TheCall->getSourceRange();
174
175 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
176}
177
Peter Collingbournef7706832014-12-12 23:41:25 +0000178static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
179 if (checkArgCount(S, BuiltinCall, 2))
180 return true;
181
182 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
183 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
184 Expr *Call = BuiltinCall->getArg(0);
185 Expr *Chain = BuiltinCall->getArg(1);
186
187 if (Call->getStmtClass() != Stmt::CallExprClass) {
188 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
189 << Call->getSourceRange();
190 return true;
191 }
192
193 auto CE = cast<CallExpr>(Call);
194 if (CE->getCallee()->getType()->isBlockPointerType()) {
195 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
196 << Call->getSourceRange();
197 return true;
198 }
199
200 const Decl *TargetDecl = CE->getCalleeDecl();
201 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
202 if (FD->getBuiltinID()) {
203 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
204 << Call->getSourceRange();
205 return true;
206 }
207
208 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
209 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
210 << Call->getSourceRange();
211 return true;
212 }
213
214 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
215 if (ChainResult.isInvalid())
216 return true;
217 if (!ChainResult.get()->getType()->isPointerType()) {
218 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
219 << Chain->getSourceRange();
220 return true;
221 }
222
David Majnemerced8bdf2015-02-25 17:36:15 +0000223 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000224 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
225 QualType BuiltinTy = S.Context.getFunctionType(
226 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
227 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
228
229 Builtin =
230 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
231
232 BuiltinCall->setType(CE->getType());
233 BuiltinCall->setValueKind(CE->getValueKind());
234 BuiltinCall->setObjectKind(CE->getObjectKind());
235 BuiltinCall->setCallee(Builtin);
236 BuiltinCall->setArg(1, ChainResult.get());
237
238 return false;
239}
240
Reid Kleckner1d59f992015-01-22 01:36:17 +0000241static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
242 Scope::ScopeFlags NeededScopeFlags,
243 unsigned DiagID) {
244 // Scopes aren't available during instantiation. Fortunately, builtin
245 // functions cannot be template args so they cannot be formed through template
246 // instantiation. Therefore checking once during the parse is sufficient.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000247 if (SemaRef.inTemplateInstantiation())
Reid Kleckner1d59f992015-01-22 01:36:17 +0000248 return false;
249
250 Scope *S = SemaRef.getCurScope();
251 while (S && !S->isSEHExceptScope())
252 S = S->getParent();
253 if (!S || !(S->getFlags() & NeededScopeFlags)) {
254 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
255 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
256 << DRE->getDecl()->getIdentifier();
257 return true;
258 }
259
260 return false;
261}
262
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000263static inline bool isBlockPointer(Expr *Arg) {
264 return Arg->getType()->isBlockPointerType();
265}
266
267/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
268/// void*, which is a requirement of device side enqueue.
269static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
270 const BlockPointerType *BPT =
271 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
272 ArrayRef<QualType> Params =
273 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
274 unsigned ArgCounter = 0;
275 bool IllegalParams = false;
276 // Iterate through the block parameters until either one is found that is not
277 // a local void*, or the block is valid.
278 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
279 I != E; ++I, ++ArgCounter) {
280 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
281 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
282 LangAS::opencl_local) {
283 // Get the location of the error. If a block literal has been passed
284 // (BlockExpr) then we can point straight to the offending argument,
285 // else we just point to the variable reference.
286 SourceLocation ErrorLoc;
287 if (isa<BlockExpr>(BlockArg)) {
288 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
289 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
290 } else if (isa<DeclRefExpr>(BlockArg)) {
291 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
292 }
293 S.Diag(ErrorLoc,
294 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
295 IllegalParams = true;
296 }
297 }
298
299 return IllegalParams;
300}
301
302/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
303/// get_kernel_work_group_size
304/// and get_kernel_preferred_work_group_size_multiple builtin functions.
305static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
306 if (checkArgCount(S, TheCall, 1))
307 return true;
308
309 Expr *BlockArg = TheCall->getArg(0);
310 if (!isBlockPointer(BlockArg)) {
311 S.Diag(BlockArg->getLocStart(),
312 diag::err_opencl_enqueue_kernel_expected_type) << "block";
313 return true;
314 }
315 return checkOpenCLBlockArgs(S, BlockArg);
316}
317
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.
Anastasia Stulova58984e72017-02-16 12:27:47 +0000411 if (Arg2->getType().getAsString() != "ndrange_t") {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000412 S.Diag(TheCall->getArg(2)->getLocStart(),
413 diag::err_opencl_enqueue_kernel_expected_type)
Anastasia Stulova58984e72017-02-16 12:27:47 +0000414 << "'ndrange_t'";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000415 return true;
416 }
417
418 // With four arguments, there is only one form that the function could be
419 // called in: no events and no variable arguments.
420 if (NumArgs == 4) {
421 // check that the last argument is the right block type.
422 if (!isBlockPointer(Arg3)) {
423 S.Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
424 << "block";
425 return true;
426 }
427 // we have a block type, check the prototype
428 const BlockPointerType *BPT =
429 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
430 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
431 S.Diag(Arg3->getLocStart(),
432 diag::err_opencl_enqueue_kernel_blocks_no_args);
433 return true;
434 }
435 return false;
436 }
437 // we can have block + varargs.
438 if (isBlockPointer(Arg3))
439 return (checkOpenCLBlockArgs(S, Arg3) ||
440 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
441 // last two cases with either exactly 7 args or 7 args and varargs.
442 if (NumArgs >= 7) {
443 // check common block argument.
444 Expr *Arg6 = TheCall->getArg(6);
445 if (!isBlockPointer(Arg6)) {
446 S.Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
447 << "block";
448 return true;
449 }
450 if (checkOpenCLBlockArgs(S, Arg6))
451 return true;
452
453 // Forth argument has to be any integer type.
454 if (!Arg3->getType()->isIntegerType()) {
455 S.Diag(TheCall->getArg(3)->getLocStart(),
456 diag::err_opencl_enqueue_kernel_expected_type)
457 << "integer";
458 return true;
459 }
460 // check remaining common arguments.
461 Expr *Arg4 = TheCall->getArg(4);
462 Expr *Arg5 = TheCall->getArg(5);
463
Anastasia Stulova2b461202016-11-14 15:34:01 +0000464 // Fifth argument is always passed as a pointer to clk_event_t.
465 if (!Arg4->isNullPointerConstant(S.Context,
466 Expr::NPC_ValueDependentIsNotNull) &&
467 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000468 S.Diag(TheCall->getArg(4)->getLocStart(),
469 diag::err_opencl_enqueue_kernel_expected_type)
470 << S.Context.getPointerType(S.Context.OCLClkEventTy);
471 return true;
472 }
473
Anastasia Stulova2b461202016-11-14 15:34:01 +0000474 // Sixth argument is always passed as a pointer to clk_event_t.
475 if (!Arg5->isNullPointerConstant(S.Context,
476 Expr::NPC_ValueDependentIsNotNull) &&
477 !(Arg5->getType()->isPointerType() &&
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000478 Arg5->getType()->getPointeeType()->isClkEventT())) {
479 S.Diag(TheCall->getArg(5)->getLocStart(),
480 diag::err_opencl_enqueue_kernel_expected_type)
481 << S.Context.getPointerType(S.Context.OCLClkEventTy);
482 return true;
483 }
484
485 if (NumArgs == 7)
486 return false;
487
488 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
489 }
490
491 // None of the specific case has been detected, give generic error
492 S.Diag(TheCall->getLocStart(),
493 diag::err_opencl_enqueue_kernel_incorrect_args);
494 return true;
495}
496
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000497/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000498static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000499 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000500}
501
502/// Returns true if pipe element type is different from the pointer.
503static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
504 const Expr *Arg0 = Call->getArg(0);
505 // First argument type should always be pipe.
506 if (!Arg0->getType()->isPipeType()) {
507 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000508 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000509 return true;
510 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000511 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000512 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
513 // Validates the access qualifier is compatible with the call.
514 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
515 // read_only and write_only, and assumed to be read_only if no qualifier is
516 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000517 switch (Call->getDirectCallee()->getBuiltinID()) {
518 case Builtin::BIread_pipe:
519 case Builtin::BIreserve_read_pipe:
520 case Builtin::BIcommit_read_pipe:
521 case Builtin::BIwork_group_reserve_read_pipe:
522 case Builtin::BIsub_group_reserve_read_pipe:
523 case Builtin::BIwork_group_commit_read_pipe:
524 case Builtin::BIsub_group_commit_read_pipe:
525 if (!(!AccessQual || AccessQual->isReadOnly())) {
526 S.Diag(Arg0->getLocStart(),
527 diag::err_opencl_builtin_pipe_invalid_access_modifier)
528 << "read_only" << Arg0->getSourceRange();
529 return true;
530 }
531 break;
532 case Builtin::BIwrite_pipe:
533 case Builtin::BIreserve_write_pipe:
534 case Builtin::BIcommit_write_pipe:
535 case Builtin::BIwork_group_reserve_write_pipe:
536 case Builtin::BIsub_group_reserve_write_pipe:
537 case Builtin::BIwork_group_commit_write_pipe:
538 case Builtin::BIsub_group_commit_write_pipe:
539 if (!(AccessQual && AccessQual->isWriteOnly())) {
540 S.Diag(Arg0->getLocStart(),
541 diag::err_opencl_builtin_pipe_invalid_access_modifier)
542 << "write_only" << Arg0->getSourceRange();
543 return true;
544 }
545 break;
546 default:
547 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000548 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000549 return false;
550}
551
552/// Returns true if pipe element type is different from the pointer.
553static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
554 const Expr *Arg0 = Call->getArg(0);
555 const Expr *ArgIdx = Call->getArg(Idx);
556 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000557 const QualType EltTy = PipeTy->getElementType();
558 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000559 // The Idx argument should be a pointer and the type of the pointer and
560 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000561 if (!ArgTy ||
562 !S.Context.hasSameType(
563 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000564 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000565 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000566 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000567 return true;
568 }
569 return false;
570}
571
572// \brief Performs semantic analysis for the read/write_pipe call.
573// \param S Reference to the semantic analyzer.
574// \param Call A pointer to the builtin call.
575// \return True if a semantic error has been found, false otherwise.
576static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000577 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
578 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000579 switch (Call->getNumArgs()) {
580 case 2: {
581 if (checkOpenCLPipeArg(S, Call))
582 return true;
583 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000584 // read/write_pipe(pipe T, T*).
585 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000586 if (checkOpenCLPipePacketType(S, Call, 1))
587 return true;
588 } break;
589
590 case 4: {
591 if (checkOpenCLPipeArg(S, Call))
592 return true;
593 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000594 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
595 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000596 if (!Call->getArg(1)->getType()->isReserveIDT()) {
597 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000598 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000599 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000600 return true;
601 }
602
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000603 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000604 const Expr *Arg2 = Call->getArg(2);
605 if (!Arg2->getType()->isIntegerType() &&
606 !Arg2->getType()->isUnsignedIntegerType()) {
607 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000608 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000609 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000610 return true;
611 }
612
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000613 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000614 if (checkOpenCLPipePacketType(S, Call, 3))
615 return true;
616 } break;
617 default:
618 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000619 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000620 return true;
621 }
622
623 return false;
624}
625
626// \brief Performs a semantic analysis on the {work_group_/sub_group_
627// /_}reserve_{read/write}_pipe
628// \param S Reference to the semantic analyzer.
629// \param Call The call to the builtin function to be analyzed.
630// \return True if a semantic error was found, false otherwise.
631static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
632 if (checkArgCount(S, Call, 2))
633 return true;
634
635 if (checkOpenCLPipeArg(S, Call))
636 return true;
637
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000638 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000639 if (!Call->getArg(1)->getType()->isIntegerType() &&
640 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
641 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000642 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000643 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000644 return true;
645 }
646
647 return false;
648}
649
650// \brief Performs a semantic analysis on {work_group_/sub_group_
651// /_}commit_{read/write}_pipe
652// \param S Reference to the semantic analyzer.
653// \param Call The call to the builtin function to be analyzed.
654// \return True if a semantic error was found, false otherwise.
655static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
656 if (checkArgCount(S, Call, 2))
657 return true;
658
659 if (checkOpenCLPipeArg(S, Call))
660 return true;
661
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000662 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000663 if (!Call->getArg(1)->getType()->isReserveIDT()) {
664 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000665 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000666 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000667 return true;
668 }
669
670 return false;
671}
672
673// \brief Performs a semantic analysis on the call to built-in Pipe
674// Query Functions.
675// \param S Reference to the semantic analyzer.
676// \param Call The call to the builtin function to be analyzed.
677// \return True if a semantic error was found, false otherwise.
678static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
679 if (checkArgCount(S, Call, 1))
680 return true;
681
682 if (!Call->getArg(0)->getType()->isPipeType()) {
683 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000684 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000685 return true;
686 }
687
688 return false;
689}
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +0000690// \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
Yaxun Liuf7449a12016-05-20 19:54:38 +0000691// \brief Performs semantic analysis for the to_global/local/private call.
692// \param S Reference to the semantic analyzer.
693// \param BuiltinID ID of the builtin function.
694// \param Call A pointer to the builtin call.
695// \return True if a semantic error has been found, false otherwise.
696static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
697 CallExpr *Call) {
Yaxun Liuf7449a12016-05-20 19:54:38 +0000698 if (Call->getNumArgs() != 1) {
699 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
700 << Call->getDirectCallee() << Call->getSourceRange();
701 return true;
702 }
703
704 auto RT = Call->getArg(0)->getType();
705 if (!RT->isPointerType() || RT->getPointeeType()
706 .getAddressSpace() == LangAS::opencl_constant) {
707 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
708 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
709 return true;
710 }
711
712 RT = RT->getPointeeType();
713 auto Qual = RT.getQualifiers();
714 switch (BuiltinID) {
715 case Builtin::BIto_global:
716 Qual.setAddressSpace(LangAS::opencl_global);
717 break;
718 case Builtin::BIto_local:
719 Qual.setAddressSpace(LangAS::opencl_local);
720 break;
721 default:
722 Qual.removeAddressSpace();
723 }
724 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
725 RT.getUnqualifiedType(), Qual)));
726
727 return false;
728}
729
John McCalldadc5752010-08-24 06:29:42 +0000730ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000731Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
732 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000733 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000734
Chris Lattner3be167f2010-10-01 23:23:24 +0000735 // Find out if any arguments are required to be integer constant expressions.
736 unsigned ICEArguments = 0;
737 ASTContext::GetBuiltinTypeError Error;
738 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
739 if (Error != ASTContext::GE_None)
740 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
741
742 // If any arguments are required to be ICE's, check and diagnose.
743 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
744 // Skip arguments not required to be ICE's.
745 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
746
747 llvm::APSInt Result;
748 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
749 return true;
750 ICEArguments &= ~(1 << ArgNo);
751 }
752
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000753 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000754 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000755 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000756 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000757 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000758 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000759 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000760 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000761 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000762 if (SemaBuiltinVAStart(TheCall))
763 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000764 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000765 case Builtin::BI__va_start: {
766 switch (Context.getTargetInfo().getTriple().getArch()) {
767 case llvm::Triple::arm:
768 case llvm::Triple::thumb:
769 if (SemaBuiltinVAStartARM(TheCall))
770 return ExprError();
771 break;
772 default:
773 if (SemaBuiltinVAStart(TheCall))
774 return ExprError();
775 break;
776 }
777 break;
778 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000779 case Builtin::BI__builtin_isgreater:
780 case Builtin::BI__builtin_isgreaterequal:
781 case Builtin::BI__builtin_isless:
782 case Builtin::BI__builtin_islessequal:
783 case Builtin::BI__builtin_islessgreater:
784 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000785 if (SemaBuiltinUnorderedCompare(TheCall))
786 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000787 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000788 case Builtin::BI__builtin_fpclassify:
789 if (SemaBuiltinFPClassification(TheCall, 6))
790 return ExprError();
791 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000792 case Builtin::BI__builtin_isfinite:
793 case Builtin::BI__builtin_isinf:
794 case Builtin::BI__builtin_isinf_sign:
795 case Builtin::BI__builtin_isnan:
796 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000797 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000798 return ExprError();
799 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000800 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000801 return SemaBuiltinShuffleVector(TheCall);
802 // TheCall will be freed by the smart pointer here, but that's fine, since
803 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000804 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000805 if (SemaBuiltinPrefetch(TheCall))
806 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000807 break;
David Majnemer51169932016-10-31 05:37:48 +0000808 case Builtin::BI__builtin_alloca_with_align:
809 if (SemaBuiltinAllocaWithAlign(TheCall))
810 return ExprError();
811 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000812 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000813 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000814 if (SemaBuiltinAssume(TheCall))
815 return ExprError();
816 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000817 case Builtin::BI__builtin_assume_aligned:
818 if (SemaBuiltinAssumeAligned(TheCall))
819 return ExprError();
820 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000821 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000822 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000823 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000824 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000825 case Builtin::BI__builtin_longjmp:
826 if (SemaBuiltinLongjmp(TheCall))
827 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000828 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000829 case Builtin::BI__builtin_setjmp:
830 if (SemaBuiltinSetjmp(TheCall))
831 return ExprError();
832 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000833 case Builtin::BI_setjmp:
834 case Builtin::BI_setjmpex:
835 if (checkArgCount(*this, TheCall, 1))
836 return true;
837 break;
John McCallbebede42011-02-26 05:39:39 +0000838
839 case Builtin::BI__builtin_classify_type:
840 if (checkArgCount(*this, TheCall, 1)) return true;
841 TheCall->setType(Context.IntTy);
842 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000843 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000844 if (checkArgCount(*this, TheCall, 1)) return true;
845 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000846 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000847 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000848 case Builtin::BI__sync_fetch_and_add_1:
849 case Builtin::BI__sync_fetch_and_add_2:
850 case Builtin::BI__sync_fetch_and_add_4:
851 case Builtin::BI__sync_fetch_and_add_8:
852 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000853 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000854 case Builtin::BI__sync_fetch_and_sub_1:
855 case Builtin::BI__sync_fetch_and_sub_2:
856 case Builtin::BI__sync_fetch_and_sub_4:
857 case Builtin::BI__sync_fetch_and_sub_8:
858 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000859 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000860 case Builtin::BI__sync_fetch_and_or_1:
861 case Builtin::BI__sync_fetch_and_or_2:
862 case Builtin::BI__sync_fetch_and_or_4:
863 case Builtin::BI__sync_fetch_and_or_8:
864 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000865 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000866 case Builtin::BI__sync_fetch_and_and_1:
867 case Builtin::BI__sync_fetch_and_and_2:
868 case Builtin::BI__sync_fetch_and_and_4:
869 case Builtin::BI__sync_fetch_and_and_8:
870 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000871 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000872 case Builtin::BI__sync_fetch_and_xor_1:
873 case Builtin::BI__sync_fetch_and_xor_2:
874 case Builtin::BI__sync_fetch_and_xor_4:
875 case Builtin::BI__sync_fetch_and_xor_8:
876 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000877 case Builtin::BI__sync_fetch_and_nand:
878 case Builtin::BI__sync_fetch_and_nand_1:
879 case Builtin::BI__sync_fetch_and_nand_2:
880 case Builtin::BI__sync_fetch_and_nand_4:
881 case Builtin::BI__sync_fetch_and_nand_8:
882 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000883 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000884 case Builtin::BI__sync_add_and_fetch_1:
885 case Builtin::BI__sync_add_and_fetch_2:
886 case Builtin::BI__sync_add_and_fetch_4:
887 case Builtin::BI__sync_add_and_fetch_8:
888 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000889 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000890 case Builtin::BI__sync_sub_and_fetch_1:
891 case Builtin::BI__sync_sub_and_fetch_2:
892 case Builtin::BI__sync_sub_and_fetch_4:
893 case Builtin::BI__sync_sub_and_fetch_8:
894 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000895 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000896 case Builtin::BI__sync_and_and_fetch_1:
897 case Builtin::BI__sync_and_and_fetch_2:
898 case Builtin::BI__sync_and_and_fetch_4:
899 case Builtin::BI__sync_and_and_fetch_8:
900 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000901 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000902 case Builtin::BI__sync_or_and_fetch_1:
903 case Builtin::BI__sync_or_and_fetch_2:
904 case Builtin::BI__sync_or_and_fetch_4:
905 case Builtin::BI__sync_or_and_fetch_8:
906 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000907 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000908 case Builtin::BI__sync_xor_and_fetch_1:
909 case Builtin::BI__sync_xor_and_fetch_2:
910 case Builtin::BI__sync_xor_and_fetch_4:
911 case Builtin::BI__sync_xor_and_fetch_8:
912 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000913 case Builtin::BI__sync_nand_and_fetch:
914 case Builtin::BI__sync_nand_and_fetch_1:
915 case Builtin::BI__sync_nand_and_fetch_2:
916 case Builtin::BI__sync_nand_and_fetch_4:
917 case Builtin::BI__sync_nand_and_fetch_8:
918 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000919 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000920 case Builtin::BI__sync_val_compare_and_swap_1:
921 case Builtin::BI__sync_val_compare_and_swap_2:
922 case Builtin::BI__sync_val_compare_and_swap_4:
923 case Builtin::BI__sync_val_compare_and_swap_8:
924 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000925 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000926 case Builtin::BI__sync_bool_compare_and_swap_1:
927 case Builtin::BI__sync_bool_compare_and_swap_2:
928 case Builtin::BI__sync_bool_compare_and_swap_4:
929 case Builtin::BI__sync_bool_compare_and_swap_8:
930 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000931 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000932 case Builtin::BI__sync_lock_test_and_set_1:
933 case Builtin::BI__sync_lock_test_and_set_2:
934 case Builtin::BI__sync_lock_test_and_set_4:
935 case Builtin::BI__sync_lock_test_and_set_8:
936 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000937 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000938 case Builtin::BI__sync_lock_release_1:
939 case Builtin::BI__sync_lock_release_2:
940 case Builtin::BI__sync_lock_release_4:
941 case Builtin::BI__sync_lock_release_8:
942 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000943 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000944 case Builtin::BI__sync_swap_1:
945 case Builtin::BI__sync_swap_2:
946 case Builtin::BI__sync_swap_4:
947 case Builtin::BI__sync_swap_8:
948 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000949 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000950 case Builtin::BI__builtin_nontemporal_load:
951 case Builtin::BI__builtin_nontemporal_store:
952 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000953#define BUILTIN(ID, TYPE, ATTRS)
954#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
955 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000956 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000957#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000958 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000959 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000960 return ExprError();
961 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000962 case Builtin::BI__builtin_addressof:
963 if (SemaBuiltinAddressof(*this, TheCall))
964 return ExprError();
965 break;
John McCall03107a42015-10-29 20:48:01 +0000966 case Builtin::BI__builtin_add_overflow:
967 case Builtin::BI__builtin_sub_overflow:
968 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +0000969 if (SemaBuiltinOverflow(*this, TheCall))
970 return ExprError();
971 break;
Richard Smith760520b2014-06-03 23:27:44 +0000972 case Builtin::BI__builtin_operator_new:
973 case Builtin::BI__builtin_operator_delete:
974 if (!getLangOpts().CPlusPlus) {
975 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
976 << (BuiltinID == Builtin::BI__builtin_operator_new
977 ? "__builtin_operator_new"
978 : "__builtin_operator_delete")
979 << "C++";
980 return ExprError();
981 }
982 // CodeGen assumes it can find the global new and delete to call,
983 // so ensure that they are declared.
984 DeclareGlobalNewDelete();
985 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000986
987 // check secure string manipulation functions where overflows
988 // are detectable at compile time
989 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000990 case Builtin::BI__builtin___memmove_chk:
991 case Builtin::BI__builtin___memset_chk:
992 case Builtin::BI__builtin___strlcat_chk:
993 case Builtin::BI__builtin___strlcpy_chk:
994 case Builtin::BI__builtin___strncat_chk:
995 case Builtin::BI__builtin___strncpy_chk:
996 case Builtin::BI__builtin___stpncpy_chk:
997 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
998 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000999 case Builtin::BI__builtin___memccpy_chk:
1000 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1001 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001002 case Builtin::BI__builtin___snprintf_chk:
1003 case Builtin::BI__builtin___vsnprintf_chk:
1004 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1005 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001006 case Builtin::BI__builtin_call_with_static_chain:
1007 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1008 return ExprError();
1009 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001010 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001011 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001012 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1013 diag::err_seh___except_block))
1014 return ExprError();
1015 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001016 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001017 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001018 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1019 diag::err_seh___except_filter))
1020 return ExprError();
1021 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001022 case Builtin::BI__GetExceptionInfo:
1023 if (checkArgCount(*this, TheCall, 1))
1024 return ExprError();
1025
1026 if (CheckCXXThrowOperand(
1027 TheCall->getLocStart(),
1028 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1029 TheCall))
1030 return ExprError();
1031
1032 TheCall->setType(Context.VoidPtrTy);
1033 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001034 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001035 case Builtin::BIread_pipe:
1036 case Builtin::BIwrite_pipe:
1037 // Since those two functions are declared with var args, we need a semantic
1038 // check for the argument.
1039 if (SemaBuiltinRWPipe(*this, TheCall))
1040 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001041 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001042 break;
1043 case Builtin::BIreserve_read_pipe:
1044 case Builtin::BIreserve_write_pipe:
1045 case Builtin::BIwork_group_reserve_read_pipe:
1046 case Builtin::BIwork_group_reserve_write_pipe:
1047 case Builtin::BIsub_group_reserve_read_pipe:
1048 case Builtin::BIsub_group_reserve_write_pipe:
1049 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1050 return ExprError();
1051 // Since return type of reserve_read/write_pipe built-in function is
1052 // reserve_id_t, which is not defined in the builtin def file , we used int
1053 // as return type and need to override the return type of these functions.
1054 TheCall->setType(Context.OCLReserveIDTy);
1055 break;
1056 case Builtin::BIcommit_read_pipe:
1057 case Builtin::BIcommit_write_pipe:
1058 case Builtin::BIwork_group_commit_read_pipe:
1059 case Builtin::BIwork_group_commit_write_pipe:
1060 case Builtin::BIsub_group_commit_read_pipe:
1061 case Builtin::BIsub_group_commit_write_pipe:
1062 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1063 return ExprError();
1064 break;
1065 case Builtin::BIget_pipe_num_packets:
1066 case Builtin::BIget_pipe_max_packets:
1067 if (SemaBuiltinPipePackets(*this, TheCall))
1068 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001069 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001070 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001071 case Builtin::BIto_global:
1072 case Builtin::BIto_local:
1073 case Builtin::BIto_private:
1074 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1075 return ExprError();
1076 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001077 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1078 case Builtin::BIenqueue_kernel:
1079 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1080 return ExprError();
1081 break;
1082 case Builtin::BIget_kernel_work_group_size:
1083 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1084 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1085 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001086 break;
1087 case Builtin::BI__builtin_os_log_format:
1088 case Builtin::BI__builtin_os_log_format_buffer_size:
1089 if (SemaBuiltinOSLogFormat(TheCall)) {
1090 return ExprError();
1091 }
1092 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001093 }
Richard Smith760520b2014-06-03 23:27:44 +00001094
Nate Begeman4904e322010-06-08 02:47:44 +00001095 // Since the target specific builtins for each arch overlap, only check those
1096 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001097 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001098 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001099 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001100 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001101 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001102 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001103 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1104 return ExprError();
1105 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001106 case llvm::Triple::aarch64:
1107 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001108 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001109 return ExprError();
1110 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001111 case llvm::Triple::mips:
1112 case llvm::Triple::mipsel:
1113 case llvm::Triple::mips64:
1114 case llvm::Triple::mips64el:
1115 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1116 return ExprError();
1117 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001118 case llvm::Triple::systemz:
1119 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1120 return ExprError();
1121 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001122 case llvm::Triple::x86:
1123 case llvm::Triple::x86_64:
1124 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1125 return ExprError();
1126 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001127 case llvm::Triple::ppc:
1128 case llvm::Triple::ppc64:
1129 case llvm::Triple::ppc64le:
1130 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1131 return ExprError();
1132 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001133 default:
1134 break;
1135 }
1136 }
1137
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001138 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001139}
1140
Nate Begeman91e1fea2010-06-14 05:21:25 +00001141// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001142static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001143 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001144 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001145 switch (Type.getEltType()) {
1146 case NeonTypeFlags::Int8:
1147 case NeonTypeFlags::Poly8:
1148 return shift ? 7 : (8 << IsQuad) - 1;
1149 case NeonTypeFlags::Int16:
1150 case NeonTypeFlags::Poly16:
1151 return shift ? 15 : (4 << IsQuad) - 1;
1152 case NeonTypeFlags::Int32:
1153 return shift ? 31 : (2 << IsQuad) - 1;
1154 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001155 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001156 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001157 case NeonTypeFlags::Poly128:
1158 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001159 case NeonTypeFlags::Float16:
1160 assert(!shift && "cannot shift float types!");
1161 return (4 << IsQuad) - 1;
1162 case NeonTypeFlags::Float32:
1163 assert(!shift && "cannot shift float types!");
1164 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001165 case NeonTypeFlags::Float64:
1166 assert(!shift && "cannot shift float types!");
1167 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001168 }
David Blaikie8a40f702012-01-17 06:56:22 +00001169 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001170}
1171
Bob Wilsone4d77232011-11-08 05:04:11 +00001172/// getNeonEltType - Return the QualType corresponding to the elements of
1173/// the vector type specified by the NeonTypeFlags. This is used to check
1174/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001175static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001176 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001177 switch (Flags.getEltType()) {
1178 case NeonTypeFlags::Int8:
1179 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1180 case NeonTypeFlags::Int16:
1181 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1182 case NeonTypeFlags::Int32:
1183 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1184 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001185 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001186 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1187 else
1188 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1189 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001190 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001191 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001192 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001193 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001194 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001195 if (IsInt64Long)
1196 return Context.UnsignedLongTy;
1197 else
1198 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001199 case NeonTypeFlags::Poly128:
1200 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001201 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001202 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001203 case NeonTypeFlags::Float32:
1204 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001205 case NeonTypeFlags::Float64:
1206 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001207 }
David Blaikie8a40f702012-01-17 06:56:22 +00001208 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001209}
1210
Tim Northover12670412014-02-19 10:37:05 +00001211bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001212 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001213 uint64_t mask = 0;
1214 unsigned TV = 0;
1215 int PtrArgNum = -1;
1216 bool HasConstPtr = false;
1217 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001218#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001219#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001220#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001221 }
1222
1223 // For NEON intrinsics which are overloaded on vector element type, validate
1224 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001225 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001226 if (mask) {
1227 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1228 return true;
1229
1230 TV = Result.getLimitedValue(64);
1231 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1232 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001233 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001234 }
1235
1236 if (PtrArgNum >= 0) {
1237 // Check that pointer arguments have the specified type.
1238 Expr *Arg = TheCall->getArg(PtrArgNum);
1239 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1240 Arg = ICE->getSubExpr();
1241 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1242 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001243
Tim Northovera2ee4332014-03-29 15:09:45 +00001244 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001245 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1246 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001247 bool IsInt64Long =
1248 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1249 QualType EltTy =
1250 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001251 if (HasConstPtr)
1252 EltTy = EltTy.withConst();
1253 QualType LHSTy = Context.getPointerType(EltTy);
1254 AssignConvertType ConvTy;
1255 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1256 if (RHS.isInvalid())
1257 return true;
1258 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1259 RHS.get(), AA_Assigning))
1260 return true;
1261 }
1262
1263 // For NEON intrinsics which take an immediate value as part of the
1264 // instruction, range check them here.
1265 unsigned i = 0, l = 0, u = 0;
1266 switch (BuiltinID) {
1267 default:
1268 return false;
Tim Northover12670412014-02-19 10:37:05 +00001269#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001270#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001271#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001272 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001273
Richard Sandiford28940af2014-04-16 08:47:51 +00001274 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001275}
1276
Tim Northovera2ee4332014-03-29 15:09:45 +00001277bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1278 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001279 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001280 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001281 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001282 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001283 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001284 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1285 BuiltinID == AArch64::BI__builtin_arm_strex ||
1286 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001287 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001288 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001289 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1290 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1291 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001292
1293 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1294
1295 // Ensure that we have the proper number of arguments.
1296 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1297 return true;
1298
1299 // Inspect the pointer argument of the atomic builtin. This should always be
1300 // a pointer type, whose element is an integral scalar or pointer type.
1301 // Because it is a pointer type, we don't have to worry about any implicit
1302 // casts here.
1303 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1304 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1305 if (PointerArgRes.isInvalid())
1306 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001307 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001308
1309 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1310 if (!pointerType) {
1311 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1312 << PointerArg->getType() << PointerArg->getSourceRange();
1313 return true;
1314 }
1315
1316 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1317 // task is to insert the appropriate casts into the AST. First work out just
1318 // what the appropriate type is.
1319 QualType ValType = pointerType->getPointeeType();
1320 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1321 if (IsLdrex)
1322 AddrType.addConst();
1323
1324 // Issue a warning if the cast is dodgy.
1325 CastKind CastNeeded = CK_NoOp;
1326 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1327 CastNeeded = CK_BitCast;
1328 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1329 << PointerArg->getType()
1330 << Context.getPointerType(AddrType)
1331 << AA_Passing << PointerArg->getSourceRange();
1332 }
1333
1334 // Finally, do the cast and replace the argument with the corrected version.
1335 AddrType = Context.getPointerType(AddrType);
1336 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1337 if (PointerArgRes.isInvalid())
1338 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001339 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001340
1341 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1342
1343 // In general, we allow ints, floats and pointers to be loaded and stored.
1344 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1345 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1346 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1347 << PointerArg->getType() << PointerArg->getSourceRange();
1348 return true;
1349 }
1350
1351 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001352 if (Context.getTypeSize(ValType) > MaxWidth) {
1353 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001354 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1355 << PointerArg->getType() << PointerArg->getSourceRange();
1356 return true;
1357 }
1358
1359 switch (ValType.getObjCLifetime()) {
1360 case Qualifiers::OCL_None:
1361 case Qualifiers::OCL_ExplicitNone:
1362 // okay
1363 break;
1364
1365 case Qualifiers::OCL_Weak:
1366 case Qualifiers::OCL_Strong:
1367 case Qualifiers::OCL_Autoreleasing:
1368 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1369 << ValType << PointerArg->getSourceRange();
1370 return true;
1371 }
1372
Tim Northover6aacd492013-07-16 09:47:53 +00001373 if (IsLdrex) {
1374 TheCall->setType(ValType);
1375 return false;
1376 }
1377
1378 // Initialize the argument to be stored.
1379 ExprResult ValArg = TheCall->getArg(0);
1380 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1381 Context, ValType, /*consume*/ false);
1382 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1383 if (ValArg.isInvalid())
1384 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001385 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001386
1387 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1388 // but the custom checker bypasses all default analysis.
1389 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001390 return false;
1391}
1392
Nate Begeman4904e322010-06-08 02:47:44 +00001393bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +00001394 llvm::APSInt Result;
1395
Tim Northover6aacd492013-07-16 09:47:53 +00001396 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001397 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1398 BuiltinID == ARM::BI__builtin_arm_strex ||
1399 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001400 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001401 }
1402
Yi Kong26d104a2014-08-13 19:18:14 +00001403 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1404 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1405 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1406 }
1407
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001408 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1409 BuiltinID == ARM::BI__builtin_arm_wsr64)
1410 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1411
1412 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1413 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1414 BuiltinID == ARM::BI__builtin_arm_wsr ||
1415 BuiltinID == ARM::BI__builtin_arm_wsrp)
1416 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1417
Tim Northover12670412014-02-19 10:37:05 +00001418 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1419 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001420
Yi Kong4efadfb2014-07-03 16:01:25 +00001421 // For intrinsics which take an immediate value as part of the instruction,
1422 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001423 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001424 switch (BuiltinID) {
1425 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001426 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1427 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001428 case ARM::BI__builtin_arm_vcvtr_f:
1429 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001430 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001431 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001432 case ARM::BI__builtin_arm_isb:
1433 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001434 }
Nate Begemand773fe62010-06-13 04:47:52 +00001435
Nate Begemanf568b072010-08-03 21:32:34 +00001436 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001437 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001438}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001439
Tim Northover573cbee2014-05-24 12:52:07 +00001440bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001441 CallExpr *TheCall) {
1442 llvm::APSInt Result;
1443
Tim Northover573cbee2014-05-24 12:52:07 +00001444 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001445 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1446 BuiltinID == AArch64::BI__builtin_arm_strex ||
1447 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001448 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1449 }
1450
Yi Konga5548432014-08-13 19:18:20 +00001451 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1452 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1453 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1454 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1455 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1456 }
1457
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001458 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1459 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001460 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001461
1462 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1463 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1464 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1465 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1466 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1467
Tim Northovera2ee4332014-03-29 15:09:45 +00001468 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1469 return true;
1470
Yi Kong19a29ac2014-07-17 10:52:06 +00001471 // For intrinsics which take an immediate value as part of the instruction,
1472 // range check them here.
1473 unsigned i = 0, l = 0, u = 0;
1474 switch (BuiltinID) {
1475 default: return false;
1476 case AArch64::BI__builtin_arm_dmb:
1477 case AArch64::BI__builtin_arm_dsb:
1478 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1479 }
1480
Yi Kong19a29ac2014-07-17 10:52:06 +00001481 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001482}
1483
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001484// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1485// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1486// ordering for DSP is unspecified. MSA is ordered by the data format used
1487// by the underlying instruction i.e., df/m, df/n and then by size.
1488//
1489// FIXME: The size tests here should instead be tablegen'd along with the
1490// definitions from include/clang/Basic/BuiltinsMips.def.
1491// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1492// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001493bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001494 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001495 switch (BuiltinID) {
1496 default: return false;
1497 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1498 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001499 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1500 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1501 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1502 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1503 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001504 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1505 // df/m field.
1506 // These intrinsics take an unsigned 3 bit immediate.
1507 case Mips::BI__builtin_msa_bclri_b:
1508 case Mips::BI__builtin_msa_bnegi_b:
1509 case Mips::BI__builtin_msa_bseti_b:
1510 case Mips::BI__builtin_msa_sat_s_b:
1511 case Mips::BI__builtin_msa_sat_u_b:
1512 case Mips::BI__builtin_msa_slli_b:
1513 case Mips::BI__builtin_msa_srai_b:
1514 case Mips::BI__builtin_msa_srari_b:
1515 case Mips::BI__builtin_msa_srli_b:
1516 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1517 case Mips::BI__builtin_msa_binsli_b:
1518 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1519 // These intrinsics take an unsigned 4 bit immediate.
1520 case Mips::BI__builtin_msa_bclri_h:
1521 case Mips::BI__builtin_msa_bnegi_h:
1522 case Mips::BI__builtin_msa_bseti_h:
1523 case Mips::BI__builtin_msa_sat_s_h:
1524 case Mips::BI__builtin_msa_sat_u_h:
1525 case Mips::BI__builtin_msa_slli_h:
1526 case Mips::BI__builtin_msa_srai_h:
1527 case Mips::BI__builtin_msa_srari_h:
1528 case Mips::BI__builtin_msa_srli_h:
1529 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1530 case Mips::BI__builtin_msa_binsli_h:
1531 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1532 // These intrinsics take an unsigned 5 bit immedate.
1533 // The first block of intrinsics actually have an unsigned 5 bit field,
1534 // not a df/n field.
1535 case Mips::BI__builtin_msa_clei_u_b:
1536 case Mips::BI__builtin_msa_clei_u_h:
1537 case Mips::BI__builtin_msa_clei_u_w:
1538 case Mips::BI__builtin_msa_clei_u_d:
1539 case Mips::BI__builtin_msa_clti_u_b:
1540 case Mips::BI__builtin_msa_clti_u_h:
1541 case Mips::BI__builtin_msa_clti_u_w:
1542 case Mips::BI__builtin_msa_clti_u_d:
1543 case Mips::BI__builtin_msa_maxi_u_b:
1544 case Mips::BI__builtin_msa_maxi_u_h:
1545 case Mips::BI__builtin_msa_maxi_u_w:
1546 case Mips::BI__builtin_msa_maxi_u_d:
1547 case Mips::BI__builtin_msa_mini_u_b:
1548 case Mips::BI__builtin_msa_mini_u_h:
1549 case Mips::BI__builtin_msa_mini_u_w:
1550 case Mips::BI__builtin_msa_mini_u_d:
1551 case Mips::BI__builtin_msa_addvi_b:
1552 case Mips::BI__builtin_msa_addvi_h:
1553 case Mips::BI__builtin_msa_addvi_w:
1554 case Mips::BI__builtin_msa_addvi_d:
1555 case Mips::BI__builtin_msa_bclri_w:
1556 case Mips::BI__builtin_msa_bnegi_w:
1557 case Mips::BI__builtin_msa_bseti_w:
1558 case Mips::BI__builtin_msa_sat_s_w:
1559 case Mips::BI__builtin_msa_sat_u_w:
1560 case Mips::BI__builtin_msa_slli_w:
1561 case Mips::BI__builtin_msa_srai_w:
1562 case Mips::BI__builtin_msa_srari_w:
1563 case Mips::BI__builtin_msa_srli_w:
1564 case Mips::BI__builtin_msa_srlri_w:
1565 case Mips::BI__builtin_msa_subvi_b:
1566 case Mips::BI__builtin_msa_subvi_h:
1567 case Mips::BI__builtin_msa_subvi_w:
1568 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1569 case Mips::BI__builtin_msa_binsli_w:
1570 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1571 // These intrinsics take an unsigned 6 bit immediate.
1572 case Mips::BI__builtin_msa_bclri_d:
1573 case Mips::BI__builtin_msa_bnegi_d:
1574 case Mips::BI__builtin_msa_bseti_d:
1575 case Mips::BI__builtin_msa_sat_s_d:
1576 case Mips::BI__builtin_msa_sat_u_d:
1577 case Mips::BI__builtin_msa_slli_d:
1578 case Mips::BI__builtin_msa_srai_d:
1579 case Mips::BI__builtin_msa_srari_d:
1580 case Mips::BI__builtin_msa_srli_d:
1581 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1582 case Mips::BI__builtin_msa_binsli_d:
1583 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1584 // These intrinsics take a signed 5 bit immediate.
1585 case Mips::BI__builtin_msa_ceqi_b:
1586 case Mips::BI__builtin_msa_ceqi_h:
1587 case Mips::BI__builtin_msa_ceqi_w:
1588 case Mips::BI__builtin_msa_ceqi_d:
1589 case Mips::BI__builtin_msa_clti_s_b:
1590 case Mips::BI__builtin_msa_clti_s_h:
1591 case Mips::BI__builtin_msa_clti_s_w:
1592 case Mips::BI__builtin_msa_clti_s_d:
1593 case Mips::BI__builtin_msa_clei_s_b:
1594 case Mips::BI__builtin_msa_clei_s_h:
1595 case Mips::BI__builtin_msa_clei_s_w:
1596 case Mips::BI__builtin_msa_clei_s_d:
1597 case Mips::BI__builtin_msa_maxi_s_b:
1598 case Mips::BI__builtin_msa_maxi_s_h:
1599 case Mips::BI__builtin_msa_maxi_s_w:
1600 case Mips::BI__builtin_msa_maxi_s_d:
1601 case Mips::BI__builtin_msa_mini_s_b:
1602 case Mips::BI__builtin_msa_mini_s_h:
1603 case Mips::BI__builtin_msa_mini_s_w:
1604 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1605 // These intrinsics take an unsigned 8 bit immediate.
1606 case Mips::BI__builtin_msa_andi_b:
1607 case Mips::BI__builtin_msa_nori_b:
1608 case Mips::BI__builtin_msa_ori_b:
1609 case Mips::BI__builtin_msa_shf_b:
1610 case Mips::BI__builtin_msa_shf_h:
1611 case Mips::BI__builtin_msa_shf_w:
1612 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1613 case Mips::BI__builtin_msa_bseli_b:
1614 case Mips::BI__builtin_msa_bmnzi_b:
1615 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1616 // df/n format
1617 // These intrinsics take an unsigned 4 bit immediate.
1618 case Mips::BI__builtin_msa_copy_s_b:
1619 case Mips::BI__builtin_msa_copy_u_b:
1620 case Mips::BI__builtin_msa_insve_b:
1621 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001622 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1623 // These intrinsics take an unsigned 3 bit immediate.
1624 case Mips::BI__builtin_msa_copy_s_h:
1625 case Mips::BI__builtin_msa_copy_u_h:
1626 case Mips::BI__builtin_msa_insve_h:
1627 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001628 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1629 // These intrinsics take an unsigned 2 bit immediate.
1630 case Mips::BI__builtin_msa_copy_s_w:
1631 case Mips::BI__builtin_msa_copy_u_w:
1632 case Mips::BI__builtin_msa_insve_w:
1633 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001634 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1635 // These intrinsics take an unsigned 1 bit immediate.
1636 case Mips::BI__builtin_msa_copy_s_d:
1637 case Mips::BI__builtin_msa_copy_u_d:
1638 case Mips::BI__builtin_msa_insve_d:
1639 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001640 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1641 // Memory offsets and immediate loads.
1642 // These intrinsics take a signed 10 bit immediate.
1643 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 127; break;
1644 case Mips::BI__builtin_msa_ldi_h:
1645 case Mips::BI__builtin_msa_ldi_w:
1646 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1647 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1648 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1649 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1650 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1651 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1652 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1653 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1654 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001655 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001656
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001657 if (!m)
1658 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1659
1660 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1661 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001662}
1663
Kit Bartone50adcb2015-03-30 19:40:59 +00001664bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1665 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001666 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1667 BuiltinID == PPC::BI__builtin_divdeu ||
1668 BuiltinID == PPC::BI__builtin_bpermd;
1669 bool IsTarget64Bit = Context.getTargetInfo()
1670 .getTypeWidth(Context
1671 .getTargetInfo()
1672 .getIntPtrType()) == 64;
1673 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1674 BuiltinID == PPC::BI__builtin_divweu ||
1675 BuiltinID == PPC::BI__builtin_divde ||
1676 BuiltinID == PPC::BI__builtin_divdeu;
1677
1678 if (Is64BitBltin && !IsTarget64Bit)
1679 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1680 << TheCall->getSourceRange();
1681
1682 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1683 (BuiltinID == PPC::BI__builtin_bpermd &&
1684 !Context.getTargetInfo().hasFeature("bpermd")))
1685 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1686 << TheCall->getSourceRange();
1687
Kit Bartone50adcb2015-03-30 19:40:59 +00001688 switch (BuiltinID) {
1689 default: return false;
1690 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1691 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1692 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1693 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1694 case PPC::BI__builtin_tbegin:
1695 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1696 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1697 case PPC::BI__builtin_tabortwc:
1698 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1699 case PPC::BI__builtin_tabortwci:
1700 case PPC::BI__builtin_tabortdci:
1701 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1702 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1703 }
1704 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1705}
1706
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001707bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1708 CallExpr *TheCall) {
1709 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1710 Expr *Arg = TheCall->getArg(0);
1711 llvm::APSInt AbortCode(32);
1712 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1713 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1714 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1715 << Arg->getSourceRange();
1716 }
1717
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001718 // For intrinsics which take an immediate value as part of the instruction,
1719 // range check them here.
1720 unsigned i = 0, l = 0, u = 0;
1721 switch (BuiltinID) {
1722 default: return false;
1723 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1724 case SystemZ::BI__builtin_s390_verimb:
1725 case SystemZ::BI__builtin_s390_verimh:
1726 case SystemZ::BI__builtin_s390_verimf:
1727 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1728 case SystemZ::BI__builtin_s390_vfaeb:
1729 case SystemZ::BI__builtin_s390_vfaeh:
1730 case SystemZ::BI__builtin_s390_vfaef:
1731 case SystemZ::BI__builtin_s390_vfaebs:
1732 case SystemZ::BI__builtin_s390_vfaehs:
1733 case SystemZ::BI__builtin_s390_vfaefs:
1734 case SystemZ::BI__builtin_s390_vfaezb:
1735 case SystemZ::BI__builtin_s390_vfaezh:
1736 case SystemZ::BI__builtin_s390_vfaezf:
1737 case SystemZ::BI__builtin_s390_vfaezbs:
1738 case SystemZ::BI__builtin_s390_vfaezhs:
1739 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1740 case SystemZ::BI__builtin_s390_vfidb:
1741 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1742 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1743 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1744 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1745 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1746 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1747 case SystemZ::BI__builtin_s390_vstrcb:
1748 case SystemZ::BI__builtin_s390_vstrch:
1749 case SystemZ::BI__builtin_s390_vstrcf:
1750 case SystemZ::BI__builtin_s390_vstrczb:
1751 case SystemZ::BI__builtin_s390_vstrczh:
1752 case SystemZ::BI__builtin_s390_vstrczf:
1753 case SystemZ::BI__builtin_s390_vstrcbs:
1754 case SystemZ::BI__builtin_s390_vstrchs:
1755 case SystemZ::BI__builtin_s390_vstrcfs:
1756 case SystemZ::BI__builtin_s390_vstrczbs:
1757 case SystemZ::BI__builtin_s390_vstrczhs:
1758 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1759 }
1760 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001761}
1762
Craig Topper5ba2c502015-11-07 08:08:31 +00001763/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1764/// This checks that the target supports __builtin_cpu_supports and
1765/// that the string argument is constant and valid.
1766static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1767 Expr *Arg = TheCall->getArg(0);
1768
1769 // Check if the argument is a string literal.
1770 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1771 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1772 << Arg->getSourceRange();
1773
1774 // Check the contents of the string.
1775 StringRef Feature =
1776 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1777 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1778 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1779 << Arg->getSourceRange();
1780 return false;
1781}
1782
Craig Toppera7e253e2016-09-23 04:48:31 +00001783// Check if the rounding mode is legal.
1784bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1785 // Indicates if this instruction has rounding control or just SAE.
1786 bool HasRC = false;
1787
1788 unsigned ArgNum = 0;
1789 switch (BuiltinID) {
1790 default:
1791 return false;
1792 case X86::BI__builtin_ia32_vcvttsd2si32:
1793 case X86::BI__builtin_ia32_vcvttsd2si64:
1794 case X86::BI__builtin_ia32_vcvttsd2usi32:
1795 case X86::BI__builtin_ia32_vcvttsd2usi64:
1796 case X86::BI__builtin_ia32_vcvttss2si32:
1797 case X86::BI__builtin_ia32_vcvttss2si64:
1798 case X86::BI__builtin_ia32_vcvttss2usi32:
1799 case X86::BI__builtin_ia32_vcvttss2usi64:
1800 ArgNum = 1;
1801 break;
1802 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1803 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1804 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1805 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1806 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1807 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1808 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1809 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1810 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1811 case X86::BI__builtin_ia32_exp2pd_mask:
1812 case X86::BI__builtin_ia32_exp2ps_mask:
1813 case X86::BI__builtin_ia32_getexppd512_mask:
1814 case X86::BI__builtin_ia32_getexpps512_mask:
1815 case X86::BI__builtin_ia32_rcp28pd_mask:
1816 case X86::BI__builtin_ia32_rcp28ps_mask:
1817 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1818 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1819 case X86::BI__builtin_ia32_vcomisd:
1820 case X86::BI__builtin_ia32_vcomiss:
1821 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1822 ArgNum = 3;
1823 break;
1824 case X86::BI__builtin_ia32_cmppd512_mask:
1825 case X86::BI__builtin_ia32_cmpps512_mask:
1826 case X86::BI__builtin_ia32_cmpsd_mask:
1827 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001828 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001829 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1830 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001831 case X86::BI__builtin_ia32_maxpd512_mask:
1832 case X86::BI__builtin_ia32_maxps512_mask:
1833 case X86::BI__builtin_ia32_maxsd_round_mask:
1834 case X86::BI__builtin_ia32_maxss_round_mask:
1835 case X86::BI__builtin_ia32_minpd512_mask:
1836 case X86::BI__builtin_ia32_minps512_mask:
1837 case X86::BI__builtin_ia32_minsd_round_mask:
1838 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001839 case X86::BI__builtin_ia32_rcp28sd_round_mask:
1840 case X86::BI__builtin_ia32_rcp28ss_round_mask:
1841 case X86::BI__builtin_ia32_reducepd512_mask:
1842 case X86::BI__builtin_ia32_reduceps512_mask:
1843 case X86::BI__builtin_ia32_rndscalepd_mask:
1844 case X86::BI__builtin_ia32_rndscaleps_mask:
1845 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1846 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1847 ArgNum = 4;
1848 break;
1849 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001850 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001851 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001852 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001853 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001854 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001855 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001856 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001857 case X86::BI__builtin_ia32_rangepd512_mask:
1858 case X86::BI__builtin_ia32_rangeps512_mask:
1859 case X86::BI__builtin_ia32_rangesd128_round_mask:
1860 case X86::BI__builtin_ia32_rangess128_round_mask:
1861 case X86::BI__builtin_ia32_reducesd_mask:
1862 case X86::BI__builtin_ia32_reducess_mask:
1863 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1864 case X86::BI__builtin_ia32_rndscaless_round_mask:
1865 ArgNum = 5;
1866 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00001867 case X86::BI__builtin_ia32_vcvtsd2si64:
1868 case X86::BI__builtin_ia32_vcvtsd2si32:
1869 case X86::BI__builtin_ia32_vcvtsd2usi32:
1870 case X86::BI__builtin_ia32_vcvtsd2usi64:
1871 case X86::BI__builtin_ia32_vcvtss2si32:
1872 case X86::BI__builtin_ia32_vcvtss2si64:
1873 case X86::BI__builtin_ia32_vcvtss2usi32:
1874 case X86::BI__builtin_ia32_vcvtss2usi64:
1875 ArgNum = 1;
1876 HasRC = true;
1877 break;
Craig Topper8e066312016-11-07 07:01:09 +00001878 case X86::BI__builtin_ia32_cvtsi2sd64:
1879 case X86::BI__builtin_ia32_cvtsi2ss32:
1880 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00001881 case X86::BI__builtin_ia32_cvtusi2sd64:
1882 case X86::BI__builtin_ia32_cvtusi2ss32:
1883 case X86::BI__builtin_ia32_cvtusi2ss64:
1884 ArgNum = 2;
1885 HasRC = true;
1886 break;
1887 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1888 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1889 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1890 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1891 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1892 case X86::BI__builtin_ia32_cvtps2qq512_mask:
1893 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1894 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1895 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1896 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1897 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001898 case X86::BI__builtin_ia32_sqrtpd512_mask:
1899 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001900 ArgNum = 3;
1901 HasRC = true;
1902 break;
1903 case X86::BI__builtin_ia32_addpd512_mask:
1904 case X86::BI__builtin_ia32_addps512_mask:
1905 case X86::BI__builtin_ia32_divpd512_mask:
1906 case X86::BI__builtin_ia32_divps512_mask:
1907 case X86::BI__builtin_ia32_mulpd512_mask:
1908 case X86::BI__builtin_ia32_mulps512_mask:
1909 case X86::BI__builtin_ia32_subpd512_mask:
1910 case X86::BI__builtin_ia32_subps512_mask:
1911 case X86::BI__builtin_ia32_addss_round_mask:
1912 case X86::BI__builtin_ia32_addsd_round_mask:
1913 case X86::BI__builtin_ia32_divss_round_mask:
1914 case X86::BI__builtin_ia32_divsd_round_mask:
1915 case X86::BI__builtin_ia32_mulss_round_mask:
1916 case X86::BI__builtin_ia32_mulsd_round_mask:
1917 case X86::BI__builtin_ia32_subss_round_mask:
1918 case X86::BI__builtin_ia32_subsd_round_mask:
1919 case X86::BI__builtin_ia32_scalefpd512_mask:
1920 case X86::BI__builtin_ia32_scalefps512_mask:
1921 case X86::BI__builtin_ia32_scalefsd_round_mask:
1922 case X86::BI__builtin_ia32_scalefss_round_mask:
1923 case X86::BI__builtin_ia32_getmantpd512_mask:
1924 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001925 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
1926 case X86::BI__builtin_ia32_sqrtsd_round_mask:
1927 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001928 case X86::BI__builtin_ia32_vfmaddpd512_mask:
1929 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1930 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1931 case X86::BI__builtin_ia32_vfmaddps512_mask:
1932 case X86::BI__builtin_ia32_vfmaddps512_mask3:
1933 case X86::BI__builtin_ia32_vfmaddps512_maskz:
1934 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1935 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1936 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1937 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1938 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1939 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1940 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1941 case X86::BI__builtin_ia32_vfmsubps512_mask3:
1942 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1943 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1944 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1945 case X86::BI__builtin_ia32_vfnmaddps512_mask:
1946 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1947 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1948 case X86::BI__builtin_ia32_vfnmsubps512_mask:
1949 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1950 case X86::BI__builtin_ia32_vfmaddsd3_mask:
1951 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1952 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1953 case X86::BI__builtin_ia32_vfmaddss3_mask:
1954 case X86::BI__builtin_ia32_vfmaddss3_maskz:
1955 case X86::BI__builtin_ia32_vfmaddss3_mask3:
1956 ArgNum = 4;
1957 HasRC = true;
1958 break;
1959 case X86::BI__builtin_ia32_getmantsd_round_mask:
1960 case X86::BI__builtin_ia32_getmantss_round_mask:
1961 ArgNum = 5;
1962 HasRC = true;
1963 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00001964 }
1965
1966 llvm::APSInt Result;
1967
1968 // We can't check the value of a dependent argument.
1969 Expr *Arg = TheCall->getArg(ArgNum);
1970 if (Arg->isTypeDependent() || Arg->isValueDependent())
1971 return false;
1972
1973 // Check constant-ness first.
1974 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1975 return true;
1976
1977 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1978 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1979 // combined with ROUND_NO_EXC.
1980 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1981 Result == 8/*ROUND_NO_EXC*/ ||
1982 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1983 return false;
1984
1985 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1986 << Arg->getSourceRange();
1987}
1988
Craig Topperf0ddc892016-09-23 04:48:27 +00001989bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1990 if (BuiltinID == X86::BI__builtin_cpu_supports)
1991 return SemaBuiltinCpuSupports(*this, TheCall);
1992
1993 if (BuiltinID == X86::BI__builtin_ms_va_start)
1994 return SemaBuiltinMSVAStart(TheCall);
1995
Craig Toppera7e253e2016-09-23 04:48:31 +00001996 // If the intrinsic has rounding or SAE make sure its valid.
1997 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
1998 return true;
1999
Craig Topperf0ddc892016-09-23 04:48:27 +00002000 // For intrinsics which take an immediate value as part of the instruction,
2001 // range check them here.
2002 int i = 0, l = 0, u = 0;
2003 switch (BuiltinID) {
2004 default:
2005 return false;
Richard Trieucc3949d2016-02-18 22:34:54 +00002006 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00002007 i = 1; l = 0; u = 3;
2008 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002009 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00002010 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2011 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2012 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2013 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002014 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002015 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002016 case X86::BI__builtin_ia32_vpermil2pd:
2017 case X86::BI__builtin_ia32_vpermil2pd256:
2018 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002019 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002020 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002021 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002022 case X86::BI__builtin_ia32_cmpb128_mask:
2023 case X86::BI__builtin_ia32_cmpw128_mask:
2024 case X86::BI__builtin_ia32_cmpd128_mask:
2025 case X86::BI__builtin_ia32_cmpq128_mask:
2026 case X86::BI__builtin_ia32_cmpb256_mask:
2027 case X86::BI__builtin_ia32_cmpw256_mask:
2028 case X86::BI__builtin_ia32_cmpd256_mask:
2029 case X86::BI__builtin_ia32_cmpq256_mask:
2030 case X86::BI__builtin_ia32_cmpb512_mask:
2031 case X86::BI__builtin_ia32_cmpw512_mask:
2032 case X86::BI__builtin_ia32_cmpd512_mask:
2033 case X86::BI__builtin_ia32_cmpq512_mask:
2034 case X86::BI__builtin_ia32_ucmpb128_mask:
2035 case X86::BI__builtin_ia32_ucmpw128_mask:
2036 case X86::BI__builtin_ia32_ucmpd128_mask:
2037 case X86::BI__builtin_ia32_ucmpq128_mask:
2038 case X86::BI__builtin_ia32_ucmpb256_mask:
2039 case X86::BI__builtin_ia32_ucmpw256_mask:
2040 case X86::BI__builtin_ia32_ucmpd256_mask:
2041 case X86::BI__builtin_ia32_ucmpq256_mask:
2042 case X86::BI__builtin_ia32_ucmpb512_mask:
2043 case X86::BI__builtin_ia32_ucmpw512_mask:
2044 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002045 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002046 case X86::BI__builtin_ia32_vpcomub:
2047 case X86::BI__builtin_ia32_vpcomuw:
2048 case X86::BI__builtin_ia32_vpcomud:
2049 case X86::BI__builtin_ia32_vpcomuq:
2050 case X86::BI__builtin_ia32_vpcomb:
2051 case X86::BI__builtin_ia32_vpcomw:
2052 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002053 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00002054 i = 2; l = 0; u = 7;
2055 break;
2056 case X86::BI__builtin_ia32_roundps:
2057 case X86::BI__builtin_ia32_roundpd:
2058 case X86::BI__builtin_ia32_roundps256:
2059 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002060 i = 1; l = 0; u = 15;
2061 break;
2062 case X86::BI__builtin_ia32_roundss:
2063 case X86::BI__builtin_ia32_roundsd:
2064 case X86::BI__builtin_ia32_rangepd128_mask:
2065 case X86::BI__builtin_ia32_rangepd256_mask:
2066 case X86::BI__builtin_ia32_rangepd512_mask:
2067 case X86::BI__builtin_ia32_rangeps128_mask:
2068 case X86::BI__builtin_ia32_rangeps256_mask:
2069 case X86::BI__builtin_ia32_rangeps512_mask:
2070 case X86::BI__builtin_ia32_getmantsd_round_mask:
2071 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002072 i = 2; l = 0; u = 15;
2073 break;
2074 case X86::BI__builtin_ia32_cmpps:
2075 case X86::BI__builtin_ia32_cmpss:
2076 case X86::BI__builtin_ia32_cmppd:
2077 case X86::BI__builtin_ia32_cmpsd:
2078 case X86::BI__builtin_ia32_cmpps256:
2079 case X86::BI__builtin_ia32_cmppd256:
2080 case X86::BI__builtin_ia32_cmpps128_mask:
2081 case X86::BI__builtin_ia32_cmppd128_mask:
2082 case X86::BI__builtin_ia32_cmpps256_mask:
2083 case X86::BI__builtin_ia32_cmppd256_mask:
2084 case X86::BI__builtin_ia32_cmpps512_mask:
2085 case X86::BI__builtin_ia32_cmppd512_mask:
2086 case X86::BI__builtin_ia32_cmpsd_mask:
2087 case X86::BI__builtin_ia32_cmpss_mask:
2088 i = 2; l = 0; u = 31;
2089 break;
2090 case X86::BI__builtin_ia32_xabort:
2091 i = 0; l = -128; u = 255;
2092 break;
2093 case X86::BI__builtin_ia32_pshufw:
2094 case X86::BI__builtin_ia32_aeskeygenassist128:
2095 i = 1; l = -128; u = 255;
2096 break;
2097 case X86::BI__builtin_ia32_vcvtps2ph:
2098 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper39c87102016-05-18 03:18:12 +00002099 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2100 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2101 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2102 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2103 case X86::BI__builtin_ia32_rndscaleps_mask:
2104 case X86::BI__builtin_ia32_rndscalepd_mask:
2105 case X86::BI__builtin_ia32_reducepd128_mask:
2106 case X86::BI__builtin_ia32_reducepd256_mask:
2107 case X86::BI__builtin_ia32_reducepd512_mask:
2108 case X86::BI__builtin_ia32_reduceps128_mask:
2109 case X86::BI__builtin_ia32_reduceps256_mask:
2110 case X86::BI__builtin_ia32_reduceps512_mask:
2111 case X86::BI__builtin_ia32_prold512_mask:
2112 case X86::BI__builtin_ia32_prolq512_mask:
2113 case X86::BI__builtin_ia32_prold128_mask:
2114 case X86::BI__builtin_ia32_prold256_mask:
2115 case X86::BI__builtin_ia32_prolq128_mask:
2116 case X86::BI__builtin_ia32_prolq256_mask:
2117 case X86::BI__builtin_ia32_prord128_mask:
2118 case X86::BI__builtin_ia32_prord256_mask:
2119 case X86::BI__builtin_ia32_prorq128_mask:
2120 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002121 case X86::BI__builtin_ia32_fpclasspd128_mask:
2122 case X86::BI__builtin_ia32_fpclasspd256_mask:
2123 case X86::BI__builtin_ia32_fpclassps128_mask:
2124 case X86::BI__builtin_ia32_fpclassps256_mask:
2125 case X86::BI__builtin_ia32_fpclassps512_mask:
2126 case X86::BI__builtin_ia32_fpclasspd512_mask:
2127 case X86::BI__builtin_ia32_fpclasssd_mask:
2128 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002129 i = 1; l = 0; u = 255;
2130 break;
2131 case X86::BI__builtin_ia32_palignr:
2132 case X86::BI__builtin_ia32_insertps128:
2133 case X86::BI__builtin_ia32_dpps:
2134 case X86::BI__builtin_ia32_dppd:
2135 case X86::BI__builtin_ia32_dpps256:
2136 case X86::BI__builtin_ia32_mpsadbw128:
2137 case X86::BI__builtin_ia32_mpsadbw256:
2138 case X86::BI__builtin_ia32_pcmpistrm128:
2139 case X86::BI__builtin_ia32_pcmpistri128:
2140 case X86::BI__builtin_ia32_pcmpistria128:
2141 case X86::BI__builtin_ia32_pcmpistric128:
2142 case X86::BI__builtin_ia32_pcmpistrio128:
2143 case X86::BI__builtin_ia32_pcmpistris128:
2144 case X86::BI__builtin_ia32_pcmpistriz128:
2145 case X86::BI__builtin_ia32_pclmulqdq128:
2146 case X86::BI__builtin_ia32_vperm2f128_pd256:
2147 case X86::BI__builtin_ia32_vperm2f128_ps256:
2148 case X86::BI__builtin_ia32_vperm2f128_si256:
2149 case X86::BI__builtin_ia32_permti256:
2150 i = 2; l = -128; u = 255;
2151 break;
2152 case X86::BI__builtin_ia32_palignr128:
2153 case X86::BI__builtin_ia32_palignr256:
Craig Topper39c87102016-05-18 03:18:12 +00002154 case X86::BI__builtin_ia32_palignr512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002155 case X86::BI__builtin_ia32_vcomisd:
2156 case X86::BI__builtin_ia32_vcomiss:
2157 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2158 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2159 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2160 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002161 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2162 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2163 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2164 i = 2; l = 0; u = 255;
2165 break;
2166 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2167 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2168 case X86::BI__builtin_ia32_fixupimmps512_mask:
2169 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2170 case X86::BI__builtin_ia32_fixupimmsd_mask:
2171 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2172 case X86::BI__builtin_ia32_fixupimmss_mask:
2173 case X86::BI__builtin_ia32_fixupimmss_maskz:
2174 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2175 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2176 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2177 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2178 case X86::BI__builtin_ia32_fixupimmps128_mask:
2179 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2180 case X86::BI__builtin_ia32_fixupimmps256_mask:
2181 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2182 case X86::BI__builtin_ia32_pternlogd512_mask:
2183 case X86::BI__builtin_ia32_pternlogd512_maskz:
2184 case X86::BI__builtin_ia32_pternlogq512_mask:
2185 case X86::BI__builtin_ia32_pternlogq512_maskz:
2186 case X86::BI__builtin_ia32_pternlogd128_mask:
2187 case X86::BI__builtin_ia32_pternlogd128_maskz:
2188 case X86::BI__builtin_ia32_pternlogd256_mask:
2189 case X86::BI__builtin_ia32_pternlogd256_maskz:
2190 case X86::BI__builtin_ia32_pternlogq128_mask:
2191 case X86::BI__builtin_ia32_pternlogq128_maskz:
2192 case X86::BI__builtin_ia32_pternlogq256_mask:
2193 case X86::BI__builtin_ia32_pternlogq256_maskz:
2194 i = 3; l = 0; u = 255;
2195 break;
2196 case X86::BI__builtin_ia32_pcmpestrm128:
2197 case X86::BI__builtin_ia32_pcmpestri128:
2198 case X86::BI__builtin_ia32_pcmpestria128:
2199 case X86::BI__builtin_ia32_pcmpestric128:
2200 case X86::BI__builtin_ia32_pcmpestrio128:
2201 case X86::BI__builtin_ia32_pcmpestris128:
2202 case X86::BI__builtin_ia32_pcmpestriz128:
2203 i = 4; l = -128; u = 255;
2204 break;
2205 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2206 case X86::BI__builtin_ia32_rndscaless_round_mask:
2207 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002208 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002209 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002210 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002211}
2212
Richard Smith55ce3522012-06-25 20:30:08 +00002213/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2214/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2215/// Returns true when the format fits the function and the FormatStringInfo has
2216/// been populated.
2217bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2218 FormatStringInfo *FSI) {
2219 FSI->HasVAListArg = Format->getFirstArg() == 0;
2220 FSI->FormatIdx = Format->getFormatIdx() - 1;
2221 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002222
Richard Smith55ce3522012-06-25 20:30:08 +00002223 // The way the format attribute works in GCC, the implicit this argument
2224 // of member functions is counted. However, it doesn't appear in our own
2225 // lists, so decrement format_idx in that case.
2226 if (IsCXXMember) {
2227 if(FSI->FormatIdx == 0)
2228 return false;
2229 --FSI->FormatIdx;
2230 if (FSI->FirstDataArg != 0)
2231 --FSI->FirstDataArg;
2232 }
2233 return true;
2234}
Mike Stump11289f42009-09-09 15:08:12 +00002235
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002236/// Checks if a the given expression evaluates to null.
2237///
2238/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002239static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002240 // If the expression has non-null type, it doesn't evaluate to null.
2241 if (auto nullability
2242 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2243 if (*nullability == NullabilityKind::NonNull)
2244 return false;
2245 }
2246
Ted Kremeneka146db32014-01-17 06:24:47 +00002247 // As a special case, transparent unions initialized with zero are
2248 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002249 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002250 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2251 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002252 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002253 if (const InitListExpr *ILE =
2254 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002255 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002256 }
2257
2258 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002259 return (!Expr->isValueDependent() &&
2260 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2261 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002262}
2263
2264static void CheckNonNullArgument(Sema &S,
2265 const Expr *ArgExpr,
2266 SourceLocation CallSiteLoc) {
2267 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002268 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2269 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002270}
2271
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002272bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2273 FormatStringInfo FSI;
2274 if ((GetFormatStringType(Format) == FST_NSString) &&
2275 getFormatStringInfo(Format, false, &FSI)) {
2276 Idx = FSI.FormatIdx;
2277 return true;
2278 }
2279 return false;
2280}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002281/// \brief Diagnose use of %s directive in an NSString which is being passed
2282/// as formatting string to formatting method.
2283static void
2284DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2285 const NamedDecl *FDecl,
2286 Expr **Args,
2287 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002288 unsigned Idx = 0;
2289 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002290 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2291 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002292 Idx = 2;
2293 Format = true;
2294 }
2295 else
2296 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2297 if (S.GetFormatNSStringIdx(I, Idx)) {
2298 Format = true;
2299 break;
2300 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002301 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002302 if (!Format || NumArgs <= Idx)
2303 return;
2304 const Expr *FormatExpr = Args[Idx];
2305 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2306 FormatExpr = CSCE->getSubExpr();
2307 const StringLiteral *FormatString;
2308 if (const ObjCStringLiteral *OSL =
2309 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2310 FormatString = OSL->getString();
2311 else
2312 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2313 if (!FormatString)
2314 return;
2315 if (S.FormatStringHasSArg(FormatString)) {
2316 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2317 << "%s" << 1 << 1;
2318 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2319 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002320 }
2321}
2322
Douglas Gregorb4866e82015-06-19 18:13:19 +00002323/// Determine whether the given type has a non-null nullability annotation.
2324static bool isNonNullType(ASTContext &ctx, QualType type) {
2325 if (auto nullability = type->getNullability(ctx))
2326 return *nullability == NullabilityKind::NonNull;
2327
2328 return false;
2329}
2330
Ted Kremenek2bc73332014-01-17 06:24:43 +00002331static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002332 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002333 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002334 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002335 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002336 assert((FDecl || Proto) && "Need a function declaration or prototype");
2337
Ted Kremenek9aedc152014-01-17 06:24:56 +00002338 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002339 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002340 if (FDecl) {
2341 // Handle the nonnull attribute on the function/method declaration itself.
2342 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2343 if (!NonNull->args_size()) {
2344 // Easy case: all pointer arguments are nonnull.
2345 for (const auto *Arg : Args)
2346 if (S.isValidPointerAttrType(Arg->getType()))
2347 CheckNonNullArgument(S, Arg, CallSiteLoc);
2348 return;
2349 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002350
Douglas Gregorb4866e82015-06-19 18:13:19 +00002351 for (unsigned Val : NonNull->args()) {
2352 if (Val >= Args.size())
2353 continue;
2354 if (NonNullArgs.empty())
2355 NonNullArgs.resize(Args.size());
2356 NonNullArgs.set(Val);
2357 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002358 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002359 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002360
Douglas Gregorb4866e82015-06-19 18:13:19 +00002361 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2362 // Handle the nonnull attribute on the parameters of the
2363 // function/method.
2364 ArrayRef<ParmVarDecl*> parms;
2365 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2366 parms = FD->parameters();
2367 else
2368 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2369
2370 unsigned ParamIndex = 0;
2371 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2372 I != E; ++I, ++ParamIndex) {
2373 const ParmVarDecl *PVD = *I;
2374 if (PVD->hasAttr<NonNullAttr>() ||
2375 isNonNullType(S.Context, PVD->getType())) {
2376 if (NonNullArgs.empty())
2377 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002378
Douglas Gregorb4866e82015-06-19 18:13:19 +00002379 NonNullArgs.set(ParamIndex);
2380 }
2381 }
2382 } else {
2383 // If we have a non-function, non-method declaration but no
2384 // function prototype, try to dig out the function prototype.
2385 if (!Proto) {
2386 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2387 QualType type = VD->getType().getNonReferenceType();
2388 if (auto pointerType = type->getAs<PointerType>())
2389 type = pointerType->getPointeeType();
2390 else if (auto blockType = type->getAs<BlockPointerType>())
2391 type = blockType->getPointeeType();
2392 // FIXME: data member pointers?
2393
2394 // Dig out the function prototype, if there is one.
2395 Proto = type->getAs<FunctionProtoType>();
2396 }
2397 }
2398
2399 // Fill in non-null argument information from the nullability
2400 // information on the parameter types (if we have them).
2401 if (Proto) {
2402 unsigned Index = 0;
2403 for (auto paramType : Proto->getParamTypes()) {
2404 if (isNonNullType(S.Context, paramType)) {
2405 if (NonNullArgs.empty())
2406 NonNullArgs.resize(Args.size());
2407
2408 NonNullArgs.set(Index);
2409 }
2410
2411 ++Index;
2412 }
2413 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002414 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002415
Douglas Gregorb4866e82015-06-19 18:13:19 +00002416 // Check for non-null arguments.
2417 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2418 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002419 if (NonNullArgs[ArgIndex])
2420 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002421 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002422}
2423
Richard Smith55ce3522012-06-25 20:30:08 +00002424/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00002425/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2426/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002427void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00002428 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2429 bool IsMemberFunction, SourceLocation Loc,
2430 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002431 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002432 if (CurContext->isDependentContext())
2433 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002434
Ted Kremenekb8176da2010-09-09 04:33:05 +00002435 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002436 llvm::SmallBitVector CheckedVarArgs;
2437 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002438 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002439 // Only create vector if there are format attributes.
2440 CheckedVarArgs.resize(Args.size());
2441
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002442 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002443 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002444 }
Richard Smithd7293d72013-08-05 18:49:43 +00002445 }
Richard Smith55ce3522012-06-25 20:30:08 +00002446
2447 // Refuse POD arguments that weren't caught by the format string
2448 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00002449 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2450 if (CallType != VariadicDoesNotApply &&
2451 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
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 }
George Burgess IVce6284b2017-01-28 02:19:40 +00002477
2478 if (FD)
2479 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00002480}
2481
2482/// CheckConstructorCall - Check a constructor call for correctness and safety
2483/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002484void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2485 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002486 const FunctionProtoType *Proto,
2487 SourceLocation Loc) {
2488 VariadicCallType CallType =
2489 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00002490 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2491 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002492}
2493
2494/// CheckFunctionCall - Check a direct function call for various correctness
2495/// and safety properties not strictly enforced by the C type system.
2496bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2497 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002498 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2499 isa<CXXMethodDecl>(FDecl);
2500 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2501 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002502 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2503 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002504 Expr** Args = TheCall->getArgs();
2505 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00002506
2507 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00002508 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002509 // If this is a call to a member operator, hide the first argument
2510 // from checkCall.
2511 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00002512 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00002513 ++Args;
2514 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00002515 } else if (IsMemberFunction)
2516 ImplicitThis =
2517 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2518
2519 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002520 IsMemberFunction, TheCall->getRParenLoc(),
2521 TheCall->getCallee()->getSourceRange(), CallType);
2522
2523 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2524 // None of the checks below are needed for functions that don't have
2525 // simple names (e.g., C++ conversion functions).
2526 if (!FnInfo)
2527 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002528
Richard Trieua7f30b12016-12-06 01:42:28 +00002529 CheckAbsoluteValueFunction(TheCall, FDecl);
2530 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00002531
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002532 if (getLangOpts().ObjC1)
2533 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002534
Anna Zaks22122702012-01-17 00:37:07 +00002535 unsigned CMId = FDecl->getMemoryFunctionKind();
2536 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002537 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002538
Anna Zaks201d4892012-01-13 21:52:01 +00002539 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002540 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002541 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002542 else if (CMId == Builtin::BIstrncat)
2543 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002544 else
Anna Zaks22122702012-01-17 00:37:07 +00002545 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002546
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002547 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002548}
2549
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002550bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002551 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002552 VariadicCallType CallType =
2553 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002554
George Burgess IVce6284b2017-01-28 02:19:40 +00002555 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2556 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002557 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002558
2559 return false;
2560}
2561
Richard Trieu664c4c62013-06-20 21:03:13 +00002562bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2563 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002564 QualType Ty;
2565 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002566 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002567 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002568 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002569 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002570 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002571
Douglas Gregorb4866e82015-06-19 18:13:19 +00002572 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2573 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002574 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002575
Richard Trieu664c4c62013-06-20 21:03:13 +00002576 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002577 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002578 CallType = VariadicDoesNotApply;
2579 } else if (Ty->isBlockPointerType()) {
2580 CallType = VariadicBlock;
2581 } else { // Ty->isFunctionPointerType()
2582 CallType = VariadicFunction;
2583 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002584
George Burgess IVce6284b2017-01-28 02:19:40 +00002585 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002586 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2587 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002588 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002589
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002590 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002591}
2592
Richard Trieu41bc0992013-06-22 00:20:41 +00002593/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2594/// such as function pointers returned from functions.
2595bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002596 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002597 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00002598 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002599 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002600 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002601 TheCall->getCallee()->getSourceRange(), CallType);
2602
2603 return false;
2604}
2605
Tim Northovere94a34c2014-03-11 10:49:14 +00002606static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002607 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002608 return false;
2609
JF Bastiendda2cb12016-04-18 18:01:49 +00002610 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002611 switch (Op) {
2612 case AtomicExpr::AO__c11_atomic_init:
2613 llvm_unreachable("There is no ordering argument for an init");
2614
2615 case AtomicExpr::AO__c11_atomic_load:
2616 case AtomicExpr::AO__atomic_load_n:
2617 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002618 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2619 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002620
2621 case AtomicExpr::AO__c11_atomic_store:
2622 case AtomicExpr::AO__atomic_store:
2623 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002624 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2625 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2626 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002627
2628 default:
2629 return true;
2630 }
2631}
2632
Richard Smithfeea8832012-04-12 05:08:17 +00002633ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2634 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002635 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2636 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002637
Richard Smithfeea8832012-04-12 05:08:17 +00002638 // All these operations take one of the following forms:
2639 enum {
2640 // C __c11_atomic_init(A *, C)
2641 Init,
2642 // C __c11_atomic_load(A *, int)
2643 Load,
2644 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002645 LoadCopy,
2646 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002647 Copy,
2648 // C __c11_atomic_add(A *, M, int)
2649 Arithmetic,
2650 // C __atomic_exchange_n(A *, CP, int)
2651 Xchg,
2652 // void __atomic_exchange(A *, C *, CP, int)
2653 GNUXchg,
2654 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2655 C11CmpXchg,
2656 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2657 GNUCmpXchg
2658 } Form = Init;
Eric Fiselier8d662442016-03-30 23:39:56 +00002659 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2660 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002661 // where:
2662 // C is an appropriate type,
2663 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2664 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2665 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2666 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002667
Gabor Horvath98bd0982015-03-16 09:59:54 +00002668 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2669 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2670 AtomicExpr::AO__atomic_load,
2671 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00002672 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2673 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2674 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2675 Op == AtomicExpr::AO__atomic_store_n ||
2676 Op == AtomicExpr::AO__atomic_exchange_n ||
2677 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2678 bool IsAddSub = false;
2679
2680 switch (Op) {
2681 case AtomicExpr::AO__c11_atomic_init:
2682 Form = Init;
2683 break;
2684
2685 case AtomicExpr::AO__c11_atomic_load:
2686 case AtomicExpr::AO__atomic_load_n:
2687 Form = Load;
2688 break;
2689
Richard Smithfeea8832012-04-12 05:08:17 +00002690 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002691 Form = LoadCopy;
2692 break;
2693
2694 case AtomicExpr::AO__c11_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002695 case AtomicExpr::AO__atomic_store:
2696 case AtomicExpr::AO__atomic_store_n:
2697 Form = Copy;
2698 break;
2699
2700 case AtomicExpr::AO__c11_atomic_fetch_add:
2701 case AtomicExpr::AO__c11_atomic_fetch_sub:
2702 case AtomicExpr::AO__atomic_fetch_add:
2703 case AtomicExpr::AO__atomic_fetch_sub:
2704 case AtomicExpr::AO__atomic_add_fetch:
2705 case AtomicExpr::AO__atomic_sub_fetch:
2706 IsAddSub = true;
2707 // Fall through.
2708 case AtomicExpr::AO__c11_atomic_fetch_and:
2709 case AtomicExpr::AO__c11_atomic_fetch_or:
2710 case AtomicExpr::AO__c11_atomic_fetch_xor:
2711 case AtomicExpr::AO__atomic_fetch_and:
2712 case AtomicExpr::AO__atomic_fetch_or:
2713 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00002714 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00002715 case AtomicExpr::AO__atomic_and_fetch:
2716 case AtomicExpr::AO__atomic_or_fetch:
2717 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00002718 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00002719 Form = Arithmetic;
2720 break;
2721
2722 case AtomicExpr::AO__c11_atomic_exchange:
2723 case AtomicExpr::AO__atomic_exchange_n:
2724 Form = Xchg;
2725 break;
2726
2727 case AtomicExpr::AO__atomic_exchange:
2728 Form = GNUXchg;
2729 break;
2730
2731 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2732 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2733 Form = C11CmpXchg;
2734 break;
2735
2736 case AtomicExpr::AO__atomic_compare_exchange:
2737 case AtomicExpr::AO__atomic_compare_exchange_n:
2738 Form = GNUCmpXchg;
2739 break;
2740 }
2741
2742 // Check we have the right number of arguments.
2743 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002744 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002745 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002746 << TheCall->getCallee()->getSourceRange();
2747 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00002748 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2749 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002750 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002751 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002752 << TheCall->getCallee()->getSourceRange();
2753 return ExprError();
2754 }
2755
Richard Smithfeea8832012-04-12 05:08:17 +00002756 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002757 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00002758 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2759 if (ConvertedPtr.isInvalid())
2760 return ExprError();
2761
2762 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002763 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2764 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00002765 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002766 << Ptr->getType() << Ptr->getSourceRange();
2767 return ExprError();
2768 }
2769
Richard Smithfeea8832012-04-12 05:08:17 +00002770 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2771 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2772 QualType ValType = AtomTy; // 'C'
2773 if (IsC11) {
2774 if (!AtomTy->isAtomicType()) {
2775 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2776 << Ptr->getType() << Ptr->getSourceRange();
2777 return ExprError();
2778 }
Richard Smithe00921a2012-09-15 06:09:58 +00002779 if (AtomTy.isConstQualified()) {
2780 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2781 << Ptr->getType() << Ptr->getSourceRange();
2782 return ExprError();
2783 }
Richard Smithfeea8832012-04-12 05:08:17 +00002784 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00002785 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002786 if (ValType.isConstQualified()) {
2787 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2788 << Ptr->getType() << Ptr->getSourceRange();
2789 return ExprError();
2790 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002791 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002792
Richard Smithfeea8832012-04-12 05:08:17 +00002793 // For an arithmetic operation, the implied arithmetic must be well-formed.
2794 if (Form == Arithmetic) {
2795 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2796 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2797 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2798 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2799 return ExprError();
2800 }
2801 if (!IsAddSub && !ValType->isIntegerType()) {
2802 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2803 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2804 return ExprError();
2805 }
David Majnemere85cff82015-01-28 05:48:06 +00002806 if (IsC11 && ValType->isPointerType() &&
2807 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2808 diag::err_incomplete_type)) {
2809 return ExprError();
2810 }
Richard Smithfeea8832012-04-12 05:08:17 +00002811 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2812 // For __atomic_*_n operations, the value type must be a scalar integral or
2813 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002814 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00002815 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2816 return ExprError();
2817 }
2818
Eli Friedmanaa769812013-09-11 03:49:34 +00002819 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2820 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00002821 // For GNU atomics, require a trivially-copyable type. This is not part of
2822 // the GNU atomics specification, but we enforce it for sanity.
2823 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002824 << Ptr->getType() << Ptr->getSourceRange();
2825 return ExprError();
2826 }
2827
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002828 switch (ValType.getObjCLifetime()) {
2829 case Qualifiers::OCL_None:
2830 case Qualifiers::OCL_ExplicitNone:
2831 // okay
2832 break;
2833
2834 case Qualifiers::OCL_Weak:
2835 case Qualifiers::OCL_Strong:
2836 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002837 // FIXME: Can this happen? By this point, ValType should be known
2838 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002839 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2840 << ValType << Ptr->getSourceRange();
2841 return ExprError();
2842 }
2843
David Majnemerc6eb6502015-06-03 00:26:35 +00002844 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2845 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00002846 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00002847 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00002848 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002849 QualType ResultType = ValType;
Eric Fiselier8d662442016-03-30 23:39:56 +00002850 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002851 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002852 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002853 ResultType = Context.BoolTy;
2854
Richard Smithfeea8832012-04-12 05:08:17 +00002855 // The type of a parameter passed 'by value'. In the GNU atomics, such
2856 // arguments are actually passed as pointers.
2857 QualType ByValType = ValType; // 'CP'
2858 if (!IsC11 && !IsN)
2859 ByValType = Ptr->getType();
2860
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002861 // The first argument --- the pointer --- has a fixed type; we
2862 // deduce the types of the rest of the arguments accordingly. Walk
2863 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002864 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002865 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002866 if (i < NumVals[Form] + 1) {
2867 switch (i) {
2868 case 1:
2869 // The second argument is the non-atomic operand. For arithmetic, this
2870 // is always passed by value, and for a compare_exchange it is always
2871 // passed by address. For the rest, GNU uses by-address and C11 uses
2872 // by-value.
2873 assert(Form != Load);
2874 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2875 Ty = ValType;
2876 else if (Form == Copy || Form == Xchg)
2877 Ty = ByValType;
2878 else if (Form == Arithmetic)
2879 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002880 else {
2881 Expr *ValArg = TheCall->getArg(i);
Alex Lorenz67522152016-11-23 16:57:03 +00002882 // Treat this argument as _Nonnull as we want to show a warning if
2883 // NULL is passed into it.
2884 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002885 unsigned AS = 0;
2886 // Keep address space of non-atomic pointer type.
2887 if (const PointerType *PtrTy =
2888 ValArg->getType()->getAs<PointerType>()) {
2889 AS = PtrTy->getPointeeType().getAddressSpace();
2890 }
2891 Ty = Context.getPointerType(
2892 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2893 }
Richard Smithfeea8832012-04-12 05:08:17 +00002894 break;
2895 case 2:
2896 // The third argument to compare_exchange / GNU exchange is a
2897 // (pointer to a) desired value.
2898 Ty = ByValType;
2899 break;
2900 case 3:
2901 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2902 Ty = Context.BoolTy;
2903 break;
2904 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002905 } else {
2906 // The order(s) are always converted to int.
2907 Ty = Context.IntTy;
2908 }
Richard Smithfeea8832012-04-12 05:08:17 +00002909
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002910 InitializedEntity Entity =
2911 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00002912 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002913 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2914 if (Arg.isInvalid())
2915 return true;
2916 TheCall->setArg(i, Arg.get());
2917 }
2918
Richard Smithfeea8832012-04-12 05:08:17 +00002919 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002920 SmallVector<Expr*, 5> SubExprs;
2921 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00002922 switch (Form) {
2923 case Init:
2924 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00002925 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002926 break;
2927 case Load:
2928 SubExprs.push_back(TheCall->getArg(1)); // Order
2929 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00002930 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00002931 case Copy:
2932 case Arithmetic:
2933 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002934 SubExprs.push_back(TheCall->getArg(2)); // Order
2935 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002936 break;
2937 case GNUXchg:
2938 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2939 SubExprs.push_back(TheCall->getArg(3)); // Order
2940 SubExprs.push_back(TheCall->getArg(1)); // Val1
2941 SubExprs.push_back(TheCall->getArg(2)); // Val2
2942 break;
2943 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002944 SubExprs.push_back(TheCall->getArg(3)); // Order
2945 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002946 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00002947 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00002948 break;
2949 case GNUCmpXchg:
2950 SubExprs.push_back(TheCall->getArg(4)); // Order
2951 SubExprs.push_back(TheCall->getArg(1)); // Val1
2952 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2953 SubExprs.push_back(TheCall->getArg(2)); // Val2
2954 SubExprs.push_back(TheCall->getArg(3)); // Weak
2955 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002956 }
Tim Northovere94a34c2014-03-11 10:49:14 +00002957
2958 if (SubExprs.size() >= 2 && Form != Init) {
2959 llvm::APSInt Result(32);
2960 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2961 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00002962 Diag(SubExprs[1]->getLocStart(),
2963 diag::warn_atomic_op_has_invalid_memory_order)
2964 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00002965 }
2966
Fariborz Jahanian615de762013-05-28 17:37:39 +00002967 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2968 SubExprs, ResultType, Op,
2969 TheCall->getRParenLoc());
2970
2971 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2972 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2973 Context.AtomicUsesUnsupportedLibcall(AE))
2974 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2975 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002976
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002977 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002978}
2979
John McCall29ad95b2011-08-27 01:09:30 +00002980/// checkBuiltinArgument - Given a call to a builtin function, perform
2981/// normal type-checking on the given argument, updating the call in
2982/// place. This is useful when a builtin function requires custom
2983/// type-checking for some of its arguments but not necessarily all of
2984/// them.
2985///
2986/// Returns true on error.
2987static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2988 FunctionDecl *Fn = E->getDirectCallee();
2989 assert(Fn && "builtin call without direct callee!");
2990
2991 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2992 InitializedEntity Entity =
2993 InitializedEntity::InitializeParameter(S.Context, Param);
2994
2995 ExprResult Arg = E->getArg(0);
2996 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2997 if (Arg.isInvalid())
2998 return true;
2999
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003000 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003001 return false;
3002}
3003
Chris Lattnerdc046542009-05-08 06:58:22 +00003004/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3005/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3006/// type of its first argument. The main ActOnCallExpr routines have already
3007/// promoted the types of arguments because all of these calls are prototyped as
3008/// void(...).
3009///
3010/// This function goes through and does final semantic checking for these
3011/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003012ExprResult
3013Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003014 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003015 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3016 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3017
3018 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003019 if (TheCall->getNumArgs() < 1) {
3020 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3021 << 0 << 1 << TheCall->getNumArgs()
3022 << TheCall->getCallee()->getSourceRange();
3023 return ExprError();
3024 }
Mike Stump11289f42009-09-09 15:08:12 +00003025
Chris Lattnerdc046542009-05-08 06:58:22 +00003026 // Inspect the first argument of the atomic builtin. This should always be
3027 // a pointer type, whose element is an integral scalar or pointer type.
3028 // Because it is a pointer type, we don't have to worry about any implicit
3029 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003030 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003031 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003032 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3033 if (FirstArgResult.isInvalid())
3034 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003035 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003036 TheCall->setArg(0, FirstArg);
3037
John McCall31168b02011-06-15 23:02:42 +00003038 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3039 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003040 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3041 << FirstArg->getType() << FirstArg->getSourceRange();
3042 return ExprError();
3043 }
Mike Stump11289f42009-09-09 15:08:12 +00003044
John McCall31168b02011-06-15 23:02:42 +00003045 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003046 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003047 !ValType->isBlockPointerType()) {
3048 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3049 << FirstArg->getType() << FirstArg->getSourceRange();
3050 return ExprError();
3051 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003052
John McCall31168b02011-06-15 23:02:42 +00003053 switch (ValType.getObjCLifetime()) {
3054 case Qualifiers::OCL_None:
3055 case Qualifiers::OCL_ExplicitNone:
3056 // okay
3057 break;
3058
3059 case Qualifiers::OCL_Weak:
3060 case Qualifiers::OCL_Strong:
3061 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003062 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003063 << ValType << FirstArg->getSourceRange();
3064 return ExprError();
3065 }
3066
John McCallb50451a2011-10-05 07:41:44 +00003067 // Strip any qualifiers off ValType.
3068 ValType = ValType.getUnqualifiedType();
3069
Chandler Carruth3973af72010-07-18 20:54:12 +00003070 // The majority of builtins return a value, but a few have special return
3071 // types, so allow them to override appropriately below.
3072 QualType ResultType = ValType;
3073
Chris Lattnerdc046542009-05-08 06:58:22 +00003074 // We need to figure out which concrete builtin this maps onto. For example,
3075 // __sync_fetch_and_add with a 2 byte object turns into
3076 // __sync_fetch_and_add_2.
3077#define BUILTIN_ROW(x) \
3078 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3079 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003080
Chris Lattnerdc046542009-05-08 06:58:22 +00003081 static const unsigned BuiltinIndices[][5] = {
3082 BUILTIN_ROW(__sync_fetch_and_add),
3083 BUILTIN_ROW(__sync_fetch_and_sub),
3084 BUILTIN_ROW(__sync_fetch_and_or),
3085 BUILTIN_ROW(__sync_fetch_and_and),
3086 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003087 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003088
Chris Lattnerdc046542009-05-08 06:58:22 +00003089 BUILTIN_ROW(__sync_add_and_fetch),
3090 BUILTIN_ROW(__sync_sub_and_fetch),
3091 BUILTIN_ROW(__sync_and_and_fetch),
3092 BUILTIN_ROW(__sync_or_and_fetch),
3093 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003094 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003095
Chris Lattnerdc046542009-05-08 06:58:22 +00003096 BUILTIN_ROW(__sync_val_compare_and_swap),
3097 BUILTIN_ROW(__sync_bool_compare_and_swap),
3098 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003099 BUILTIN_ROW(__sync_lock_release),
3100 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003101 };
Mike Stump11289f42009-09-09 15:08:12 +00003102#undef BUILTIN_ROW
3103
Chris Lattnerdc046542009-05-08 06:58:22 +00003104 // Determine the index of the size.
3105 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003106 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003107 case 1: SizeIndex = 0; break;
3108 case 2: SizeIndex = 1; break;
3109 case 4: SizeIndex = 2; break;
3110 case 8: SizeIndex = 3; break;
3111 case 16: SizeIndex = 4; break;
3112 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003113 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3114 << FirstArg->getType() << FirstArg->getSourceRange();
3115 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003116 }
Mike Stump11289f42009-09-09 15:08:12 +00003117
Chris Lattnerdc046542009-05-08 06:58:22 +00003118 // Each of these builtins has one pointer argument, followed by some number of
3119 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3120 // that we ignore. Find out which row of BuiltinIndices to read from as well
3121 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003122 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003123 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003124 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003125 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003126 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003127 case Builtin::BI__sync_fetch_and_add:
3128 case Builtin::BI__sync_fetch_and_add_1:
3129 case Builtin::BI__sync_fetch_and_add_2:
3130 case Builtin::BI__sync_fetch_and_add_4:
3131 case Builtin::BI__sync_fetch_and_add_8:
3132 case Builtin::BI__sync_fetch_and_add_16:
3133 BuiltinIndex = 0;
3134 break;
3135
3136 case Builtin::BI__sync_fetch_and_sub:
3137 case Builtin::BI__sync_fetch_and_sub_1:
3138 case Builtin::BI__sync_fetch_and_sub_2:
3139 case Builtin::BI__sync_fetch_and_sub_4:
3140 case Builtin::BI__sync_fetch_and_sub_8:
3141 case Builtin::BI__sync_fetch_and_sub_16:
3142 BuiltinIndex = 1;
3143 break;
3144
3145 case Builtin::BI__sync_fetch_and_or:
3146 case Builtin::BI__sync_fetch_and_or_1:
3147 case Builtin::BI__sync_fetch_and_or_2:
3148 case Builtin::BI__sync_fetch_and_or_4:
3149 case Builtin::BI__sync_fetch_and_or_8:
3150 case Builtin::BI__sync_fetch_and_or_16:
3151 BuiltinIndex = 2;
3152 break;
3153
3154 case Builtin::BI__sync_fetch_and_and:
3155 case Builtin::BI__sync_fetch_and_and_1:
3156 case Builtin::BI__sync_fetch_and_and_2:
3157 case Builtin::BI__sync_fetch_and_and_4:
3158 case Builtin::BI__sync_fetch_and_and_8:
3159 case Builtin::BI__sync_fetch_and_and_16:
3160 BuiltinIndex = 3;
3161 break;
Mike Stump11289f42009-09-09 15:08:12 +00003162
Douglas Gregor73722482011-11-28 16:30:08 +00003163 case Builtin::BI__sync_fetch_and_xor:
3164 case Builtin::BI__sync_fetch_and_xor_1:
3165 case Builtin::BI__sync_fetch_and_xor_2:
3166 case Builtin::BI__sync_fetch_and_xor_4:
3167 case Builtin::BI__sync_fetch_and_xor_8:
3168 case Builtin::BI__sync_fetch_and_xor_16:
3169 BuiltinIndex = 4;
3170 break;
3171
Hal Finkeld2208b52014-10-02 20:53:50 +00003172 case Builtin::BI__sync_fetch_and_nand:
3173 case Builtin::BI__sync_fetch_and_nand_1:
3174 case Builtin::BI__sync_fetch_and_nand_2:
3175 case Builtin::BI__sync_fetch_and_nand_4:
3176 case Builtin::BI__sync_fetch_and_nand_8:
3177 case Builtin::BI__sync_fetch_and_nand_16:
3178 BuiltinIndex = 5;
3179 WarnAboutSemanticsChange = true;
3180 break;
3181
Douglas Gregor73722482011-11-28 16:30:08 +00003182 case Builtin::BI__sync_add_and_fetch:
3183 case Builtin::BI__sync_add_and_fetch_1:
3184 case Builtin::BI__sync_add_and_fetch_2:
3185 case Builtin::BI__sync_add_and_fetch_4:
3186 case Builtin::BI__sync_add_and_fetch_8:
3187 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003188 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003189 break;
3190
3191 case Builtin::BI__sync_sub_and_fetch:
3192 case Builtin::BI__sync_sub_and_fetch_1:
3193 case Builtin::BI__sync_sub_and_fetch_2:
3194 case Builtin::BI__sync_sub_and_fetch_4:
3195 case Builtin::BI__sync_sub_and_fetch_8:
3196 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003197 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003198 break;
3199
3200 case Builtin::BI__sync_and_and_fetch:
3201 case Builtin::BI__sync_and_and_fetch_1:
3202 case Builtin::BI__sync_and_and_fetch_2:
3203 case Builtin::BI__sync_and_and_fetch_4:
3204 case Builtin::BI__sync_and_and_fetch_8:
3205 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003206 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003207 break;
3208
3209 case Builtin::BI__sync_or_and_fetch:
3210 case Builtin::BI__sync_or_and_fetch_1:
3211 case Builtin::BI__sync_or_and_fetch_2:
3212 case Builtin::BI__sync_or_and_fetch_4:
3213 case Builtin::BI__sync_or_and_fetch_8:
3214 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003215 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003216 break;
3217
3218 case Builtin::BI__sync_xor_and_fetch:
3219 case Builtin::BI__sync_xor_and_fetch_1:
3220 case Builtin::BI__sync_xor_and_fetch_2:
3221 case Builtin::BI__sync_xor_and_fetch_4:
3222 case Builtin::BI__sync_xor_and_fetch_8:
3223 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003224 BuiltinIndex = 10;
3225 break;
3226
3227 case Builtin::BI__sync_nand_and_fetch:
3228 case Builtin::BI__sync_nand_and_fetch_1:
3229 case Builtin::BI__sync_nand_and_fetch_2:
3230 case Builtin::BI__sync_nand_and_fetch_4:
3231 case Builtin::BI__sync_nand_and_fetch_8:
3232 case Builtin::BI__sync_nand_and_fetch_16:
3233 BuiltinIndex = 11;
3234 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003235 break;
Mike Stump11289f42009-09-09 15:08:12 +00003236
Chris Lattnerdc046542009-05-08 06:58:22 +00003237 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003238 case Builtin::BI__sync_val_compare_and_swap_1:
3239 case Builtin::BI__sync_val_compare_and_swap_2:
3240 case Builtin::BI__sync_val_compare_and_swap_4:
3241 case Builtin::BI__sync_val_compare_and_swap_8:
3242 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003243 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003244 NumFixed = 2;
3245 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003246
Chris Lattnerdc046542009-05-08 06:58:22 +00003247 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003248 case Builtin::BI__sync_bool_compare_and_swap_1:
3249 case Builtin::BI__sync_bool_compare_and_swap_2:
3250 case Builtin::BI__sync_bool_compare_and_swap_4:
3251 case Builtin::BI__sync_bool_compare_and_swap_8:
3252 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003253 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003254 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003255 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003256 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003257
3258 case Builtin::BI__sync_lock_test_and_set:
3259 case Builtin::BI__sync_lock_test_and_set_1:
3260 case Builtin::BI__sync_lock_test_and_set_2:
3261 case Builtin::BI__sync_lock_test_and_set_4:
3262 case Builtin::BI__sync_lock_test_and_set_8:
3263 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003264 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003265 break;
3266
Chris Lattnerdc046542009-05-08 06:58:22 +00003267 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003268 case Builtin::BI__sync_lock_release_1:
3269 case Builtin::BI__sync_lock_release_2:
3270 case Builtin::BI__sync_lock_release_4:
3271 case Builtin::BI__sync_lock_release_8:
3272 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003273 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003274 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003275 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003276 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003277
3278 case Builtin::BI__sync_swap:
3279 case Builtin::BI__sync_swap_1:
3280 case Builtin::BI__sync_swap_2:
3281 case Builtin::BI__sync_swap_4:
3282 case Builtin::BI__sync_swap_8:
3283 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003284 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003285 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003286 }
Mike Stump11289f42009-09-09 15:08:12 +00003287
Chris Lattnerdc046542009-05-08 06:58:22 +00003288 // Now that we know how many fixed arguments we expect, first check that we
3289 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003290 if (TheCall->getNumArgs() < 1+NumFixed) {
3291 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3292 << 0 << 1+NumFixed << TheCall->getNumArgs()
3293 << TheCall->getCallee()->getSourceRange();
3294 return ExprError();
3295 }
Mike Stump11289f42009-09-09 15:08:12 +00003296
Hal Finkeld2208b52014-10-02 20:53:50 +00003297 if (WarnAboutSemanticsChange) {
3298 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3299 << TheCall->getCallee()->getSourceRange();
3300 }
3301
Chris Lattner5b9241b2009-05-08 15:36:58 +00003302 // Get the decl for the concrete builtin from this, we can tell what the
3303 // concrete integer type we should convert to is.
3304 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003305 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003306 FunctionDecl *NewBuiltinDecl;
3307 if (NewBuiltinID == BuiltinID)
3308 NewBuiltinDecl = FDecl;
3309 else {
3310 // Perform builtin lookup to avoid redeclaring it.
3311 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3312 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3313 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3314 assert(Res.getFoundDecl());
3315 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003316 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003317 return ExprError();
3318 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003319
John McCallcf142162010-08-07 06:22:56 +00003320 // The first argument --- the pointer --- has a fixed type; we
3321 // deduce the types of the rest of the arguments accordingly. Walk
3322 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003323 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003324 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003325
Chris Lattnerdc046542009-05-08 06:58:22 +00003326 // GCC does an implicit conversion to the pointer or integer ValType. This
3327 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003328 // Initialize the argument.
3329 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3330 ValType, /*consume*/ false);
3331 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003332 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003333 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003334
Chris Lattnerdc046542009-05-08 06:58:22 +00003335 // Okay, we have something that *can* be converted to the right type. Check
3336 // to see if there is a potentially weird extension going on here. This can
3337 // happen when you do an atomic operation on something like an char* and
3338 // pass in 42. The 42 gets converted to char. This is even more strange
3339 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003340 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003341 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003342 }
Mike Stump11289f42009-09-09 15:08:12 +00003343
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003344 ASTContext& Context = this->getASTContext();
3345
3346 // Create a new DeclRefExpr to refer to the new decl.
3347 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3348 Context,
3349 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003350 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003351 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003352 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003353 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003354 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003355 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003356
Chris Lattnerdc046542009-05-08 06:58:22 +00003357 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003358 // FIXME: This loses syntactic information.
3359 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3360 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3361 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003362 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003363
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003364 // Change the result type of the call to match the original value type. This
3365 // is arbitrary, but the codegen for these builtins ins design to handle it
3366 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003367 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003368
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003369 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003370}
3371
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003372/// SemaBuiltinNontemporalOverloaded - We have a call to
3373/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3374/// overloaded function based on the pointer type of its last argument.
3375///
3376/// This function goes through and does final semantic checking for these
3377/// builtins.
3378ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3379 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3380 DeclRefExpr *DRE =
3381 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3382 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3383 unsigned BuiltinID = FDecl->getBuiltinID();
3384 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3385 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3386 "Unexpected nontemporal load/store builtin!");
3387 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3388 unsigned numArgs = isStore ? 2 : 1;
3389
3390 // Ensure that we have the proper number of arguments.
3391 if (checkArgCount(*this, TheCall, numArgs))
3392 return ExprError();
3393
3394 // Inspect the last argument of the nontemporal builtin. This should always
3395 // be a pointer type, from which we imply the type of the memory access.
3396 // Because it is a pointer type, we don't have to worry about any implicit
3397 // casts here.
3398 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3399 ExprResult PointerArgResult =
3400 DefaultFunctionArrayLvalueConversion(PointerArg);
3401
3402 if (PointerArgResult.isInvalid())
3403 return ExprError();
3404 PointerArg = PointerArgResult.get();
3405 TheCall->setArg(numArgs - 1, PointerArg);
3406
3407 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3408 if (!pointerType) {
3409 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3410 << PointerArg->getType() << PointerArg->getSourceRange();
3411 return ExprError();
3412 }
3413
3414 QualType ValType = pointerType->getPointeeType();
3415
3416 // Strip any qualifiers off ValType.
3417 ValType = ValType.getUnqualifiedType();
3418 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3419 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3420 !ValType->isVectorType()) {
3421 Diag(DRE->getLocStart(),
3422 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3423 << PointerArg->getType() << PointerArg->getSourceRange();
3424 return ExprError();
3425 }
3426
3427 if (!isStore) {
3428 TheCall->setType(ValType);
3429 return TheCallResult;
3430 }
3431
3432 ExprResult ValArg = TheCall->getArg(0);
3433 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3434 Context, ValType, /*consume*/ false);
3435 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3436 if (ValArg.isInvalid())
3437 return ExprError();
3438
3439 TheCall->setArg(0, ValArg.get());
3440 TheCall->setType(Context.VoidTy);
3441 return TheCallResult;
3442}
3443
Chris Lattner6436fb62009-02-18 06:01:06 +00003444/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003445/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003446/// Note: It might also make sense to do the UTF-16 conversion here (would
3447/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003448bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003449 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003450 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3451
Douglas Gregorfb65e592011-07-27 05:40:30 +00003452 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003453 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3454 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003455 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003456 }
Mike Stump11289f42009-09-09 15:08:12 +00003457
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003458 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003459 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003460 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00003461 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3462 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3463 llvm::UTF16 *ToPtr = &ToBuf[0];
3464
3465 llvm::ConversionResult Result =
3466 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3467 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003468 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00003469 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003470 Diag(Arg->getLocStart(),
3471 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3472 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003473 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003474}
3475
Mehdi Amini06d367c2016-10-24 20:39:34 +00003476/// CheckObjCString - Checks that the format string argument to the os_log()
3477/// and os_trace() functions is correct, and converts it to const char *.
3478ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3479 Arg = Arg->IgnoreParenCasts();
3480 auto *Literal = dyn_cast<StringLiteral>(Arg);
3481 if (!Literal) {
3482 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3483 Literal = ObjcLiteral->getString();
3484 }
3485 }
3486
3487 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3488 return ExprError(
3489 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3490 << Arg->getSourceRange());
3491 }
3492
3493 ExprResult Result(Literal);
3494 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3495 InitializedEntity Entity =
3496 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3497 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3498 return Result;
3499}
3500
Charles Davisc7d5c942015-09-17 20:55:33 +00003501/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3502/// for validity. Emit an error and return true on failure; return false
3503/// on success.
3504bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003505 Expr *Fn = TheCall->getCallee();
3506 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003507 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003508 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003509 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3510 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003511 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003512 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003513 return true;
3514 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003515
3516 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003517 return Diag(TheCall->getLocEnd(),
3518 diag::err_typecheck_call_too_few_args_at_least)
3519 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003520 }
3521
John McCall29ad95b2011-08-27 01:09:30 +00003522 // Type-check the first argument normally.
3523 if (checkBuiltinArgument(*this, TheCall, 0))
3524 return true;
3525
Chris Lattnere202e6a2007-12-20 00:05:45 +00003526 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00003527 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00003528 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00003529 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00003530 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00003531 else if (FunctionDecl *FD = getCurFunctionDecl())
3532 isVariadic = FD->isVariadic();
3533 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00003534 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00003535
Chris Lattnere202e6a2007-12-20 00:05:45 +00003536 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003537 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3538 return true;
3539 }
Mike Stump11289f42009-09-09 15:08:12 +00003540
Chris Lattner43be2e62007-12-19 23:59:04 +00003541 // Verify that the second argument to the builtin is the last argument of the
3542 // current function or method.
3543 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003544 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003545
Nico Weber9eea7642013-05-24 23:31:57 +00003546 // These are valid if SecondArgIsLastNamedArgument is false after the next
3547 // block.
3548 QualType Type;
3549 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003550 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003551
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003552 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3553 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003554 // FIXME: This isn't correct for methods (results in bogus warning).
3555 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003556 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00003557 if (CurBlock)
David Majnemera3debed2016-06-24 05:33:44 +00003558 LastArg = CurBlock->TheDecl->parameters().back();
Steve Naroff439a3e42009-04-15 19:33:47 +00003559 else if (FunctionDecl *FD = getCurFunctionDecl())
David Majnemera3debed2016-06-24 05:33:44 +00003560 LastArg = FD->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003561 else
David Majnemera3debed2016-06-24 05:33:44 +00003562 LastArg = getCurMethodDecl()->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003563 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00003564
3565 Type = PV->getType();
3566 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003567 IsCRegister =
3568 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003569 }
3570 }
Mike Stump11289f42009-09-09 15:08:12 +00003571
Chris Lattner43be2e62007-12-19 23:59:04 +00003572 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003573 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003574 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003575 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00003576 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3577 // Promotable integers are UB, but enumerations need a bit of
3578 // extra checking to see what their promotable type actually is.
3579 if (!Type->isPromotableIntegerType())
3580 return false;
3581 if (!Type->isEnumeralType())
3582 return true;
3583 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3584 return !(ED &&
3585 Context.typesAreCompatible(ED->getPromotionType(), Type));
3586 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00003587 unsigned Reason = 0;
3588 if (Type->isReferenceType()) Reason = 1;
3589 else if (IsCRegister) Reason = 2;
3590 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003591 Diag(ParamLoc, diag::note_parameter_type) << Type;
3592 }
3593
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003594 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003595 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003596}
Chris Lattner43be2e62007-12-19 23:59:04 +00003597
Charles Davisc7d5c942015-09-17 20:55:33 +00003598/// Check the arguments to '__builtin_va_start' for validity, and that
3599/// it was called from a function of the native ABI.
3600/// Emit an error and return true on failure; return false on success.
3601bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3602 // On x86-64 Unix, don't allow this in Win64 ABI functions.
3603 // On x64 Windows, don't allow this in System V ABI functions.
3604 // (Yes, that means there's no corresponding way to support variadic
3605 // System V ABI functions on Windows.)
3606 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3607 unsigned OS = Context.getTargetInfo().getTriple().getOS();
3608 clang::CallingConv CC = CC_C;
3609 if (const FunctionDecl *FD = getCurFunctionDecl())
3610 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3611 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3612 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3613 return Diag(TheCall->getCallee()->getLocStart(),
3614 diag::err_va_start_used_in_wrong_abi_function)
3615 << (OS != llvm::Triple::Win32);
3616 }
3617 return SemaBuiltinVAStartImpl(TheCall);
3618}
3619
3620/// Check the arguments to '__builtin_ms_va_start' for validity, and that
3621/// it was called from a Win64 ABI function.
3622/// Emit an error and return true on failure; return false on success.
3623bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3624 // This only makes sense for x86-64.
3625 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3626 Expr *Callee = TheCall->getCallee();
3627 if (TT.getArch() != llvm::Triple::x86_64)
3628 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3629 // Don't allow this in System V ABI functions.
3630 clang::CallingConv CC = CC_C;
3631 if (const FunctionDecl *FD = getCurFunctionDecl())
3632 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3633 if (CC == CC_X86_64SysV ||
3634 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3635 return Diag(Callee->getLocStart(),
3636 diag::err_ms_va_start_used_in_sysv_function);
3637 return SemaBuiltinVAStartImpl(TheCall);
3638}
3639
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003640bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3641 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3642 // const char *named_addr);
3643
3644 Expr *Func = Call->getCallee();
3645
3646 if (Call->getNumArgs() < 3)
3647 return Diag(Call->getLocEnd(),
3648 diag::err_typecheck_call_too_few_args_at_least)
3649 << 0 /*function call*/ << 3 << Call->getNumArgs();
3650
3651 // Determine whether the current function is variadic or not.
3652 bool IsVariadic;
3653 if (BlockScopeInfo *CurBlock = getCurBlock())
3654 IsVariadic = CurBlock->TheDecl->isVariadic();
3655 else if (FunctionDecl *FD = getCurFunctionDecl())
3656 IsVariadic = FD->isVariadic();
3657 else if (ObjCMethodDecl *MD = getCurMethodDecl())
3658 IsVariadic = MD->isVariadic();
3659 else
3660 llvm_unreachable("unexpected statement type");
3661
3662 if (!IsVariadic) {
3663 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3664 return true;
3665 }
3666
3667 // Type-check the first argument normally.
3668 if (checkBuiltinArgument(*this, Call, 0))
3669 return true;
3670
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003671 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003672 unsigned ArgNo;
3673 QualType Type;
3674 } ArgumentTypes[] = {
3675 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3676 { 2, Context.getSizeType() },
3677 };
3678
3679 for (const auto &AT : ArgumentTypes) {
3680 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3681 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3682 continue;
3683 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3684 << Arg->getType() << AT.Type << 1 /* different class */
3685 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3686 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3687 }
3688
3689 return false;
3690}
3691
Chris Lattner2da14fb2007-12-20 00:26:33 +00003692/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3693/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003694bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3695 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003696 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003697 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003698 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003699 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003700 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003701 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003702 << SourceRange(TheCall->getArg(2)->getLocStart(),
3703 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003704
John Wiegley01296292011-04-08 18:41:53 +00003705 ExprResult OrigArg0 = TheCall->getArg(0);
3706 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003707
Chris Lattner2da14fb2007-12-20 00:26:33 +00003708 // Do standard promotions between the two arguments, returning their common
3709 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003710 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003711 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3712 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003713
3714 // Make sure any conversions are pushed back into the call; this is
3715 // type safe since unordered compare builtins are declared as "_Bool
3716 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003717 TheCall->setArg(0, OrigArg0.get());
3718 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003719
John Wiegley01296292011-04-08 18:41:53 +00003720 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003721 return false;
3722
Chris Lattner2da14fb2007-12-20 00:26:33 +00003723 // If the common type isn't a real floating type, then the arguments were
3724 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003725 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00003726 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003727 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00003728 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3729 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003730
Chris Lattner2da14fb2007-12-20 00:26:33 +00003731 return false;
3732}
3733
Benjamin Kramer634fc102010-02-15 22:42:31 +00003734/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3735/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00003736/// to check everything. We expect the last argument to be a floating point
3737/// value.
3738bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3739 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00003740 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003741 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00003742 if (TheCall->getNumArgs() > NumArgs)
3743 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003744 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003745 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00003746 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003747 (*(TheCall->arg_end()-1))->getLocEnd());
3748
Benjamin Kramer64aae502010-02-16 10:07:31 +00003749 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00003750
Eli Friedman7e4faac2009-08-31 20:06:00 +00003751 if (OrigArg->isTypeDependent())
3752 return false;
3753
Chris Lattner68784ef2010-05-06 05:50:07 +00003754 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00003755 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00003756 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003757 diag::err_typecheck_call_invalid_unary_fp)
3758 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003759
Neil Hickey88c0fac2016-12-13 16:22:50 +00003760 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00003761 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00003762 // Only remove standard FloatCasts, leaving other casts inplace
3763 if (Cast->getCastKind() == CK_FloatingCast) {
3764 Expr *CastArg = Cast->getSubExpr();
3765 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3766 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
3767 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
3768 "promotion from float to either float or double is the only expected cast here");
3769 Cast->setSubExpr(nullptr);
3770 TheCall->setArg(NumArgs-1, CastArg);
3771 }
Chris Lattner68784ef2010-05-06 05:50:07 +00003772 }
3773 }
3774
Eli Friedman7e4faac2009-08-31 20:06:00 +00003775 return false;
3776}
3777
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003778/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3779// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00003780ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00003781 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003782 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00003783 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00003784 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3785 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003786
Nate Begemana0110022010-06-08 00:16:34 +00003787 // Determine which of the following types of shufflevector we're checking:
3788 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00003789 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00003790 QualType resType = TheCall->getArg(0)->getType();
3791 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00003792
Douglas Gregorc25f7662009-05-19 22:10:17 +00003793 if (!TheCall->getArg(0)->isTypeDependent() &&
3794 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00003795 QualType LHSType = TheCall->getArg(0)->getType();
3796 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00003797
Craig Topperbaca3892013-07-29 06:47:04 +00003798 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3799 return ExprError(Diag(TheCall->getLocStart(),
3800 diag::err_shufflevector_non_vector)
3801 << SourceRange(TheCall->getArg(0)->getLocStart(),
3802 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003803
Nate Begemana0110022010-06-08 00:16:34 +00003804 numElements = LHSType->getAs<VectorType>()->getNumElements();
3805 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00003806
Nate Begemana0110022010-06-08 00:16:34 +00003807 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3808 // with mask. If so, verify that RHS is an integer vector type with the
3809 // same number of elts as lhs.
3810 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00003811 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00003812 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00003813 return ExprError(Diag(TheCall->getLocStart(),
3814 diag::err_shufflevector_incompatible_vector)
3815 << SourceRange(TheCall->getArg(1)->getLocStart(),
3816 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003817 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00003818 return ExprError(Diag(TheCall->getLocStart(),
3819 diag::err_shufflevector_incompatible_vector)
3820 << SourceRange(TheCall->getArg(0)->getLocStart(),
3821 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00003822 } else if (numElements != numResElements) {
3823 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00003824 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003825 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003826 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003827 }
3828
3829 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00003830 if (TheCall->getArg(i)->isTypeDependent() ||
3831 TheCall->getArg(i)->isValueDependent())
3832 continue;
3833
Nate Begemana0110022010-06-08 00:16:34 +00003834 llvm::APSInt Result(32);
3835 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3836 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003837 diag::err_shufflevector_nonconstant_argument)
3838 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003839
Craig Topper50ad5b72013-08-03 17:40:38 +00003840 // Allow -1 which will be translated to undef in the IR.
3841 if (Result.isSigned() && Result.isAllOnesValue())
3842 continue;
3843
Chris Lattner7ab824e2008-08-10 02:05:13 +00003844 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003845 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003846 diag::err_shufflevector_argument_too_large)
3847 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003848 }
3849
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003850 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003851
Chris Lattner7ab824e2008-08-10 02:05:13 +00003852 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003853 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00003854 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003855 }
3856
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003857 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3858 TheCall->getCallee()->getLocStart(),
3859 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003860}
Chris Lattner43be2e62007-12-19 23:59:04 +00003861
Hal Finkelc4d7c822013-09-18 03:29:45 +00003862/// SemaConvertVectorExpr - Handle __builtin_convertvector
3863ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3864 SourceLocation BuiltinLoc,
3865 SourceLocation RParenLoc) {
3866 ExprValueKind VK = VK_RValue;
3867 ExprObjectKind OK = OK_Ordinary;
3868 QualType DstTy = TInfo->getType();
3869 QualType SrcTy = E->getType();
3870
3871 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3872 return ExprError(Diag(BuiltinLoc,
3873 diag::err_convertvector_non_vector)
3874 << E->getSourceRange());
3875 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3876 return ExprError(Diag(BuiltinLoc,
3877 diag::err_convertvector_non_vector_type));
3878
3879 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3880 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3881 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3882 if (SrcElts != DstElts)
3883 return ExprError(Diag(BuiltinLoc,
3884 diag::err_convertvector_incompatible_vector)
3885 << E->getSourceRange());
3886 }
3887
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003888 return new (Context)
3889 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003890}
3891
Daniel Dunbarb7257262008-07-21 22:59:13 +00003892/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3893// This is declared to take (const void*, ...) and can take two
3894// optional constant int args.
3895bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003896 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003897
Chris Lattner3b054132008-11-19 05:08:23 +00003898 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003899 return Diag(TheCall->getLocEnd(),
3900 diag::err_typecheck_call_too_many_args_at_most)
3901 << 0 /*function call*/ << 3 << NumArgs
3902 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003903
3904 // Argument 0 is checked for us and the remaining arguments must be
3905 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003906 for (unsigned i = 1; i != NumArgs; ++i)
3907 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003908 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003909
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003910 return false;
3911}
3912
Hal Finkelf0417332014-07-17 14:25:55 +00003913/// SemaBuiltinAssume - Handle __assume (MS Extension).
3914// __assume does not evaluate its arguments, and should warn if its argument
3915// has side effects.
3916bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3917 Expr *Arg = TheCall->getArg(0);
3918 if (Arg->isInstantiationDependent()) return false;
3919
3920 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003921 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003922 << Arg->getSourceRange()
3923 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3924
3925 return false;
3926}
3927
David Majnemer86b1bfa2016-10-31 18:07:57 +00003928/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00003929/// as (size_t, size_t) where the second size_t must be a power of 2 greater
3930/// than 8.
3931bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
3932 // The alignment must be a constant integer.
3933 Expr *Arg = TheCall->getArg(1);
3934
3935 // We can't check the value of a dependent argument.
3936 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00003937 if (const auto *UE =
3938 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
3939 if (UE->getKind() == UETT_AlignOf)
3940 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
3941 << Arg->getSourceRange();
3942
David Majnemer51169932016-10-31 05:37:48 +00003943 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
3944
3945 if (!Result.isPowerOf2())
3946 return Diag(TheCall->getLocStart(),
3947 diag::err_alignment_not_power_of_two)
3948 << Arg->getSourceRange();
3949
3950 if (Result < Context.getCharWidth())
3951 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
3952 << (unsigned)Context.getCharWidth()
3953 << Arg->getSourceRange();
3954
3955 if (Result > INT32_MAX)
3956 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
3957 << INT32_MAX
3958 << Arg->getSourceRange();
3959 }
3960
3961 return false;
3962}
3963
3964/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00003965/// as (const void*, size_t, ...) and can take one optional constant int arg.
3966bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3967 unsigned NumArgs = TheCall->getNumArgs();
3968
3969 if (NumArgs > 3)
3970 return Diag(TheCall->getLocEnd(),
3971 diag::err_typecheck_call_too_many_args_at_most)
3972 << 0 /*function call*/ << 3 << NumArgs
3973 << TheCall->getSourceRange();
3974
3975 // The alignment must be a constant integer.
3976 Expr *Arg = TheCall->getArg(1);
3977
3978 // We can't check the value of a dependent argument.
3979 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3980 llvm::APSInt Result;
3981 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3982 return true;
3983
3984 if (!Result.isPowerOf2())
3985 return Diag(TheCall->getLocStart(),
3986 diag::err_alignment_not_power_of_two)
3987 << Arg->getSourceRange();
3988 }
3989
3990 if (NumArgs > 2) {
3991 ExprResult Arg(TheCall->getArg(2));
3992 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3993 Context.getSizeType(), false);
3994 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3995 if (Arg.isInvalid()) return true;
3996 TheCall->setArg(2, Arg.get());
3997 }
Hal Finkelf0417332014-07-17 14:25:55 +00003998
3999 return false;
4000}
4001
Mehdi Amini06d367c2016-10-24 20:39:34 +00004002bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4003 unsigned BuiltinID =
4004 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4005 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4006
4007 unsigned NumArgs = TheCall->getNumArgs();
4008 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4009 if (NumArgs < NumRequiredArgs) {
4010 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4011 << 0 /* function call */ << NumRequiredArgs << NumArgs
4012 << TheCall->getSourceRange();
4013 }
4014 if (NumArgs >= NumRequiredArgs + 0x100) {
4015 return Diag(TheCall->getLocEnd(),
4016 diag::err_typecheck_call_too_many_args_at_most)
4017 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4018 << TheCall->getSourceRange();
4019 }
4020 unsigned i = 0;
4021
4022 // For formatting call, check buffer arg.
4023 if (!IsSizeCall) {
4024 ExprResult Arg(TheCall->getArg(i));
4025 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4026 Context, Context.VoidPtrTy, false);
4027 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4028 if (Arg.isInvalid())
4029 return true;
4030 TheCall->setArg(i, Arg.get());
4031 i++;
4032 }
4033
4034 // Check string literal arg.
4035 unsigned FormatIdx = i;
4036 {
4037 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4038 if (Arg.isInvalid())
4039 return true;
4040 TheCall->setArg(i, Arg.get());
4041 i++;
4042 }
4043
4044 // Make sure variadic args are scalar.
4045 unsigned FirstDataArg = i;
4046 while (i < NumArgs) {
4047 ExprResult Arg = DefaultVariadicArgumentPromotion(
4048 TheCall->getArg(i), VariadicFunction, nullptr);
4049 if (Arg.isInvalid())
4050 return true;
4051 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4052 if (ArgSize.getQuantity() >= 0x100) {
4053 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4054 << i << (int)ArgSize.getQuantity() << 0xff
4055 << TheCall->getSourceRange();
4056 }
4057 TheCall->setArg(i, Arg.get());
4058 i++;
4059 }
4060
4061 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4062 // call to avoid duplicate diagnostics.
4063 if (!IsSizeCall) {
4064 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4065 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4066 bool Success = CheckFormatArguments(
4067 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4068 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4069 CheckedVarArgs);
4070 if (!Success)
4071 return true;
4072 }
4073
4074 if (IsSizeCall) {
4075 TheCall->setType(Context.getSizeType());
4076 } else {
4077 TheCall->setType(Context.VoidPtrTy);
4078 }
4079 return false;
4080}
4081
Eric Christopher8d0c6212010-04-17 02:26:23 +00004082/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4083/// TheCall is a constant expression.
4084bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4085 llvm::APSInt &Result) {
4086 Expr *Arg = TheCall->getArg(ArgNum);
4087 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4088 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4089
4090 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4091
4092 if (!Arg->isIntegerConstantExpr(Result, Context))
4093 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004094 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004095
Chris Lattnerd545ad12009-09-23 06:06:36 +00004096 return false;
4097}
4098
Richard Sandiford28940af2014-04-16 08:47:51 +00004099/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4100/// TheCall is a constant expression in the range [Low, High].
4101bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4102 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004103 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004104
4105 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004106 Expr *Arg = TheCall->getArg(ArgNum);
4107 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004108 return false;
4109
Eric Christopher8d0c6212010-04-17 02:26:23 +00004110 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004111 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004112 return true;
4113
Richard Sandiford28940af2014-04-16 08:47:51 +00004114 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004115 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004116 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004117
4118 return false;
4119}
4120
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004121/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4122/// TheCall is a constant expression is a multiple of Num..
4123bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4124 unsigned Num) {
4125 llvm::APSInt Result;
4126
4127 // We can't check the value of a dependent argument.
4128 Expr *Arg = TheCall->getArg(ArgNum);
4129 if (Arg->isTypeDependent() || Arg->isValueDependent())
4130 return false;
4131
4132 // Check constant-ness first.
4133 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4134 return true;
4135
4136 if (Result.getSExtValue() % Num != 0)
4137 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4138 << Num << Arg->getSourceRange();
4139
4140 return false;
4141}
4142
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004143/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4144/// TheCall is an ARM/AArch64 special register string literal.
4145bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4146 int ArgNum, unsigned ExpectedFieldNum,
4147 bool AllowName) {
4148 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4149 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4150 BuiltinID == ARM::BI__builtin_arm_rsr ||
4151 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4152 BuiltinID == ARM::BI__builtin_arm_wsr ||
4153 BuiltinID == ARM::BI__builtin_arm_wsrp;
4154 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4155 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4156 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4157 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4158 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4159 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4160 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4161
4162 // We can't check the value of a dependent argument.
4163 Expr *Arg = TheCall->getArg(ArgNum);
4164 if (Arg->isTypeDependent() || Arg->isValueDependent())
4165 return false;
4166
4167 // Check if the argument is a string literal.
4168 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4169 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4170 << Arg->getSourceRange();
4171
4172 // Check the type of special register given.
4173 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4174 SmallVector<StringRef, 6> Fields;
4175 Reg.split(Fields, ":");
4176
4177 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4178 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4179 << Arg->getSourceRange();
4180
4181 // If the string is the name of a register then we cannot check that it is
4182 // valid here but if the string is of one the forms described in ACLE then we
4183 // can check that the supplied fields are integers and within the valid
4184 // ranges.
4185 if (Fields.size() > 1) {
4186 bool FiveFields = Fields.size() == 5;
4187
4188 bool ValidString = true;
4189 if (IsARMBuiltin) {
4190 ValidString &= Fields[0].startswith_lower("cp") ||
4191 Fields[0].startswith_lower("p");
4192 if (ValidString)
4193 Fields[0] =
4194 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4195
4196 ValidString &= Fields[2].startswith_lower("c");
4197 if (ValidString)
4198 Fields[2] = Fields[2].drop_front(1);
4199
4200 if (FiveFields) {
4201 ValidString &= Fields[3].startswith_lower("c");
4202 if (ValidString)
4203 Fields[3] = Fields[3].drop_front(1);
4204 }
4205 }
4206
4207 SmallVector<int, 5> Ranges;
4208 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00004209 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004210 else
4211 Ranges.append({15, 7, 15});
4212
4213 for (unsigned i=0; i<Fields.size(); ++i) {
4214 int IntField;
4215 ValidString &= !Fields[i].getAsInteger(10, IntField);
4216 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4217 }
4218
4219 if (!ValidString)
4220 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4221 << Arg->getSourceRange();
4222
4223 } else if (IsAArch64Builtin && Fields.size() == 1) {
4224 // If the register name is one of those that appear in the condition below
4225 // and the special register builtin being used is one of the write builtins,
4226 // then we require that the argument provided for writing to the register
4227 // is an integer constant expression. This is because it will be lowered to
4228 // an MSR (immediate) instruction, so we need to know the immediate at
4229 // compile time.
4230 if (TheCall->getNumArgs() != 2)
4231 return false;
4232
4233 std::string RegLower = Reg.lower();
4234 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4235 RegLower != "pan" && RegLower != "uao")
4236 return false;
4237
4238 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4239 }
4240
4241 return false;
4242}
4243
Eli Friedmanc97d0142009-05-03 06:04:26 +00004244/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004245/// This checks that the target supports __builtin_longjmp and
4246/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004247bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004248 if (!Context.getTargetInfo().hasSjLjLowering())
4249 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4250 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4251
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004252 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004253 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004254
Eric Christopher8d0c6212010-04-17 02:26:23 +00004255 // TODO: This is less than ideal. Overload this to take a value.
4256 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4257 return true;
4258
4259 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004260 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4261 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4262
4263 return false;
4264}
4265
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004266/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4267/// This checks that the target supports __builtin_setjmp.
4268bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4269 if (!Context.getTargetInfo().hasSjLjLowering())
4270 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4271 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4272 return false;
4273}
4274
Richard Smithd7293d72013-08-05 18:49:43 +00004275namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004276class UncoveredArgHandler {
4277 enum { Unknown = -1, AllCovered = -2 };
4278 signed FirstUncoveredArg;
4279 SmallVector<const Expr *, 4> DiagnosticExprs;
4280
4281public:
4282 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4283
4284 bool hasUncoveredArg() const {
4285 return (FirstUncoveredArg >= 0);
4286 }
4287
4288 unsigned getUncoveredArg() const {
4289 assert(hasUncoveredArg() && "no uncovered argument");
4290 return FirstUncoveredArg;
4291 }
4292
4293 void setAllCovered() {
4294 // A string has been found with all arguments covered, so clear out
4295 // the diagnostics.
4296 DiagnosticExprs.clear();
4297 FirstUncoveredArg = AllCovered;
4298 }
4299
4300 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4301 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4302
4303 // Don't update if a previous string covers all arguments.
4304 if (FirstUncoveredArg == AllCovered)
4305 return;
4306
4307 // UncoveredArgHandler tracks the highest uncovered argument index
4308 // and with it all the strings that match this index.
4309 if (NewFirstUncoveredArg == FirstUncoveredArg)
4310 DiagnosticExprs.push_back(StrExpr);
4311 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4312 DiagnosticExprs.clear();
4313 DiagnosticExprs.push_back(StrExpr);
4314 FirstUncoveredArg = NewFirstUncoveredArg;
4315 }
4316 }
4317
4318 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4319};
4320
Richard Smithd7293d72013-08-05 18:49:43 +00004321enum StringLiteralCheckType {
4322 SLCT_NotALiteral,
4323 SLCT_UncheckedLiteral,
4324 SLCT_CheckedLiteral
4325};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004326} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00004327
Stephen Hines648c3692016-09-16 01:07:04 +00004328static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4329 BinaryOperatorKind BinOpKind,
4330 bool AddendIsRight) {
4331 unsigned BitWidth = Offset.getBitWidth();
4332 unsigned AddendBitWidth = Addend.getBitWidth();
4333 // There might be negative interim results.
4334 if (Addend.isUnsigned()) {
4335 Addend = Addend.zext(++AddendBitWidth);
4336 Addend.setIsSigned(true);
4337 }
4338 // Adjust the bit width of the APSInts.
4339 if (AddendBitWidth > BitWidth) {
4340 Offset = Offset.sext(AddendBitWidth);
4341 BitWidth = AddendBitWidth;
4342 } else if (BitWidth > AddendBitWidth) {
4343 Addend = Addend.sext(BitWidth);
4344 }
4345
4346 bool Ov = false;
4347 llvm::APSInt ResOffset = Offset;
4348 if (BinOpKind == BO_Add)
4349 ResOffset = Offset.sadd_ov(Addend, Ov);
4350 else {
4351 assert(AddendIsRight && BinOpKind == BO_Sub &&
4352 "operator must be add or sub with addend on the right");
4353 ResOffset = Offset.ssub_ov(Addend, Ov);
4354 }
4355
4356 // We add an offset to a pointer here so we should support an offset as big as
4357 // possible.
4358 if (Ov) {
4359 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00004360 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00004361 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4362 return;
4363 }
4364
4365 Offset = ResOffset;
4366}
4367
4368namespace {
4369// This is a wrapper class around StringLiteral to support offsetted string
4370// literals as format strings. It takes the offset into account when returning
4371// the string and its length or the source locations to display notes correctly.
4372class FormatStringLiteral {
4373 const StringLiteral *FExpr;
4374 int64_t Offset;
4375
4376 public:
4377 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4378 : FExpr(fexpr), Offset(Offset) {}
4379
4380 StringRef getString() const {
4381 return FExpr->getString().drop_front(Offset);
4382 }
4383
4384 unsigned getByteLength() const {
4385 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4386 }
4387 unsigned getLength() const { return FExpr->getLength() - Offset; }
4388 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4389
4390 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4391
4392 QualType getType() const { return FExpr->getType(); }
4393
4394 bool isAscii() const { return FExpr->isAscii(); }
4395 bool isWide() const { return FExpr->isWide(); }
4396 bool isUTF8() const { return FExpr->isUTF8(); }
4397 bool isUTF16() const { return FExpr->isUTF16(); }
4398 bool isUTF32() const { return FExpr->isUTF32(); }
4399 bool isPascal() const { return FExpr->isPascal(); }
4400
4401 SourceLocation getLocationOfByte(
4402 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4403 const TargetInfo &Target, unsigned *StartToken = nullptr,
4404 unsigned *StartTokenByteOffset = nullptr) const {
4405 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4406 StartToken, StartTokenByteOffset);
4407 }
4408
4409 SourceLocation getLocStart() const LLVM_READONLY {
4410 return FExpr->getLocStart().getLocWithOffset(Offset);
4411 }
4412 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4413};
4414} // end anonymous namespace
4415
4416static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004417 const Expr *OrigFormatExpr,
4418 ArrayRef<const Expr *> Args,
4419 bool HasVAListArg, unsigned format_idx,
4420 unsigned firstDataArg,
4421 Sema::FormatStringType Type,
4422 bool inFunctionCall,
4423 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004424 llvm::SmallBitVector &CheckedVarArgs,
4425 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004426
Richard Smith55ce3522012-06-25 20:30:08 +00004427// Determine if an expression is a string literal or constant string.
4428// If this function returns false on the arguments to a function expecting a
4429// format string, we will usually need to emit a warning.
4430// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00004431static StringLiteralCheckType
4432checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4433 bool HasVAListArg, unsigned format_idx,
4434 unsigned firstDataArg, Sema::FormatStringType Type,
4435 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004436 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004437 UncoveredArgHandler &UncoveredArg,
4438 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00004439 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00004440 assert(Offset.isSigned() && "invalid offset");
4441
Douglas Gregorc25f7662009-05-19 22:10:17 +00004442 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00004443 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004444
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004445 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00004446
Richard Smithd7293d72013-08-05 18:49:43 +00004447 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00004448 // Technically -Wformat-nonliteral does not warn about this case.
4449 // The behavior of printf and friends in this case is implementation
4450 // dependent. Ideally if the format string cannot be null then
4451 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00004452 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00004453
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004454 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00004455 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004456 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00004457 // The expression is a literal if both sub-expressions were, and it was
4458 // completely checked only if both sub-expressions were checked.
4459 const AbstractConditionalOperator *C =
4460 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004461
4462 // Determine whether it is necessary to check both sub-expressions, for
4463 // example, because the condition expression is a constant that can be
4464 // evaluated at compile time.
4465 bool CheckLeft = true, CheckRight = true;
4466
4467 bool Cond;
4468 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4469 if (Cond)
4470 CheckRight = false;
4471 else
4472 CheckLeft = false;
4473 }
4474
Stephen Hines648c3692016-09-16 01:07:04 +00004475 // We need to maintain the offsets for the right and the left hand side
4476 // separately to check if every possible indexed expression is a valid
4477 // string literal. They might have different offsets for different string
4478 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004479 StringLiteralCheckType Left;
4480 if (!CheckLeft)
4481 Left = SLCT_UncheckedLiteral;
4482 else {
4483 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4484 HasVAListArg, format_idx, firstDataArg,
4485 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004486 CheckedVarArgs, UncoveredArg, Offset);
4487 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004488 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004489 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004490 }
4491
Richard Smith55ce3522012-06-25 20:30:08 +00004492 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004493 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004494 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004495 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004496 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004497
4498 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004499 }
4500
4501 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00004502 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4503 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004504 }
4505
John McCallc07a0c72011-02-17 10:25:35 +00004506 case Stmt::OpaqueValueExprClass:
4507 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4508 E = src;
4509 goto tryAgain;
4510 }
Richard Smith55ce3522012-06-25 20:30:08 +00004511 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004512
Ted Kremeneka8890832011-02-24 23:03:04 +00004513 case Stmt::PredefinedExprClass:
4514 // While __func__, etc., are technically not string literals, they
4515 // cannot contain format specifiers and thus are not a security
4516 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004517 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004518
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004519 case Stmt::DeclRefExprClass: {
4520 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004521
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004522 // As an exception, do not flag errors for variables binding to
4523 // const string literals.
4524 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4525 bool isConstant = false;
4526 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004527
Richard Smithd7293d72013-08-05 18:49:43 +00004528 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4529 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004530 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004531 isConstant = T.isConstant(S.Context) &&
4532 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004533 } else if (T->isObjCObjectPointerType()) {
4534 // In ObjC, there is usually no "const ObjectPointer" type,
4535 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004536 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004537 }
Mike Stump11289f42009-09-09 15:08:12 +00004538
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004539 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004540 if (const Expr *Init = VD->getAnyInitializer()) {
4541 // Look through initializers like const char c[] = { "foo" }
4542 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4543 if (InitList->isStringLiteralInit())
4544 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4545 }
Richard Smithd7293d72013-08-05 18:49:43 +00004546 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004547 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004548 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004549 /*InFunctionCall*/ false, CheckedVarArgs,
4550 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004551 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004552 }
Mike Stump11289f42009-09-09 15:08:12 +00004553
Anders Carlssonb012ca92009-06-28 19:55:58 +00004554 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4555 // special check to see if the format string is a function parameter
4556 // of the function calling the printf function. If the function
4557 // has an attribute indicating it is a printf-like function, then we
4558 // should suppress warnings concerning non-literals being used in a call
4559 // to a vprintf function. For example:
4560 //
4561 // void
4562 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4563 // va_list ap;
4564 // va_start(ap, fmt);
4565 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4566 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00004567 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004568 if (HasVAListArg) {
4569 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4570 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4571 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004572 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004573 // adjust for implicit parameter
4574 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4575 if (MD->isInstance())
4576 ++PVIndex;
4577 // We also check if the formats are compatible.
4578 // We can't pass a 'scanf' string to a 'printf' function.
4579 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00004580 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00004581 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004582 }
4583 }
4584 }
4585 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004586 }
Mike Stump11289f42009-09-09 15:08:12 +00004587
Richard Smith55ce3522012-06-25 20:30:08 +00004588 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004589 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004590
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004591 case Stmt::CallExprClass:
4592 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004593 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004594 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4595 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4596 unsigned ArgIndex = FA->getFormatIdx();
4597 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4598 if (MD->isInstance())
4599 --ArgIndex;
4600 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00004601
Richard Smithd7293d72013-08-05 18:49:43 +00004602 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004603 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00004604 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004605 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004606 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4607 unsigned BuiltinID = FD->getBuiltinID();
4608 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4609 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4610 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00004611 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004612 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004613 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004614 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004615 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004616 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004617 }
4618 }
Mike Stump11289f42009-09-09 15:08:12 +00004619
Richard Smith55ce3522012-06-25 20:30:08 +00004620 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004621 }
Alex Lorenzd9007142016-10-24 09:42:34 +00004622 case Stmt::ObjCMessageExprClass: {
4623 const auto *ME = cast<ObjCMessageExpr>(E);
4624 if (const auto *ND = ME->getMethodDecl()) {
4625 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4626 unsigned ArgIndex = FA->getFormatIdx();
4627 const Expr *Arg = ME->getArg(ArgIndex - 1);
4628 return checkFormatStringExpr(
4629 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4630 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4631 }
4632 }
4633
4634 return SLCT_NotALiteral;
4635 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004636 case Stmt::ObjCStringLiteralClass:
4637 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00004638 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004639
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004640 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004641 StrE = ObjCFExpr->getString();
4642 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004643 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004644
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004645 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00004646 if (Offset.isNegative() || Offset > StrE->getLength()) {
4647 // TODO: It would be better to have an explicit warning for out of
4648 // bounds literals.
4649 return SLCT_NotALiteral;
4650 }
4651 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4652 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004653 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004654 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00004655 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004656 }
Mike Stump11289f42009-09-09 15:08:12 +00004657
Richard Smith55ce3522012-06-25 20:30:08 +00004658 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004659 }
Stephen Hines648c3692016-09-16 01:07:04 +00004660 case Stmt::BinaryOperatorClass: {
4661 llvm::APSInt LResult;
4662 llvm::APSInt RResult;
4663
4664 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4665
4666 // A string literal + an int offset is still a string literal.
4667 if (BinOp->isAdditiveOp()) {
4668 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4669 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4670
4671 if (LIsInt != RIsInt) {
4672 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4673
4674 if (LIsInt) {
4675 if (BinOpKind == BO_Add) {
4676 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4677 E = BinOp->getRHS();
4678 goto tryAgain;
4679 }
4680 } else {
4681 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4682 E = BinOp->getLHS();
4683 goto tryAgain;
4684 }
4685 }
Stephen Hines648c3692016-09-16 01:07:04 +00004686 }
George Burgess IVd273aab2016-09-22 00:00:26 +00004687
4688 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00004689 }
4690 case Stmt::UnaryOperatorClass: {
4691 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4692 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4693 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4694 llvm::APSInt IndexResult;
4695 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4696 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4697 E = ASE->getBase();
4698 goto tryAgain;
4699 }
4700 }
4701
4702 return SLCT_NotALiteral;
4703 }
Mike Stump11289f42009-09-09 15:08:12 +00004704
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004705 default:
Richard Smith55ce3522012-06-25 20:30:08 +00004706 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004707 }
4708}
4709
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004710Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00004711 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00004712 .Case("scanf", FST_Scanf)
4713 .Cases("printf", "printf0", FST_Printf)
4714 .Cases("NSString", "CFString", FST_NSString)
4715 .Case("strftime", FST_Strftime)
4716 .Case("strfmon", FST_Strfmon)
4717 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4718 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4719 .Case("os_trace", FST_OSLog)
4720 .Case("os_log", FST_OSLog)
4721 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004722}
4723
Jordan Rose3e0ec582012-07-19 18:10:23 +00004724/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00004725/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00004726/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004727bool Sema::CheckFormatArguments(const FormatAttr *Format,
4728 ArrayRef<const Expr *> Args,
4729 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004730 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004731 SourceLocation Loc, SourceRange Range,
4732 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00004733 FormatStringInfo FSI;
4734 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004735 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00004736 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00004737 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00004738 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004739}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00004740
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004741bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004742 bool HasVAListArg, unsigned format_idx,
4743 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004744 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004745 SourceLocation Loc, SourceRange Range,
4746 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004747 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004748 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004749 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00004750 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004751 }
Mike Stump11289f42009-09-09 15:08:12 +00004752
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004753 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004754
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004755 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00004756 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004757 // Dynamically generated format strings are difficult to
4758 // automatically vet at compile time. Requiring that format strings
4759 // are string literals: (1) permits the checking of format strings by
4760 // the compiler and thereby (2) can practically remove the source of
4761 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00004762
Mike Stump11289f42009-09-09 15:08:12 +00004763 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00004764 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00004765 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00004766 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004767 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00004768 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00004769 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4770 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004771 /*IsFunctionCall*/ true, CheckedVarArgs,
4772 UncoveredArg,
4773 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004774
4775 // Generate a diagnostic where an uncovered argument is detected.
4776 if (UncoveredArg.hasUncoveredArg()) {
4777 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4778 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4779 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4780 }
4781
Richard Smith55ce3522012-06-25 20:30:08 +00004782 if (CT != SLCT_NotALiteral)
4783 // Literal format string found, check done!
4784 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00004785
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004786 // Strftime is particular as it always uses a single 'time' argument,
4787 // so it is safe to pass a non-literal string.
4788 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00004789 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004790
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004791 // Do not emit diag when the string param is a macro expansion and the
4792 // format is either NSString or CFString. This is a hack to prevent
4793 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4794 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004795 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4796 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00004797 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004798
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004799 // If there are no arguments specified, warn with -Wformat-security, otherwise
4800 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004801 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00004802 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4803 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004804 switch (Type) {
4805 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004806 break;
4807 case FST_Kprintf:
4808 case FST_FreeBSDKPrintf:
4809 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00004810 Diag(FormatLoc, diag::note_format_security_fixit)
4811 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004812 break;
4813 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00004814 Diag(FormatLoc, diag::note_format_security_fixit)
4815 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004816 break;
4817 }
4818 } else {
4819 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004820 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004821 }
Richard Smith55ce3522012-06-25 20:30:08 +00004822 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004823}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004824
Ted Kremenekab278de2010-01-28 23:39:18 +00004825namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00004826class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4827protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00004828 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00004829 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00004830 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00004831 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00004832 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00004833 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00004834 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00004835 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004836 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00004837 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00004838 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00004839 bool usesPositionalArgs;
4840 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004841 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00004842 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00004843 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004844 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004845
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004846public:
Stephen Hines648c3692016-09-16 01:07:04 +00004847 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00004848 const Expr *origFormatExpr,
4849 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004850 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00004851 ArrayRef<const Expr *> Args, unsigned formatIdx,
4852 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004853 llvm::SmallBitVector &CheckedVarArgs,
4854 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00004855 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
4856 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
4857 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
4858 usesPositionalArgs(false), atFirstArg(true),
4859 inFunctionCall(inFunctionCall), CallType(callType),
4860 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00004861 CoveredArgs.resize(numDataArgs);
4862 CoveredArgs.reset();
4863 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004864
Ted Kremenek019d2242010-01-29 01:50:07 +00004865 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004866
Ted Kremenek02087932010-07-16 02:11:22 +00004867 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004868 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004869
Jordan Rose92303592012-09-08 04:00:03 +00004870 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004871 const analyze_format_string::FormatSpecifier &FS,
4872 const analyze_format_string::ConversionSpecifier &CS,
4873 const char *startSpecifier, unsigned specifierLen,
4874 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00004875
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004876 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004877 const analyze_format_string::FormatSpecifier &FS,
4878 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004879
4880 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004881 const analyze_format_string::ConversionSpecifier &CS,
4882 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004883
Craig Toppere14c0f82014-03-12 04:55:44 +00004884 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004885
Craig Toppere14c0f82014-03-12 04:55:44 +00004886 void HandleInvalidPosition(const char *startSpecifier,
4887 unsigned specifierLen,
4888 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004889
Craig Toppere14c0f82014-03-12 04:55:44 +00004890 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004891
Craig Toppere14c0f82014-03-12 04:55:44 +00004892 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004893
Richard Trieu03cf7b72011-10-28 00:41:25 +00004894 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00004895 static void
4896 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4897 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4898 bool IsStringLocation, Range StringRange,
4899 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004900
Ted Kremenek02087932010-07-16 02:11:22 +00004901protected:
Ted Kremenekce815422010-07-19 21:25:57 +00004902 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4903 const char *startSpec,
4904 unsigned specifierLen,
4905 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004906
4907 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4908 const char *startSpec,
4909 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00004910
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004911 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00004912 CharSourceRange getSpecifierRange(const char *startSpecifier,
4913 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00004914 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004915
Ted Kremenek5739de72010-01-29 01:06:55 +00004916 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004917
4918 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4919 const analyze_format_string::ConversionSpecifier &CS,
4920 const char *startSpecifier, unsigned specifierLen,
4921 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004922
4923 template <typename Range>
4924 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4925 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004926 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00004927};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004928} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004929
Ted Kremenek02087932010-07-16 02:11:22 +00004930SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00004931 return OrigFormatExpr->getSourceRange();
4932}
4933
Ted Kremenek02087932010-07-16 02:11:22 +00004934CharSourceRange CheckFormatHandler::
4935getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00004936 SourceLocation Start = getLocationOfByte(startSpecifier);
4937 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
4938
4939 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004940 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00004941
4942 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004943}
4944
Ted Kremenek02087932010-07-16 02:11:22 +00004945SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00004946 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
4947 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00004948}
4949
Ted Kremenek02087932010-07-16 02:11:22 +00004950void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4951 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00004952 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4953 getLocationOfByte(startSpecifier),
4954 /*IsStringLocation*/true,
4955 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00004956}
4957
Jordan Rose92303592012-09-08 04:00:03 +00004958void CheckFormatHandler::HandleInvalidLengthModifier(
4959 const analyze_format_string::FormatSpecifier &FS,
4960 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00004961 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00004962 using namespace analyze_format_string;
4963
4964 const LengthModifier &LM = FS.getLengthModifier();
4965 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4966
4967 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004968 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00004969 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004970 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004971 getLocationOfByte(LM.getStart()),
4972 /*IsStringLocation*/true,
4973 getSpecifierRange(startSpecifier, specifierLen));
4974
4975 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4976 << FixedLM->toString()
4977 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4978
4979 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004980 FixItHint Hint;
4981 if (DiagID == diag::warn_format_nonsensical_length)
4982 Hint = FixItHint::CreateRemoval(LMRange);
4983
4984 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004985 getLocationOfByte(LM.getStart()),
4986 /*IsStringLocation*/true,
4987 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00004988 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00004989 }
4990}
4991
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004992void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00004993 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004994 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004995 using namespace analyze_format_string;
4996
4997 const LengthModifier &LM = FS.getLengthModifier();
4998 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4999
5000 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005001 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005002 if (FixedLM) {
5003 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5004 << LM.toString() << 0,
5005 getLocationOfByte(LM.getStart()),
5006 /*IsStringLocation*/true,
5007 getSpecifierRange(startSpecifier, specifierLen));
5008
5009 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5010 << FixedLM->toString()
5011 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5012
5013 } else {
5014 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5015 << LM.toString() << 0,
5016 getLocationOfByte(LM.getStart()),
5017 /*IsStringLocation*/true,
5018 getSpecifierRange(startSpecifier, specifierLen));
5019 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005020}
5021
5022void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5023 const analyze_format_string::ConversionSpecifier &CS,
5024 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005025 using namespace analyze_format_string;
5026
5027 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005028 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005029 if (FixedCS) {
5030 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5031 << CS.toString() << /*conversion specifier*/1,
5032 getLocationOfByte(CS.getStart()),
5033 /*IsStringLocation*/true,
5034 getSpecifierRange(startSpecifier, specifierLen));
5035
5036 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5037 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5038 << FixedCS->toString()
5039 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5040 } else {
5041 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5042 << CS.toString() << /*conversion specifier*/1,
5043 getLocationOfByte(CS.getStart()),
5044 /*IsStringLocation*/true,
5045 getSpecifierRange(startSpecifier, specifierLen));
5046 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005047}
5048
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005049void CheckFormatHandler::HandlePosition(const char *startPos,
5050 unsigned posLen) {
5051 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5052 getLocationOfByte(startPos),
5053 /*IsStringLocation*/true,
5054 getSpecifierRange(startPos, posLen));
5055}
5056
Ted Kremenekd1668192010-02-27 01:41:03 +00005057void
Ted Kremenek02087932010-07-16 02:11:22 +00005058CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5059 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005060 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5061 << (unsigned) p,
5062 getLocationOfByte(startPos), /*IsStringLocation*/true,
5063 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005064}
5065
Ted Kremenek02087932010-07-16 02:11:22 +00005066void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005067 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005068 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5069 getLocationOfByte(startPos),
5070 /*IsStringLocation*/true,
5071 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005072}
5073
Ted Kremenek02087932010-07-16 02:11:22 +00005074void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005075 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005076 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005077 EmitFormatDiagnostic(
5078 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5079 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5080 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005081 }
Ted Kremenek02087932010-07-16 02:11:22 +00005082}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005083
Jordan Rose58bbe422012-07-19 18:10:08 +00005084// Note that this may return NULL if there was an error parsing or building
5085// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005086const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005087 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005088}
5089
5090void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005091 // Does the number of data arguments exceed the number of
5092 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005093 if (!HasVAListArg) {
5094 // Find any arguments that weren't covered.
5095 CoveredArgs.flip();
5096 signed notCoveredArg = CoveredArgs.find_first();
5097 if (notCoveredArg >= 0) {
5098 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005099 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5100 } else {
5101 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005102 }
5103 }
5104}
5105
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005106void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5107 const Expr *ArgExpr) {
5108 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5109 "Invalid state");
5110
5111 if (!ArgExpr)
5112 return;
5113
5114 SourceLocation Loc = ArgExpr->getLocStart();
5115
5116 if (S.getSourceManager().isInSystemMacro(Loc))
5117 return;
5118
5119 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5120 for (auto E : DiagnosticExprs)
5121 PDiag << E->getSourceRange();
5122
5123 CheckFormatHandler::EmitFormatDiagnostic(
5124 S, IsFunctionCall, DiagnosticExprs[0],
5125 PDiag, Loc, /*IsStringLocation*/false,
5126 DiagnosticExprs[0]->getSourceRange());
5127}
5128
Ted Kremenekce815422010-07-19 21:25:57 +00005129bool
5130CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5131 SourceLocation Loc,
5132 const char *startSpec,
5133 unsigned specifierLen,
5134 const char *csStart,
5135 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005136 bool keepGoing = true;
5137 if (argIndex < NumDataArgs) {
5138 // Consider the argument coverered, even though the specifier doesn't
5139 // make sense.
5140 CoveredArgs.set(argIndex);
5141 }
5142 else {
5143 // If argIndex exceeds the number of data arguments we
5144 // don't issue a warning because that is just a cascade of warnings (and
5145 // they may have intended '%%' anyway). We don't want to continue processing
5146 // the format string after this point, however, as we will like just get
5147 // gibberish when trying to match arguments.
5148 keepGoing = false;
5149 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005150
5151 StringRef Specifier(csStart, csLen);
5152
5153 // If the specifier in non-printable, it could be the first byte of a UTF-8
5154 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5155 // hex value.
5156 std::string CodePointStr;
5157 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005158 llvm::UTF32 CodePoint;
5159 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5160 const llvm::UTF8 *E =
5161 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5162 llvm::ConversionResult Result =
5163 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005164
Justin Lebar90910552016-09-30 00:38:45 +00005165 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005166 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005167 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005168 }
5169
5170 llvm::raw_string_ostream OS(CodePointStr);
5171 if (CodePoint < 256)
5172 OS << "\\x" << llvm::format("%02x", CodePoint);
5173 else if (CodePoint <= 0xFFFF)
5174 OS << "\\u" << llvm::format("%04x", CodePoint);
5175 else
5176 OS << "\\U" << llvm::format("%08x", CodePoint);
5177 OS.flush();
5178 Specifier = CodePointStr;
5179 }
5180
5181 EmitFormatDiagnostic(
5182 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5183 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5184
Ted Kremenekce815422010-07-19 21:25:57 +00005185 return keepGoing;
5186}
5187
Richard Trieu03cf7b72011-10-28 00:41:25 +00005188void
5189CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5190 const char *startSpec,
5191 unsigned specifierLen) {
5192 EmitFormatDiagnostic(
5193 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5194 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5195}
5196
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005197bool
5198CheckFormatHandler::CheckNumArgs(
5199 const analyze_format_string::FormatSpecifier &FS,
5200 const analyze_format_string::ConversionSpecifier &CS,
5201 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5202
5203 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005204 PartialDiagnostic PDiag = FS.usesPositionalArg()
5205 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5206 << (argIndex+1) << NumDataArgs)
5207 : S.PDiag(diag::warn_printf_insufficient_data_args);
5208 EmitFormatDiagnostic(
5209 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5210 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005211
5212 // Since more arguments than conversion tokens are given, by extension
5213 // all arguments are covered, so mark this as so.
5214 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005215 return false;
5216 }
5217 return true;
5218}
5219
Richard Trieu03cf7b72011-10-28 00:41:25 +00005220template<typename Range>
5221void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5222 SourceLocation Loc,
5223 bool IsStringLocation,
5224 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005225 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005226 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005227 Loc, IsStringLocation, StringRange, FixIt);
5228}
5229
5230/// \brief If the format string is not within the funcion call, emit a note
5231/// so that the function call and string are in diagnostic messages.
5232///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005233/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005234/// call and only one diagnostic message will be produced. Otherwise, an
5235/// extra note will be emitted pointing to location of the format string.
5236///
5237/// \param ArgumentExpr the expression that is passed as the format string
5238/// argument in the function call. Used for getting locations when two
5239/// diagnostics are emitted.
5240///
5241/// \param PDiag the callee should already have provided any strings for the
5242/// diagnostic message. This function only adds locations and fixits
5243/// to diagnostics.
5244///
5245/// \param Loc primary location for diagnostic. If two diagnostics are
5246/// required, one will be at Loc and a new SourceLocation will be created for
5247/// the other one.
5248///
5249/// \param IsStringLocation if true, Loc points to the format string should be
5250/// used for the note. Otherwise, Loc points to the argument list and will
5251/// be used with PDiag.
5252///
5253/// \param StringRange some or all of the string to highlight. This is
5254/// templated so it can accept either a CharSourceRange or a SourceRange.
5255///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005256/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005257template <typename Range>
5258void CheckFormatHandler::EmitFormatDiagnostic(
5259 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5260 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5261 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005262 if (InFunctionCall) {
5263 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5264 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005265 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00005266 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005267 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5268 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00005269
5270 const Sema::SemaDiagnosticBuilder &Note =
5271 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5272 diag::note_format_string_defined);
5273
5274 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005275 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005276 }
5277}
5278
Ted Kremenek02087932010-07-16 02:11:22 +00005279//===--- CHECK: Printf format string checking ------------------------------===//
5280
5281namespace {
5282class CheckPrintfHandler : public CheckFormatHandler {
5283public:
Stephen Hines648c3692016-09-16 01:07:04 +00005284 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005285 const Expr *origFormatExpr,
5286 const Sema::FormatStringType type, unsigned firstDataArg,
5287 unsigned numDataArgs, bool isObjC, const char *beg,
5288 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005289 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005290 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005291 llvm::SmallBitVector &CheckedVarArgs,
5292 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005293 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5294 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5295 inFunctionCall, CallType, CheckedVarArgs,
5296 UncoveredArg) {}
5297
5298 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5299
5300 /// Returns true if '%@' specifiers are allowed in the format string.
5301 bool allowsObjCArg() const {
5302 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5303 FSType == Sema::FST_OSTrace;
5304 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00005305
Ted Kremenek02087932010-07-16 02:11:22 +00005306 bool HandleInvalidPrintfConversionSpecifier(
5307 const analyze_printf::PrintfSpecifier &FS,
5308 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005309 unsigned specifierLen) override;
5310
Ted Kremenek02087932010-07-16 02:11:22 +00005311 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5312 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005313 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005314 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5315 const char *StartSpecifier,
5316 unsigned SpecifierLen,
5317 const Expr *E);
5318
Ted Kremenek02087932010-07-16 02:11:22 +00005319 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5320 const char *startSpecifier, unsigned specifierLen);
5321 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5322 const analyze_printf::OptionalAmount &Amt,
5323 unsigned type,
5324 const char *startSpecifier, unsigned specifierLen);
5325 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5326 const analyze_printf::OptionalFlag &flag,
5327 const char *startSpecifier, unsigned specifierLen);
5328 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5329 const analyze_printf::OptionalFlag &ignoredFlag,
5330 const analyze_printf::OptionalFlag &flag,
5331 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005332 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00005333 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00005334
5335 void HandleEmptyObjCModifierFlag(const char *startFlag,
5336 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005337
Ted Kremenek2b417712015-07-02 05:39:16 +00005338 void HandleInvalidObjCModifierFlag(const char *startFlag,
5339 unsigned flagLen) override;
5340
5341 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5342 const char *flagsEnd,
5343 const char *conversionPosition)
5344 override;
5345};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005346} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00005347
5348bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5349 const analyze_printf::PrintfSpecifier &FS,
5350 const char *startSpecifier,
5351 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005352 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005353 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005354
Ted Kremenekce815422010-07-19 21:25:57 +00005355 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5356 getLocationOfByte(CS.getStart()),
5357 startSpecifier, specifierLen,
5358 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00005359}
5360
Ted Kremenek02087932010-07-16 02:11:22 +00005361bool CheckPrintfHandler::HandleAmount(
5362 const analyze_format_string::OptionalAmount &Amt,
5363 unsigned k, const char *startSpecifier,
5364 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005365 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005366 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00005367 unsigned argIndex = Amt.getArgIndex();
5368 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005369 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5370 << k,
5371 getLocationOfByte(Amt.getStart()),
5372 /*IsStringLocation*/true,
5373 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005374 // Don't do any more checking. We will just emit
5375 // spurious errors.
5376 return false;
5377 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005378
Ted Kremenek5739de72010-01-29 01:06:55 +00005379 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00005380 // Although not in conformance with C99, we also allow the argument to be
5381 // an 'unsigned int' as that is a reasonably safe case. GCC also
5382 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00005383 CoveredArgs.set(argIndex);
5384 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005385 if (!Arg)
5386 return false;
5387
Ted Kremenek5739de72010-01-29 01:06:55 +00005388 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005389
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005390 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5391 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005392
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005393 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005394 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005395 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00005396 << T << Arg->getSourceRange(),
5397 getLocationOfByte(Amt.getStart()),
5398 /*IsStringLocation*/true,
5399 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005400 // Don't do any more checking. We will just emit
5401 // spurious errors.
5402 return false;
5403 }
5404 }
5405 }
5406 return true;
5407}
Ted Kremenek5739de72010-01-29 01:06:55 +00005408
Tom Careb49ec692010-06-17 19:00:27 +00005409void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00005410 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005411 const analyze_printf::OptionalAmount &Amt,
5412 unsigned type,
5413 const char *startSpecifier,
5414 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005415 const analyze_printf::PrintfConversionSpecifier &CS =
5416 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00005417
Richard Trieu03cf7b72011-10-28 00:41:25 +00005418 FixItHint fixit =
5419 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5420 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5421 Amt.getConstantLength()))
5422 : FixItHint();
5423
5424 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5425 << type << CS.toString(),
5426 getLocationOfByte(Amt.getStart()),
5427 /*IsStringLocation*/true,
5428 getSpecifierRange(startSpecifier, specifierLen),
5429 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00005430}
5431
Ted Kremenek02087932010-07-16 02:11:22 +00005432void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005433 const analyze_printf::OptionalFlag &flag,
5434 const char *startSpecifier,
5435 unsigned specifierLen) {
5436 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005437 const analyze_printf::PrintfConversionSpecifier &CS =
5438 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00005439 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5440 << flag.toString() << CS.toString(),
5441 getLocationOfByte(flag.getPosition()),
5442 /*IsStringLocation*/true,
5443 getSpecifierRange(startSpecifier, specifierLen),
5444 FixItHint::CreateRemoval(
5445 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005446}
5447
5448void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00005449 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005450 const analyze_printf::OptionalFlag &ignoredFlag,
5451 const analyze_printf::OptionalFlag &flag,
5452 const char *startSpecifier,
5453 unsigned specifierLen) {
5454 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005455 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5456 << ignoredFlag.toString() << flag.toString(),
5457 getLocationOfByte(ignoredFlag.getPosition()),
5458 /*IsStringLocation*/true,
5459 getSpecifierRange(startSpecifier, specifierLen),
5460 FixItHint::CreateRemoval(
5461 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005462}
5463
Ted Kremenek2b417712015-07-02 05:39:16 +00005464// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5465// bool IsStringLocation, Range StringRange,
5466// ArrayRef<FixItHint> Fixit = None);
5467
5468void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5469 unsigned flagLen) {
5470 // Warn about an empty flag.
5471 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5472 getLocationOfByte(startFlag),
5473 /*IsStringLocation*/true,
5474 getSpecifierRange(startFlag, flagLen));
5475}
5476
5477void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5478 unsigned flagLen) {
5479 // Warn about an invalid flag.
5480 auto Range = getSpecifierRange(startFlag, flagLen);
5481 StringRef flag(startFlag, flagLen);
5482 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5483 getLocationOfByte(startFlag),
5484 /*IsStringLocation*/true,
5485 Range, FixItHint::CreateRemoval(Range));
5486}
5487
5488void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5489 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5490 // Warn about using '[...]' without a '@' conversion.
5491 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5492 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5493 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5494 getLocationOfByte(conversionPosition),
5495 /*IsStringLocation*/true,
5496 Range, FixItHint::CreateRemoval(Range));
5497}
5498
Richard Smith55ce3522012-06-25 20:30:08 +00005499// Determines if the specified is a C++ class or struct containing
5500// a member with the specified name and kind (e.g. a CXXMethodDecl named
5501// "c_str()").
5502template<typename MemberKind>
5503static llvm::SmallPtrSet<MemberKind*, 1>
5504CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5505 const RecordType *RT = Ty->getAs<RecordType>();
5506 llvm::SmallPtrSet<MemberKind*, 1> Results;
5507
5508 if (!RT)
5509 return Results;
5510 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005511 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005512 return Results;
5513
Alp Tokerb6cc5922014-05-03 03:45:55 +00005514 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005515 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005516 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005517
5518 // We just need to include all members of the right kind turned up by the
5519 // filter, at this point.
5520 if (S.LookupQualifiedName(R, RT->getDecl()))
5521 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5522 NamedDecl *decl = (*I)->getUnderlyingDecl();
5523 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5524 Results.insert(FK);
5525 }
5526 return Results;
5527}
5528
Richard Smith2868a732014-02-28 01:36:39 +00005529/// Check if we could call '.c_str()' on an object.
5530///
5531/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5532/// allow the call, or if it would be ambiguous).
5533bool Sema::hasCStrMethod(const Expr *E) {
5534 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5535 MethodSet Results =
5536 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5537 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5538 MI != ME; ++MI)
5539 if ((*MI)->getMinRequiredArguments() == 0)
5540 return true;
5541 return false;
5542}
5543
Richard Smith55ce3522012-06-25 20:30:08 +00005544// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005545// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00005546// Returns true when a c_str() conversion method is found.
5547bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00005548 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00005549 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5550
5551 MethodSet Results =
5552 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5553
5554 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5555 MI != ME; ++MI) {
5556 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00005557 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00005558 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00005559 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00005560 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00005561 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5562 << "c_str()"
5563 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5564 return true;
5565 }
5566 }
5567
5568 return false;
5569}
5570
Ted Kremenekab278de2010-01-28 23:39:18 +00005571bool
Ted Kremenek02087932010-07-16 02:11:22 +00005572CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00005573 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00005574 const char *startSpecifier,
5575 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005576 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00005577 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005578 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00005579
Ted Kremenek6cd69422010-07-19 22:01:06 +00005580 if (FS.consumesDataArgument()) {
5581 if (atFirstArg) {
5582 atFirstArg = false;
5583 usesPositionalArgs = FS.usesPositionalArg();
5584 }
5585 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005586 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5587 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005588 return false;
5589 }
Ted Kremenek5739de72010-01-29 01:06:55 +00005590 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005591
Ted Kremenekd1668192010-02-27 01:41:03 +00005592 // First check if the field width, precision, and conversion specifier
5593 // have matching data arguments.
5594 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5595 startSpecifier, specifierLen)) {
5596 return false;
5597 }
5598
5599 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5600 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005601 return false;
5602 }
5603
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005604 if (!CS.consumesDataArgument()) {
5605 // FIXME: Technically specifying a precision or field width here
5606 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00005607 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005608 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005609
Ted Kremenek4a49d982010-02-26 19:18:41 +00005610 // Consume the argument.
5611 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00005612 if (argIndex < NumDataArgs) {
5613 // The check to see if the argIndex is valid will come later.
5614 // We set the bit here because we may exit early from this
5615 // function if we encounter some other error.
5616 CoveredArgs.set(argIndex);
5617 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00005618
Dimitry Andric6b5ed342015-02-19 22:32:33 +00005619 // FreeBSD kernel extensions.
5620 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5621 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5622 // We need at least two arguments.
5623 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5624 return false;
5625
5626 // Claim the second argument.
5627 CoveredArgs.set(argIndex + 1);
5628
5629 // Type check the first argument (int for %b, pointer for %D)
5630 const Expr *Ex = getDataArg(argIndex);
5631 const analyze_printf::ArgType &AT =
5632 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5633 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5634 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5635 EmitFormatDiagnostic(
5636 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5637 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5638 << false << Ex->getSourceRange(),
5639 Ex->getLocStart(), /*IsStringLocation*/false,
5640 getSpecifierRange(startSpecifier, specifierLen));
5641
5642 // Type check the second argument (char * for both %b and %D)
5643 Ex = getDataArg(argIndex + 1);
5644 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5645 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5646 EmitFormatDiagnostic(
5647 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5648 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5649 << false << Ex->getSourceRange(),
5650 Ex->getLocStart(), /*IsStringLocation*/false,
5651 getSpecifierRange(startSpecifier, specifierLen));
5652
5653 return true;
5654 }
5655
Ted Kremenek4a49d982010-02-26 19:18:41 +00005656 // Check for using an Objective-C specific conversion specifier
5657 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00005658 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00005659 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5660 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00005661 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005662
Mehdi Amini06d367c2016-10-24 20:39:34 +00005663 // %P can only be used with os_log.
5664 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
5665 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5666 specifierLen);
5667 }
5668
5669 // %n is not allowed with os_log.
5670 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
5671 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
5672 getLocationOfByte(CS.getStart()),
5673 /*IsStringLocation*/ false,
5674 getSpecifierRange(startSpecifier, specifierLen));
5675
5676 return true;
5677 }
5678
5679 // Only scalars are allowed for os_trace.
5680 if (FSType == Sema::FST_OSTrace &&
5681 (CS.getKind() == ConversionSpecifier::PArg ||
5682 CS.getKind() == ConversionSpecifier::sArg ||
5683 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
5684 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5685 specifierLen);
5686 }
5687
5688 // Check for use of public/private annotation outside of os_log().
5689 if (FSType != Sema::FST_OSLog) {
5690 if (FS.isPublic().isSet()) {
5691 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5692 << "public",
5693 getLocationOfByte(FS.isPublic().getPosition()),
5694 /*IsStringLocation*/ false,
5695 getSpecifierRange(startSpecifier, specifierLen));
5696 }
5697 if (FS.isPrivate().isSet()) {
5698 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5699 << "private",
5700 getLocationOfByte(FS.isPrivate().getPosition()),
5701 /*IsStringLocation*/ false,
5702 getSpecifierRange(startSpecifier, specifierLen));
5703 }
5704 }
5705
Tom Careb49ec692010-06-17 19:00:27 +00005706 // Check for invalid use of field width
5707 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00005708 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00005709 startSpecifier, specifierLen);
5710 }
5711
5712 // Check for invalid use of precision
5713 if (!FS.hasValidPrecision()) {
5714 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5715 startSpecifier, specifierLen);
5716 }
5717
Mehdi Amini06d367c2016-10-24 20:39:34 +00005718 // Precision is mandatory for %P specifier.
5719 if (CS.getKind() == ConversionSpecifier::PArg &&
5720 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
5721 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
5722 getLocationOfByte(startSpecifier),
5723 /*IsStringLocation*/ false,
5724 getSpecifierRange(startSpecifier, specifierLen));
5725 }
5726
Tom Careb49ec692010-06-17 19:00:27 +00005727 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00005728 if (!FS.hasValidThousandsGroupingPrefix())
5729 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005730 if (!FS.hasValidLeadingZeros())
5731 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5732 if (!FS.hasValidPlusPrefix())
5733 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00005734 if (!FS.hasValidSpacePrefix())
5735 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005736 if (!FS.hasValidAlternativeForm())
5737 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5738 if (!FS.hasValidLeftJustified())
5739 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5740
5741 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00005742 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5743 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5744 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005745 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5746 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5747 startSpecifier, specifierLen);
5748
5749 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005750 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005751 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5752 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005753 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005754 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005755 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005756 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5757 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00005758
Jordan Rose92303592012-09-08 04:00:03 +00005759 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5760 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5761
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005762 // The remaining checks depend on the data arguments.
5763 if (HasVAListArg)
5764 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005765
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005766 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005767 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005768
Jordan Rose58bbe422012-07-19 18:10:08 +00005769 const Expr *Arg = getDataArg(argIndex);
5770 if (!Arg)
5771 return true;
5772
5773 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00005774}
5775
Jordan Roseaee34382012-09-05 22:56:26 +00005776static bool requiresParensToAddCast(const Expr *E) {
5777 // FIXME: We should have a general way to reason about operator
5778 // precedence and whether parens are actually needed here.
5779 // Take care of a few common cases where they aren't.
5780 const Expr *Inside = E->IgnoreImpCasts();
5781 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5782 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5783
5784 switch (Inside->getStmtClass()) {
5785 case Stmt::ArraySubscriptExprClass:
5786 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005787 case Stmt::CharacterLiteralClass:
5788 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005789 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005790 case Stmt::FloatingLiteralClass:
5791 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005792 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005793 case Stmt::ObjCArrayLiteralClass:
5794 case Stmt::ObjCBoolLiteralExprClass:
5795 case Stmt::ObjCBoxedExprClass:
5796 case Stmt::ObjCDictionaryLiteralClass:
5797 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005798 case Stmt::ObjCIvarRefExprClass:
5799 case Stmt::ObjCMessageExprClass:
5800 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005801 case Stmt::ObjCStringLiteralClass:
5802 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005803 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005804 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005805 case Stmt::UnaryOperatorClass:
5806 return false;
5807 default:
5808 return true;
5809 }
5810}
5811
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005812static std::pair<QualType, StringRef>
5813shouldNotPrintDirectly(const ASTContext &Context,
5814 QualType IntendedTy,
5815 const Expr *E) {
5816 // Use a 'while' to peel off layers of typedefs.
5817 QualType TyTy = IntendedTy;
5818 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5819 StringRef Name = UserTy->getDecl()->getName();
5820 QualType CastTy = llvm::StringSwitch<QualType>(Name)
5821 .Case("NSInteger", Context.LongTy)
5822 .Case("NSUInteger", Context.UnsignedLongTy)
5823 .Case("SInt32", Context.IntTy)
5824 .Case("UInt32", Context.UnsignedIntTy)
5825 .Default(QualType());
5826
5827 if (!CastTy.isNull())
5828 return std::make_pair(CastTy, Name);
5829
5830 TyTy = UserTy->desugar();
5831 }
5832
5833 // Strip parens if necessary.
5834 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5835 return shouldNotPrintDirectly(Context,
5836 PE->getSubExpr()->getType(),
5837 PE->getSubExpr());
5838
5839 // If this is a conditional expression, then its result type is constructed
5840 // via usual arithmetic conversions and thus there might be no necessary
5841 // typedef sugar there. Recurse to operands to check for NSInteger &
5842 // Co. usage condition.
5843 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5844 QualType TrueTy, FalseTy;
5845 StringRef TrueName, FalseName;
5846
5847 std::tie(TrueTy, TrueName) =
5848 shouldNotPrintDirectly(Context,
5849 CO->getTrueExpr()->getType(),
5850 CO->getTrueExpr());
5851 std::tie(FalseTy, FalseName) =
5852 shouldNotPrintDirectly(Context,
5853 CO->getFalseExpr()->getType(),
5854 CO->getFalseExpr());
5855
5856 if (TrueTy == FalseTy)
5857 return std::make_pair(TrueTy, TrueName);
5858 else if (TrueTy.isNull())
5859 return std::make_pair(FalseTy, FalseName);
5860 else if (FalseTy.isNull())
5861 return std::make_pair(TrueTy, TrueName);
5862 }
5863
5864 return std::make_pair(QualType(), StringRef());
5865}
5866
Richard Smith55ce3522012-06-25 20:30:08 +00005867bool
5868CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5869 const char *StartSpecifier,
5870 unsigned SpecifierLen,
5871 const Expr *E) {
5872 using namespace analyze_format_string;
5873 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005874 // Now type check the data expression that matches the
5875 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00005876 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00005877 if (!AT.isValid())
5878 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00005879
Jordan Rose598ec092012-12-05 18:44:40 +00005880 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00005881 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5882 ExprTy = TET->getUnderlyingExpr()->getType();
5883 }
5884
Seth Cantrellb4802962015-03-04 03:12:10 +00005885 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5886
5887 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00005888 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005889 }
Jordan Rose98709982012-06-04 22:48:57 +00005890
Jordan Rose22b74712012-09-05 22:56:19 +00005891 // Look through argument promotions for our error message's reported type.
5892 // This includes the integral and floating promotions, but excludes array
5893 // and function pointer decay; seeing that an argument intended to be a
5894 // string has type 'char [6]' is probably more confusing than 'char *'.
5895 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5896 if (ICE->getCastKind() == CK_IntegralCast ||
5897 ICE->getCastKind() == CK_FloatingCast) {
5898 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00005899 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00005900
5901 // Check if we didn't match because of an implicit cast from a 'char'
5902 // or 'short' to an 'int'. This is done because printf is a varargs
5903 // function.
5904 if (ICE->getType() == S.Context.IntTy ||
5905 ICE->getType() == S.Context.UnsignedIntTy) {
5906 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00005907 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00005908 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00005909 }
Jordan Rose98709982012-06-04 22:48:57 +00005910 }
Jordan Rose598ec092012-12-05 18:44:40 +00005911 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5912 // Special case for 'a', which has type 'int' in C.
5913 // Note, however, that we do /not/ want to treat multibyte constants like
5914 // 'MooV' as characters! This form is deprecated but still exists.
5915 if (ExprTy == S.Context.IntTy)
5916 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5917 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00005918 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005919
Jordan Rosebc53ed12014-05-31 04:12:14 +00005920 // Look through enums to their underlying type.
5921 bool IsEnum = false;
5922 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5923 ExprTy = EnumTy->getDecl()->getIntegerType();
5924 IsEnum = true;
5925 }
5926
Jordan Rose0e5badd2012-12-05 18:44:49 +00005927 // %C in an Objective-C context prints a unichar, not a wchar_t.
5928 // If the argument is an integer of some kind, believe the %C and suggest
5929 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00005930 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005931 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00005932 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5933 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5934 !ExprTy->isCharType()) {
5935 // 'unichar' is defined as a typedef of unsigned short, but we should
5936 // prefer using the typedef if it is visible.
5937 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00005938
5939 // While we are here, check if the value is an IntegerLiteral that happens
5940 // to be within the valid range.
5941 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5942 const llvm::APInt &V = IL->getValue();
5943 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5944 return true;
5945 }
5946
Jordan Rose0e5badd2012-12-05 18:44:49 +00005947 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5948 Sema::LookupOrdinaryName);
5949 if (S.LookupName(Result, S.getCurScope())) {
5950 NamedDecl *ND = Result.getFoundDecl();
5951 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5952 if (TD->getUnderlyingType() == IntendedTy)
5953 IntendedTy = S.Context.getTypedefType(TD);
5954 }
5955 }
5956 }
5957
5958 // Special-case some of Darwin's platform-independence types by suggesting
5959 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005960 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00005961 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005962 QualType CastTy;
5963 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5964 if (!CastTy.isNull()) {
5965 IntendedTy = CastTy;
5966 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00005967 }
5968 }
5969
Jordan Rose22b74712012-09-05 22:56:19 +00005970 // We may be able to offer a FixItHint if it is a supported type.
5971 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005972 bool success =
5973 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005974
Jordan Rose22b74712012-09-05 22:56:19 +00005975 if (success) {
5976 // Get the fix string from the fixed format specifier
5977 SmallString<16> buf;
5978 llvm::raw_svector_ostream os(buf);
5979 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005980
Jordan Roseaee34382012-09-05 22:56:26 +00005981 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5982
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005983 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00005984 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5985 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5986 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5987 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00005988 // In this case, the specifier is wrong and should be changed to match
5989 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00005990 EmitFormatDiagnostic(S.PDiag(diag)
5991 << AT.getRepresentativeTypeName(S.Context)
5992 << IntendedTy << IsEnum << E->getSourceRange(),
5993 E->getLocStart(),
5994 /*IsStringLocation*/ false, SpecRange,
5995 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00005996 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00005997 // The canonical type for formatting this value is different from the
5998 // actual type of the expression. (This occurs, for example, with Darwin's
5999 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6000 // should be printed as 'long' for 64-bit compatibility.)
6001 // Rather than emitting a normal format/argument mismatch, we want to
6002 // add a cast to the recommended type (and correct the format string
6003 // if necessary).
6004 SmallString<16> CastBuf;
6005 llvm::raw_svector_ostream CastFix(CastBuf);
6006 CastFix << "(";
6007 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6008 CastFix << ")";
6009
6010 SmallVector<FixItHint,4> Hints;
6011 if (!AT.matchesType(S.Context, IntendedTy))
6012 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6013
6014 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6015 // If there's already a cast present, just replace it.
6016 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6017 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6018
6019 } else if (!requiresParensToAddCast(E)) {
6020 // If the expression has high enough precedence,
6021 // just write the C-style cast.
6022 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6023 CastFix.str()));
6024 } else {
6025 // Otherwise, add parens around the expression as well as the cast.
6026 CastFix << "(";
6027 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6028 CastFix.str()));
6029
Alp Tokerb6cc5922014-05-03 03:45:55 +00006030 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006031 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6032 }
6033
Jordan Rose0e5badd2012-12-05 18:44:49 +00006034 if (ShouldNotPrintDirectly) {
6035 // The expression has a type that should not be printed directly.
6036 // We extract the name from the typedef because we don't want to show
6037 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006038 StringRef Name;
6039 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6040 Name = TypedefTy->getDecl()->getName();
6041 else
6042 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006043 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006044 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006045 << E->getSourceRange(),
6046 E->getLocStart(), /*IsStringLocation=*/false,
6047 SpecRange, Hints);
6048 } else {
6049 // In this case, the expression could be printed using a different
6050 // specifier, but we've decided that the specifier is probably correct
6051 // and we should cast instead. Just use the normal warning message.
6052 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006053 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6054 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006055 << E->getSourceRange(),
6056 E->getLocStart(), /*IsStringLocation*/false,
6057 SpecRange, Hints);
6058 }
Jordan Roseaee34382012-09-05 22:56:26 +00006059 }
Jordan Rose22b74712012-09-05 22:56:19 +00006060 } else {
6061 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6062 SpecifierLen);
6063 // Since the warning for passing non-POD types to variadic functions
6064 // was deferred until now, we emit a warning for non-POD
6065 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006066 switch (S.isValidVarArgType(ExprTy)) {
6067 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006068 case Sema::VAK_ValidInCXX11: {
6069 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6070 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6071 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6072 }
Richard Smithd7293d72013-08-05 18:49:43 +00006073
Seth Cantrellb4802962015-03-04 03:12:10 +00006074 EmitFormatDiagnostic(
6075 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6076 << IsEnum << CSR << E->getSourceRange(),
6077 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6078 break;
6079 }
Richard Smithd7293d72013-08-05 18:49:43 +00006080 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006081 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006082 EmitFormatDiagnostic(
6083 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006084 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006085 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006086 << CallType
6087 << AT.getRepresentativeTypeName(S.Context)
6088 << CSR
6089 << E->getSourceRange(),
6090 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006091 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006092 break;
6093
6094 case Sema::VAK_Invalid:
6095 if (ExprTy->isObjCObjectType())
6096 EmitFormatDiagnostic(
6097 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6098 << S.getLangOpts().CPlusPlus11
6099 << ExprTy
6100 << CallType
6101 << AT.getRepresentativeTypeName(S.Context)
6102 << CSR
6103 << E->getSourceRange(),
6104 E->getLocStart(), /*IsStringLocation*/false, CSR);
6105 else
6106 // FIXME: If this is an initializer list, suggest removing the braces
6107 // or inserting a cast to the target type.
6108 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6109 << isa<InitListExpr>(E) << ExprTy << CallType
6110 << AT.getRepresentativeTypeName(S.Context)
6111 << E->getSourceRange();
6112 break;
6113 }
6114
6115 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6116 "format string specifier index out of range");
6117 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006118 }
6119
Ted Kremenekab278de2010-01-28 23:39:18 +00006120 return true;
6121}
6122
Ted Kremenek02087932010-07-16 02:11:22 +00006123//===--- CHECK: Scanf format string checking ------------------------------===//
6124
6125namespace {
6126class CheckScanfHandler : public CheckFormatHandler {
6127public:
Stephen Hines648c3692016-09-16 01:07:04 +00006128 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006129 const Expr *origFormatExpr, Sema::FormatStringType type,
6130 unsigned firstDataArg, unsigned numDataArgs,
6131 const char *beg, bool hasVAListArg,
6132 ArrayRef<const Expr *> Args, unsigned formatIdx,
6133 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006134 llvm::SmallBitVector &CheckedVarArgs,
6135 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006136 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6137 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6138 inFunctionCall, CallType, CheckedVarArgs,
6139 UncoveredArg) {}
6140
Ted Kremenek02087932010-07-16 02:11:22 +00006141 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6142 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006143 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006144
6145 bool HandleInvalidScanfConversionSpecifier(
6146 const analyze_scanf::ScanfSpecifier &FS,
6147 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006148 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006149
Craig Toppere14c0f82014-03-12 04:55:44 +00006150 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006151};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006152} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006153
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006154void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6155 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006156 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6157 getLocationOfByte(end), /*IsStringLocation*/true,
6158 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006159}
6160
Ted Kremenekce815422010-07-19 21:25:57 +00006161bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6162 const analyze_scanf::ScanfSpecifier &FS,
6163 const char *startSpecifier,
6164 unsigned specifierLen) {
6165
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006166 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006167 FS.getConversionSpecifier();
6168
6169 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6170 getLocationOfByte(CS.getStart()),
6171 startSpecifier, specifierLen,
6172 CS.getStart(), CS.getLength());
6173}
6174
Ted Kremenek02087932010-07-16 02:11:22 +00006175bool CheckScanfHandler::HandleScanfSpecifier(
6176 const analyze_scanf::ScanfSpecifier &FS,
6177 const char *startSpecifier,
6178 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006179 using namespace analyze_scanf;
6180 using namespace analyze_format_string;
6181
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006182 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006183
Ted Kremenek6cd69422010-07-19 22:01:06 +00006184 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6185 // be used to decide if we are using positional arguments consistently.
6186 if (FS.consumesDataArgument()) {
6187 if (atFirstArg) {
6188 atFirstArg = false;
6189 usesPositionalArgs = FS.usesPositionalArg();
6190 }
6191 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006192 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6193 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006194 return false;
6195 }
Ted Kremenek02087932010-07-16 02:11:22 +00006196 }
6197
6198 // Check if the field with is non-zero.
6199 const OptionalAmount &Amt = FS.getFieldWidth();
6200 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6201 if (Amt.getConstantAmount() == 0) {
6202 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6203 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006204 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6205 getLocationOfByte(Amt.getStart()),
6206 /*IsStringLocation*/true, R,
6207 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006208 }
6209 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006210
Ted Kremenek02087932010-07-16 02:11:22 +00006211 if (!FS.consumesDataArgument()) {
6212 // FIXME: Technically specifying a precision or field width here
6213 // makes no sense. Worth issuing a warning at some point.
6214 return true;
6215 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006216
Ted Kremenek02087932010-07-16 02:11:22 +00006217 // Consume the argument.
6218 unsigned argIndex = FS.getArgIndex();
6219 if (argIndex < NumDataArgs) {
6220 // The check to see if the argIndex is valid will come later.
6221 // We set the bit here because we may exit early from this
6222 // function if we encounter some other error.
6223 CoveredArgs.set(argIndex);
6224 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006225
Ted Kremenek4407ea42010-07-20 20:04:47 +00006226 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006227 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006228 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6229 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006230 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006231 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006232 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006233 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6234 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006235
Jordan Rose92303592012-09-08 04:00:03 +00006236 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6237 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6238
Ted Kremenek02087932010-07-16 02:11:22 +00006239 // The remaining checks depend on the data arguments.
6240 if (HasVAListArg)
6241 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006242
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006243 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006244 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006245
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006246 // Check that the argument type matches the format specifier.
6247 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006248 if (!Ex)
6249 return true;
6250
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006251 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006252
6253 if (!AT.isValid()) {
6254 return true;
6255 }
6256
Seth Cantrellb4802962015-03-04 03:12:10 +00006257 analyze_format_string::ArgType::MatchKind match =
6258 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006259 if (match == analyze_format_string::ArgType::Match) {
6260 return true;
6261 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006262
Seth Cantrell79340072015-03-04 05:58:08 +00006263 ScanfSpecifier fixedFS = FS;
6264 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6265 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006266
Seth Cantrell79340072015-03-04 05:58:08 +00006267 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6268 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6269 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6270 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006271
Seth Cantrell79340072015-03-04 05:58:08 +00006272 if (success) {
6273 // Get the fix string from the fixed format specifier.
6274 SmallString<128> buf;
6275 llvm::raw_svector_ostream os(buf);
6276 fixedFS.toString(os);
6277
6278 EmitFormatDiagnostic(
6279 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6280 << Ex->getType() << false << Ex->getSourceRange(),
6281 Ex->getLocStart(),
6282 /*IsStringLocation*/ false,
6283 getSpecifierRange(startSpecifier, specifierLen),
6284 FixItHint::CreateReplacement(
6285 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6286 } else {
6287 EmitFormatDiagnostic(S.PDiag(diag)
6288 << AT.getRepresentativeTypeName(S.Context)
6289 << Ex->getType() << false << Ex->getSourceRange(),
6290 Ex->getLocStart(),
6291 /*IsStringLocation*/ false,
6292 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006293 }
6294
Ted Kremenek02087932010-07-16 02:11:22 +00006295 return true;
6296}
6297
Stephen Hines648c3692016-09-16 01:07:04 +00006298static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006299 const Expr *OrigFormatExpr,
6300 ArrayRef<const Expr *> Args,
6301 bool HasVAListArg, unsigned format_idx,
6302 unsigned firstDataArg,
6303 Sema::FormatStringType Type,
6304 bool inFunctionCall,
6305 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006306 llvm::SmallBitVector &CheckedVarArgs,
6307 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00006308 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00006309 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006310 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006311 S, inFunctionCall, Args[format_idx],
6312 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006313 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006314 return;
6315 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006316
Ted Kremenekab278de2010-01-28 23:39:18 +00006317 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006318 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00006319 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006320 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006321 const ConstantArrayType *T =
6322 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006323 assert(T && "String literal not of constant array type!");
6324 size_t TypeSize = T->getSize().getZExtValue();
6325 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006326 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006327
6328 // Emit a warning if the string literal is truncated and does not contain an
6329 // embedded null character.
6330 if (TypeSize <= StrRef.size() &&
6331 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6332 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006333 S, inFunctionCall, Args[format_idx],
6334 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006335 FExpr->getLocStart(),
6336 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6337 return;
6338 }
6339
Ted Kremenekab278de2010-01-28 23:39:18 +00006340 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006341 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006342 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006343 S, inFunctionCall, Args[format_idx],
6344 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006345 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006346 return;
6347 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006348
6349 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00006350 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6351 Type == Sema::FST_OSTrace) {
6352 CheckPrintfHandler H(
6353 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6354 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6355 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6356 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006357
Hans Wennborg23926bd2011-12-15 10:25:47 +00006358 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006359 S.getLangOpts(),
6360 S.Context.getTargetInfo(),
6361 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006362 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006363 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00006364 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6365 numDataArgs, Str, HasVAListArg, Args, format_idx,
6366 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006367
Hans Wennborg23926bd2011-12-15 10:25:47 +00006368 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006369 S.getLangOpts(),
6370 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006371 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006372 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006373}
6374
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006375bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6376 // Str - The format string. NOTE: this is NOT null-terminated!
6377 StringRef StrRef = FExpr->getString();
6378 const char *Str = StrRef.data();
6379 // Account for cases where the string literal is truncated in a declaration.
6380 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6381 assert(T && "String literal not of constant array type!");
6382 size_t TypeSize = T->getSize().getZExtValue();
6383 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6384 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6385 getLangOpts(),
6386 Context.getTargetInfo());
6387}
6388
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006389//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6390
6391// Returns the related absolute value function that is larger, of 0 if one
6392// does not exist.
6393static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6394 switch (AbsFunction) {
6395 default:
6396 return 0;
6397
6398 case Builtin::BI__builtin_abs:
6399 return Builtin::BI__builtin_labs;
6400 case Builtin::BI__builtin_labs:
6401 return Builtin::BI__builtin_llabs;
6402 case Builtin::BI__builtin_llabs:
6403 return 0;
6404
6405 case Builtin::BI__builtin_fabsf:
6406 return Builtin::BI__builtin_fabs;
6407 case Builtin::BI__builtin_fabs:
6408 return Builtin::BI__builtin_fabsl;
6409 case Builtin::BI__builtin_fabsl:
6410 return 0;
6411
6412 case Builtin::BI__builtin_cabsf:
6413 return Builtin::BI__builtin_cabs;
6414 case Builtin::BI__builtin_cabs:
6415 return Builtin::BI__builtin_cabsl;
6416 case Builtin::BI__builtin_cabsl:
6417 return 0;
6418
6419 case Builtin::BIabs:
6420 return Builtin::BIlabs;
6421 case Builtin::BIlabs:
6422 return Builtin::BIllabs;
6423 case Builtin::BIllabs:
6424 return 0;
6425
6426 case Builtin::BIfabsf:
6427 return Builtin::BIfabs;
6428 case Builtin::BIfabs:
6429 return Builtin::BIfabsl;
6430 case Builtin::BIfabsl:
6431 return 0;
6432
6433 case Builtin::BIcabsf:
6434 return Builtin::BIcabs;
6435 case Builtin::BIcabs:
6436 return Builtin::BIcabsl;
6437 case Builtin::BIcabsl:
6438 return 0;
6439 }
6440}
6441
6442// Returns the argument type of the absolute value function.
6443static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6444 unsigned AbsType) {
6445 if (AbsType == 0)
6446 return QualType();
6447
6448 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6449 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6450 if (Error != ASTContext::GE_None)
6451 return QualType();
6452
6453 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6454 if (!FT)
6455 return QualType();
6456
6457 if (FT->getNumParams() != 1)
6458 return QualType();
6459
6460 return FT->getParamType(0);
6461}
6462
6463// Returns the best absolute value function, or zero, based on type and
6464// current absolute value function.
6465static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6466 unsigned AbsFunctionKind) {
6467 unsigned BestKind = 0;
6468 uint64_t ArgSize = Context.getTypeSize(ArgType);
6469 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6470 Kind = getLargerAbsoluteValueFunction(Kind)) {
6471 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6472 if (Context.getTypeSize(ParamType) >= ArgSize) {
6473 if (BestKind == 0)
6474 BestKind = Kind;
6475 else if (Context.hasSameType(ParamType, ArgType)) {
6476 BestKind = Kind;
6477 break;
6478 }
6479 }
6480 }
6481 return BestKind;
6482}
6483
6484enum AbsoluteValueKind {
6485 AVK_Integer,
6486 AVK_Floating,
6487 AVK_Complex
6488};
6489
6490static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6491 if (T->isIntegralOrEnumerationType())
6492 return AVK_Integer;
6493 if (T->isRealFloatingType())
6494 return AVK_Floating;
6495 if (T->isAnyComplexType())
6496 return AVK_Complex;
6497
6498 llvm_unreachable("Type not integer, floating, or complex");
6499}
6500
6501// Changes the absolute value function to a different type. Preserves whether
6502// the function is a builtin.
6503static unsigned changeAbsFunction(unsigned AbsKind,
6504 AbsoluteValueKind ValueKind) {
6505 switch (ValueKind) {
6506 case AVK_Integer:
6507 switch (AbsKind) {
6508 default:
6509 return 0;
6510 case Builtin::BI__builtin_fabsf:
6511 case Builtin::BI__builtin_fabs:
6512 case Builtin::BI__builtin_fabsl:
6513 case Builtin::BI__builtin_cabsf:
6514 case Builtin::BI__builtin_cabs:
6515 case Builtin::BI__builtin_cabsl:
6516 return Builtin::BI__builtin_abs;
6517 case Builtin::BIfabsf:
6518 case Builtin::BIfabs:
6519 case Builtin::BIfabsl:
6520 case Builtin::BIcabsf:
6521 case Builtin::BIcabs:
6522 case Builtin::BIcabsl:
6523 return Builtin::BIabs;
6524 }
6525 case AVK_Floating:
6526 switch (AbsKind) {
6527 default:
6528 return 0;
6529 case Builtin::BI__builtin_abs:
6530 case Builtin::BI__builtin_labs:
6531 case Builtin::BI__builtin_llabs:
6532 case Builtin::BI__builtin_cabsf:
6533 case Builtin::BI__builtin_cabs:
6534 case Builtin::BI__builtin_cabsl:
6535 return Builtin::BI__builtin_fabsf;
6536 case Builtin::BIabs:
6537 case Builtin::BIlabs:
6538 case Builtin::BIllabs:
6539 case Builtin::BIcabsf:
6540 case Builtin::BIcabs:
6541 case Builtin::BIcabsl:
6542 return Builtin::BIfabsf;
6543 }
6544 case AVK_Complex:
6545 switch (AbsKind) {
6546 default:
6547 return 0;
6548 case Builtin::BI__builtin_abs:
6549 case Builtin::BI__builtin_labs:
6550 case Builtin::BI__builtin_llabs:
6551 case Builtin::BI__builtin_fabsf:
6552 case Builtin::BI__builtin_fabs:
6553 case Builtin::BI__builtin_fabsl:
6554 return Builtin::BI__builtin_cabsf;
6555 case Builtin::BIabs:
6556 case Builtin::BIlabs:
6557 case Builtin::BIllabs:
6558 case Builtin::BIfabsf:
6559 case Builtin::BIfabs:
6560 case Builtin::BIfabsl:
6561 return Builtin::BIcabsf;
6562 }
6563 }
6564 llvm_unreachable("Unable to convert function");
6565}
6566
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006567static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006568 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6569 if (!FnInfo)
6570 return 0;
6571
6572 switch (FDecl->getBuiltinID()) {
6573 default:
6574 return 0;
6575 case Builtin::BI__builtin_abs:
6576 case Builtin::BI__builtin_fabs:
6577 case Builtin::BI__builtin_fabsf:
6578 case Builtin::BI__builtin_fabsl:
6579 case Builtin::BI__builtin_labs:
6580 case Builtin::BI__builtin_llabs:
6581 case Builtin::BI__builtin_cabs:
6582 case Builtin::BI__builtin_cabsf:
6583 case Builtin::BI__builtin_cabsl:
6584 case Builtin::BIabs:
6585 case Builtin::BIlabs:
6586 case Builtin::BIllabs:
6587 case Builtin::BIfabs:
6588 case Builtin::BIfabsf:
6589 case Builtin::BIfabsl:
6590 case Builtin::BIcabs:
6591 case Builtin::BIcabsf:
6592 case Builtin::BIcabsl:
6593 return FDecl->getBuiltinID();
6594 }
6595 llvm_unreachable("Unknown Builtin type");
6596}
6597
6598// If the replacement is valid, emit a note with replacement function.
6599// Additionally, suggest including the proper header if not already included.
6600static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00006601 unsigned AbsKind, QualType ArgType) {
6602 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006603 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00006604 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006605 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6606 FunctionName = "std::abs";
6607 if (ArgType->isIntegralOrEnumerationType()) {
6608 HeaderName = "cstdlib";
6609 } else if (ArgType->isRealFloatingType()) {
6610 HeaderName = "cmath";
6611 } else {
6612 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006613 }
Richard Trieubeffb832014-04-15 23:47:53 +00006614
6615 // Lookup all std::abs
6616 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00006617 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00006618 R.suppressDiagnostics();
6619 S.LookupQualifiedName(R, Std);
6620
6621 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006622 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006623 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6624 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6625 } else {
6626 FDecl = dyn_cast<FunctionDecl>(I);
6627 }
6628 if (!FDecl)
6629 continue;
6630
6631 // Found std::abs(), check that they are the right ones.
6632 if (FDecl->getNumParams() != 1)
6633 continue;
6634
6635 // Check that the parameter type can handle the argument.
6636 QualType ParamType = FDecl->getParamDecl(0)->getType();
6637 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6638 S.Context.getTypeSize(ArgType) <=
6639 S.Context.getTypeSize(ParamType)) {
6640 // Found a function, don't need the header hint.
6641 EmitHeaderHint = false;
6642 break;
6643 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006644 }
Richard Trieubeffb832014-04-15 23:47:53 +00006645 }
6646 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00006647 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00006648 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6649
6650 if (HeaderName) {
6651 DeclarationName DN(&S.Context.Idents.get(FunctionName));
6652 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6653 R.suppressDiagnostics();
6654 S.LookupName(R, S.getCurScope());
6655
6656 if (R.isSingleResult()) {
6657 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6658 if (FD && FD->getBuiltinID() == AbsKind) {
6659 EmitHeaderHint = false;
6660 } else {
6661 return;
6662 }
6663 } else if (!R.empty()) {
6664 return;
6665 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006666 }
6667 }
6668
6669 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00006670 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006671
Richard Trieubeffb832014-04-15 23:47:53 +00006672 if (!HeaderName)
6673 return;
6674
6675 if (!EmitHeaderHint)
6676 return;
6677
Alp Toker5d96e0a2014-07-11 20:53:51 +00006678 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6679 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00006680}
6681
Richard Trieua7f30b12016-12-06 01:42:28 +00006682template <std::size_t StrLen>
6683static bool IsStdFunction(const FunctionDecl *FDecl,
6684 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00006685 if (!FDecl)
6686 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00006687 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00006688 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00006689 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00006690 return false;
6691
6692 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006693}
6694
6695// Warn when using the wrong abs() function.
6696void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00006697 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006698 if (Call->getNumArgs() != 1)
6699 return;
6700
6701 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00006702 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00006703 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006704 return;
6705
6706 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6707 QualType ParamType = Call->getArg(0)->getType();
6708
Alp Toker5d96e0a2014-07-11 20:53:51 +00006709 // Unsigned types cannot be negative. Suggest removing the absolute value
6710 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006711 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00006712 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00006713 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006714 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6715 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00006716 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006717 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6718 return;
6719 }
6720
David Majnemer7f77eb92015-11-15 03:04:34 +00006721 // Taking the absolute value of a pointer is very suspicious, they probably
6722 // wanted to index into an array, dereference a pointer, call a function, etc.
6723 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6724 unsigned DiagType = 0;
6725 if (ArgType->isFunctionType())
6726 DiagType = 1;
6727 else if (ArgType->isArrayType())
6728 DiagType = 2;
6729
6730 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6731 return;
6732 }
6733
Richard Trieubeffb832014-04-15 23:47:53 +00006734 // std::abs has overloads which prevent most of the absolute value problems
6735 // from occurring.
6736 if (IsStdAbs)
6737 return;
6738
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006739 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6740 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6741
6742 // The argument and parameter are the same kind. Check if they are the right
6743 // size.
6744 if (ArgValueKind == ParamValueKind) {
6745 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6746 return;
6747
6748 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6749 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6750 << FDecl << ArgType << ParamType;
6751
6752 if (NewAbsKind == 0)
6753 return;
6754
6755 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006756 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006757 return;
6758 }
6759
6760 // ArgValueKind != ParamValueKind
6761 // The wrong type of absolute value function was used. Attempt to find the
6762 // proper one.
6763 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6764 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6765 if (NewAbsKind == 0)
6766 return;
6767
6768 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6769 << FDecl << ParamValueKind << ArgValueKind;
6770
6771 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006772 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006773}
6774
Richard Trieu67c00712016-12-05 23:41:46 +00006775//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00006776void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
6777 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00006778 if (!Call || !FDecl) return;
6779
6780 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00006781 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00006782 if (Call->getExprLoc().isMacroID()) return;
6783
6784 // Only care about the one template argument, two function parameter std::max
6785 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00006786 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00006787 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
6788 if (!ArgList) return;
6789 if (ArgList->size() != 1) return;
6790
6791 // Check that template type argument is unsigned integer.
6792 const auto& TA = ArgList->get(0);
6793 if (TA.getKind() != TemplateArgument::Type) return;
6794 QualType ArgType = TA.getAsType();
6795 if (!ArgType->isUnsignedIntegerType()) return;
6796
6797 // See if either argument is a literal zero.
6798 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
6799 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
6800 if (!MTE) return false;
6801 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
6802 if (!Num) return false;
6803 if (Num->getValue() != 0) return false;
6804 return true;
6805 };
6806
6807 const Expr *FirstArg = Call->getArg(0);
6808 const Expr *SecondArg = Call->getArg(1);
6809 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
6810 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
6811
6812 // Only warn when exactly one argument is zero.
6813 if (IsFirstArgZero == IsSecondArgZero) return;
6814
6815 SourceRange FirstRange = FirstArg->getSourceRange();
6816 SourceRange SecondRange = SecondArg->getSourceRange();
6817
6818 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
6819
6820 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
6821 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
6822
6823 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
6824 SourceRange RemovalRange;
6825 if (IsFirstArgZero) {
6826 RemovalRange = SourceRange(FirstRange.getBegin(),
6827 SecondRange.getBegin().getLocWithOffset(-1));
6828 } else {
6829 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
6830 SecondRange.getEnd());
6831 }
6832
6833 Diag(Call->getExprLoc(), diag::note_remove_max_call)
6834 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
6835 << FixItHint::CreateRemoval(RemovalRange);
6836}
6837
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006838//===--- CHECK: Standard memory functions ---------------------------------===//
6839
Nico Weber0e6daef2013-12-26 23:38:39 +00006840/// \brief Takes the expression passed to the size_t parameter of functions
6841/// such as memcmp, strncat, etc and warns if it's a comparison.
6842///
6843/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6844static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6845 IdentifierInfo *FnName,
6846 SourceLocation FnLoc,
6847 SourceLocation RParenLoc) {
6848 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6849 if (!Size)
6850 return false;
6851
6852 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6853 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6854 return false;
6855
Nico Weber0e6daef2013-12-26 23:38:39 +00006856 SourceRange SizeRange = Size->getSourceRange();
6857 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6858 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00006859 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006860 << FnName << FixItHint::CreateInsertion(
6861 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00006862 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00006863 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00006864 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00006865 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6866 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00006867
6868 return true;
6869}
6870
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006871/// \brief Determine whether the given type is or contains a dynamic class type
6872/// (e.g., whether it has a vtable).
6873static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6874 bool &IsContained) {
6875 // Look through array types while ignoring qualifiers.
6876 const Type *Ty = T->getBaseElementTypeUnsafe();
6877 IsContained = false;
6878
6879 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6880 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00006881 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006882 return nullptr;
6883
6884 if (RD->isDynamicClass())
6885 return RD;
6886
6887 // Check all the fields. If any bases were dynamic, the class is dynamic.
6888 // It's impossible for a class to transitively contain itself by value, so
6889 // infinite recursion is impossible.
6890 for (auto *FD : RD->fields()) {
6891 bool SubContained;
6892 if (const CXXRecordDecl *ContainedRD =
6893 getContainedDynamicClass(FD->getType(), SubContained)) {
6894 IsContained = true;
6895 return ContainedRD;
6896 }
6897 }
6898
6899 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00006900}
6901
Chandler Carruth889ed862011-06-21 23:04:20 +00006902/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006903/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00006904static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00006905 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006906 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6907 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6908 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006909
Craig Topperc3ec1492014-05-26 06:22:03 +00006910 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006911}
6912
Chandler Carruth889ed862011-06-21 23:04:20 +00006913/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00006914static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006915 if (const UnaryExprOrTypeTraitExpr *SizeOf =
6916 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6917 if (SizeOf->getKind() == clang::UETT_SizeOf)
6918 return SizeOf->getTypeOfArgument();
6919
6920 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00006921}
6922
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006923/// \brief Check for dangerous or invalid arguments to memset().
6924///
Chandler Carruthac687262011-06-03 06:23:57 +00006925/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006926/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6927/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006928///
6929/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006930void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00006931 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006932 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00006933 assert(BId != 0);
6934
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006935 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00006936 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006937 unsigned ExpectedNumArgs =
6938 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00006939 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006940 return;
6941
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006942 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00006943 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006944 unsigned LenArg =
6945 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00006946 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006947
Nico Weber0e6daef2013-12-26 23:38:39 +00006948 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6949 Call->getLocStart(), Call->getRParenLoc()))
6950 return;
6951
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006952 // We have special checking when the length is a sizeof expression.
6953 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6954 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6955 llvm::FoldingSetNodeID SizeOfArgID;
6956
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00006957 // Although widely used, 'bzero' is not a standard function. Be more strict
6958 // with the argument types before allowing diagnostics and only allow the
6959 // form bzero(ptr, sizeof(...)).
6960 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6961 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
6962 return;
6963
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006964 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6965 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006966 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006967
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006968 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00006969 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006970 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00006971 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00006972
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006973 // Never warn about void type pointers. This can be used to suppress
6974 // false positives.
6975 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006976 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006977
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006978 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6979 // actually comparing the expressions for equality. Because computing the
6980 // expression IDs can be expensive, we only do this if the diagnostic is
6981 // enabled.
6982 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006983 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6984 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006985 // We only compute IDs for expressions if the warning is enabled, and
6986 // cache the sizeof arg's ID.
6987 if (SizeOfArgID == llvm::FoldingSetNodeID())
6988 SizeOfArg->Profile(SizeOfArgID, Context, true);
6989 llvm::FoldingSetNodeID DestID;
6990 Dest->Profile(DestID, Context, true);
6991 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00006992 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6993 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006994 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00006995 StringRef ReadableName = FnName->getName();
6996
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006997 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00006998 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006999 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007000 if (!PointeeTy->isIncompleteType() &&
7001 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007002 ActionIdx = 2; // If the pointee's size is sizeof(char),
7003 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007004
7005 // If the function is defined as a builtin macro, do not show macro
7006 // expansion.
7007 SourceLocation SL = SizeOfArg->getExprLoc();
7008 SourceRange DSR = Dest->getSourceRange();
7009 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007010 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007011
7012 if (SM.isMacroArgExpansion(SL)) {
7013 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7014 SL = SM.getSpellingLoc(SL);
7015 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7016 SM.getSpellingLoc(DSR.getEnd()));
7017 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7018 SM.getSpellingLoc(SSR.getEnd()));
7019 }
7020
Anna Zaksd08d9152012-05-30 23:14:52 +00007021 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007022 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007023 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007024 << PointeeTy
7025 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007026 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007027 << SSR);
7028 DiagRuntimeBehavior(SL, SizeOfArg,
7029 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7030 << ActionIdx
7031 << SSR);
7032
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007033 break;
7034 }
7035 }
7036
7037 // Also check for cases where the sizeof argument is the exact same
7038 // type as the memory argument, and where it points to a user-defined
7039 // record type.
7040 if (SizeOfArgTy != QualType()) {
7041 if (PointeeTy->isRecordType() &&
7042 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7043 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7044 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7045 << FnName << SizeOfArgTy << ArgIdx
7046 << PointeeTy << Dest->getSourceRange()
7047 << LenExpr->getSourceRange());
7048 break;
7049 }
Nico Weberc5e73862011-06-14 16:14:58 +00007050 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00007051 } else if (DestTy->isArrayType()) {
7052 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00007053 }
Nico Weberc5e73862011-06-14 16:14:58 +00007054
Nico Weberc44b35e2015-03-21 17:37:46 +00007055 if (PointeeTy == QualType())
7056 continue;
Anna Zaks22122702012-01-17 00:37:07 +00007057
Nico Weberc44b35e2015-03-21 17:37:46 +00007058 // Always complain about dynamic classes.
7059 bool IsContained;
7060 if (const CXXRecordDecl *ContainedRD =
7061 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00007062
Nico Weberc44b35e2015-03-21 17:37:46 +00007063 unsigned OperationType = 0;
7064 // "overwritten" if we're warning about the destination for any call
7065 // but memcmp; otherwise a verb appropriate to the call.
7066 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7067 if (BId == Builtin::BImemcpy)
7068 OperationType = 1;
7069 else if(BId == Builtin::BImemmove)
7070 OperationType = 2;
7071 else if (BId == Builtin::BImemcmp)
7072 OperationType = 3;
7073 }
7074
John McCall31168b02011-06-15 23:02:42 +00007075 DiagRuntimeBehavior(
7076 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007077 PDiag(diag::warn_dyn_class_memaccess)
7078 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7079 << FnName << IsContained << ContainedRD << OperationType
7080 << Call->getCallee()->getSourceRange());
7081 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7082 BId != Builtin::BImemset)
7083 DiagRuntimeBehavior(
7084 Dest->getExprLoc(), Dest,
7085 PDiag(diag::warn_arc_object_memaccess)
7086 << ArgIdx << FnName << PointeeTy
7087 << Call->getCallee()->getSourceRange());
7088 else
7089 continue;
7090
7091 DiagRuntimeBehavior(
7092 Dest->getExprLoc(), Dest,
7093 PDiag(diag::note_bad_memaccess_silence)
7094 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7095 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007096 }
7097}
7098
Ted Kremenek6865f772011-08-18 20:55:45 +00007099// A little helper routine: ignore addition and subtraction of integer literals.
7100// This intentionally does not ignore all integer constant expressions because
7101// we don't want to remove sizeof().
7102static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7103 Ex = Ex->IgnoreParenCasts();
7104
7105 for (;;) {
7106 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7107 if (!BO || !BO->isAdditiveOp())
7108 break;
7109
7110 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7111 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7112
7113 if (isa<IntegerLiteral>(RHS))
7114 Ex = LHS;
7115 else if (isa<IntegerLiteral>(LHS))
7116 Ex = RHS;
7117 else
7118 break;
7119 }
7120
7121 return Ex;
7122}
7123
Anna Zaks13b08572012-08-08 21:42:23 +00007124static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7125 ASTContext &Context) {
7126 // Only handle constant-sized or VLAs, but not flexible members.
7127 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7128 // Only issue the FIXIT for arrays of size > 1.
7129 if (CAT->getSize().getSExtValue() <= 1)
7130 return false;
7131 } else if (!Ty->isVariableArrayType()) {
7132 return false;
7133 }
7134 return true;
7135}
7136
Ted Kremenek6865f772011-08-18 20:55:45 +00007137// Warn if the user has made the 'size' argument to strlcpy or strlcat
7138// be the size of the source, instead of the destination.
7139void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7140 IdentifierInfo *FnName) {
7141
7142 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007143 unsigned NumArgs = Call->getNumArgs();
7144 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007145 return;
7146
7147 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7148 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007149 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007150
7151 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7152 Call->getLocStart(), Call->getRParenLoc()))
7153 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00007154
7155 // Look for 'strlcpy(dst, x, sizeof(x))'
7156 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7157 CompareWithSrc = Ex;
7158 else {
7159 // Look for 'strlcpy(dst, x, strlen(x))'
7160 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00007161 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7162 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00007163 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7164 }
7165 }
7166
7167 if (!CompareWithSrc)
7168 return;
7169
7170 // Determine if the argument to sizeof/strlen is equal to the source
7171 // argument. In principle there's all kinds of things you could do
7172 // here, for instance creating an == expression and evaluating it with
7173 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7174 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7175 if (!SrcArgDRE)
7176 return;
7177
7178 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7179 if (!CompareWithSrcDRE ||
7180 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7181 return;
7182
7183 const Expr *OriginalSizeArg = Call->getArg(2);
7184 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7185 << OriginalSizeArg->getSourceRange() << FnName;
7186
7187 // Output a FIXIT hint if the destination is an array (rather than a
7188 // pointer to an array). This could be enhanced to handle some
7189 // pointers if we know the actual size, like if DstArg is 'array+2'
7190 // we could say 'sizeof(array)-2'.
7191 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00007192 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00007193 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007194
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007195 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007196 llvm::raw_svector_ostream OS(sizeString);
7197 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007198 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00007199 OS << ")";
7200
7201 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7202 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7203 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00007204}
7205
Anna Zaks314cd092012-02-01 19:08:57 +00007206/// Check if two expressions refer to the same declaration.
7207static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7208 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7209 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7210 return D1->getDecl() == D2->getDecl();
7211 return false;
7212}
7213
7214static const Expr *getStrlenExprArg(const Expr *E) {
7215 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7216 const FunctionDecl *FD = CE->getDirectCallee();
7217 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00007218 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007219 return CE->getArg(0)->IgnoreParenCasts();
7220 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007221 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007222}
7223
7224// Warn on anti-patterns as the 'size' argument to strncat.
7225// The correct size argument should look like following:
7226// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7227void Sema::CheckStrncatArguments(const CallExpr *CE,
7228 IdentifierInfo *FnName) {
7229 // Don't crash if the user has the wrong number of arguments.
7230 if (CE->getNumArgs() < 3)
7231 return;
7232 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7233 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7234 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7235
Nico Weber0e6daef2013-12-26 23:38:39 +00007236 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7237 CE->getRParenLoc()))
7238 return;
7239
Anna Zaks314cd092012-02-01 19:08:57 +00007240 // Identify common expressions, which are wrongly used as the size argument
7241 // to strncat and may lead to buffer overflows.
7242 unsigned PatternType = 0;
7243 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7244 // - sizeof(dst)
7245 if (referToTheSameDecl(SizeOfArg, DstArg))
7246 PatternType = 1;
7247 // - sizeof(src)
7248 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7249 PatternType = 2;
7250 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7251 if (BE->getOpcode() == BO_Sub) {
7252 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7253 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7254 // - sizeof(dst) - strlen(dst)
7255 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7256 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7257 PatternType = 1;
7258 // - sizeof(src) - (anything)
7259 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7260 PatternType = 2;
7261 }
7262 }
7263
7264 if (PatternType == 0)
7265 return;
7266
Anna Zaks5069aa32012-02-03 01:27:37 +00007267 // Generate the diagnostic.
7268 SourceLocation SL = LenArg->getLocStart();
7269 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007270 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00007271
7272 // If the function is defined as a builtin macro, do not show macro expansion.
7273 if (SM.isMacroArgExpansion(SL)) {
7274 SL = SM.getSpellingLoc(SL);
7275 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7276 SM.getSpellingLoc(SR.getEnd()));
7277 }
7278
Anna Zaks13b08572012-08-08 21:42:23 +00007279 // Check if the destination is an array (rather than a pointer to an array).
7280 QualType DstTy = DstArg->getType();
7281 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7282 Context);
7283 if (!isKnownSizeArray) {
7284 if (PatternType == 1)
7285 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7286 else
7287 Diag(SL, diag::warn_strncat_src_size) << SR;
7288 return;
7289 }
7290
Anna Zaks314cd092012-02-01 19:08:57 +00007291 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00007292 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007293 else
Anna Zaks5069aa32012-02-03 01:27:37 +00007294 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007295
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007296 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00007297 llvm::raw_svector_ostream OS(sizeString);
7298 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007299 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007300 OS << ") - ";
7301 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007302 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007303 OS << ") - 1";
7304
Anna Zaks5069aa32012-02-03 01:27:37 +00007305 Diag(SL, diag::note_strncat_wrong_size)
7306 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00007307}
7308
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007309//===--- CHECK: Return Address of Stack Variable --------------------------===//
7310
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007311static const Expr *EvalVal(const Expr *E,
7312 SmallVectorImpl<const DeclRefExpr *> &refVars,
7313 const Decl *ParentDecl);
7314static const Expr *EvalAddr(const Expr *E,
7315 SmallVectorImpl<const DeclRefExpr *> &refVars,
7316 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007317
7318/// CheckReturnStackAddr - Check if a return statement returns the address
7319/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007320static void
7321CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7322 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00007323
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007324 const Expr *stackE = nullptr;
7325 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007326
7327 // Perform checking for returned stack addresses, local blocks,
7328 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00007329 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007330 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007331 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00007332 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007333 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007334 }
7335
Craig Topperc3ec1492014-05-26 06:22:03 +00007336 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007337 return; // Nothing suspicious was found.
7338
Richard Trieu81b6c562016-08-05 23:24:47 +00007339 // Parameters are initalized in the calling scope, so taking the address
7340 // of a parameter reference doesn't need a warning.
7341 for (auto *DRE : refVars)
7342 if (isa<ParmVarDecl>(DRE->getDecl()))
7343 return;
7344
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007345 SourceLocation diagLoc;
7346 SourceRange diagRange;
7347 if (refVars.empty()) {
7348 diagLoc = stackE->getLocStart();
7349 diagRange = stackE->getSourceRange();
7350 } else {
7351 // We followed through a reference variable. 'stackE' contains the
7352 // problematic expression but we will warn at the return statement pointing
7353 // at the reference variable. We will later display the "trail" of
7354 // reference variables using notes.
7355 diagLoc = refVars[0]->getLocStart();
7356 diagRange = refVars[0]->getSourceRange();
7357 }
7358
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007359 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7360 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00007361 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007362 << DR->getDecl()->getDeclName() << diagRange;
7363 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007364 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007365 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007366 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007367 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00007368 // If there is an LValue->RValue conversion, then the value of the
7369 // reference type is used, not the reference.
7370 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7371 if (ICE->getCastKind() == CK_LValueToRValue) {
7372 return;
7373 }
7374 }
Craig Topperda7b27f2015-11-17 05:40:09 +00007375 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7376 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007377 }
7378
7379 // Display the "trail" of reference variables that we followed until we
7380 // found the problematic expression using notes.
7381 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007382 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007383 // If this var binds to another reference var, show the range of the next
7384 // var, otherwise the var binds to the problematic expression, in which case
7385 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007386 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7387 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007388 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7389 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007390 }
7391}
7392
7393/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7394/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007395/// to a location on the stack, a local block, an address of a label, or a
7396/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007397/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007398/// encounter a subexpression that (1) clearly does not lead to one of the
7399/// above problematic expressions (2) is something we cannot determine leads to
7400/// a problematic expression based on such local checking.
7401///
7402/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7403/// the expression that they point to. Such variables are added to the
7404/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007405///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007406/// EvalAddr processes expressions that are pointers that are used as
7407/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007408/// At the base case of the recursion is a check for the above problematic
7409/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007410///
7411/// This implementation handles:
7412///
7413/// * pointer-to-pointer casts
7414/// * implicit conversions from array references to pointers
7415/// * taking the address of fields
7416/// * arbitrary interplay between "&" and "*" operators
7417/// * pointer arithmetic from an address of a stack variable
7418/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007419static const Expr *EvalAddr(const Expr *E,
7420 SmallVectorImpl<const DeclRefExpr *> &refVars,
7421 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007422 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00007423 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007424
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007425 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00007426 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00007427 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007428 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00007429 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00007430
Peter Collingbourne91147592011-04-15 00:35:48 +00007431 E = E->IgnoreParens();
7432
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007433 // Our "symbolic interpreter" is just a dispatch off the currently
7434 // viewed AST node. We then recursively traverse the AST by calling
7435 // EvalAddr and EvalVal appropriately.
7436 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007437 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007438 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007439
Richard Smith40f08eb2014-01-30 22:05:38 +00007440 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00007441 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00007442 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00007443
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007444 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007445 // If this is a reference variable, follow through to the expression that
7446 // it points to.
7447 if (V->hasLocalStorage() &&
7448 V->getType()->isReferenceType() && V->hasInit()) {
7449 // Add the reference variable to the "trail".
7450 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007451 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007452 }
7453
Craig Topperc3ec1492014-05-26 06:22:03 +00007454 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007455 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007456
Chris Lattner934edb22007-12-28 05:31:15 +00007457 case Stmt::UnaryOperatorClass: {
7458 // The only unary operator that make sense to handle here
7459 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007460 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007461
John McCalle3027922010-08-25 11:45:40 +00007462 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007463 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007464 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007465 }
Mike Stump11289f42009-09-09 15:08:12 +00007466
Chris Lattner934edb22007-12-28 05:31:15 +00007467 case Stmt::BinaryOperatorClass: {
7468 // Handle pointer arithmetic. All other binary operators are not valid
7469 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007470 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00007471 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00007472
John McCalle3027922010-08-25 11:45:40 +00007473 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00007474 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007475
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007476 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00007477
7478 // Determine which argument is the real pointer base. It could be
7479 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007480 if (!Base->getType()->isPointerType())
7481 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00007482
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007483 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007484 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007485 }
Steve Naroff2752a172008-09-10 19:17:48 +00007486
Chris Lattner934edb22007-12-28 05:31:15 +00007487 // For conditional operators we need to see if either the LHS or RHS are
7488 // valid DeclRefExpr*s. If one of them is valid, we return it.
7489 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007490 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007491
Chris Lattner934edb22007-12-28 05:31:15 +00007492 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007493 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007494 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007495 // In C++, we can have a throw-expression, which has 'void' type.
7496 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007497 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007498 return LHS;
7499 }
Chris Lattner934edb22007-12-28 05:31:15 +00007500
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007501 // In C++, we can have a throw-expression, which has 'void' type.
7502 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00007503 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007504
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007505 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007506 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007507
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007508 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00007509 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007510 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00007511 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007512
7513 case Stmt::AddrLabelExprClass:
7514 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00007515
John McCall28fc7092011-11-10 05:35:25 +00007516 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007517 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7518 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00007519
Ted Kremenekc3b4c522008-08-07 00:49:01 +00007520 // For casts, we need to handle conversions from arrays to
7521 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00007522 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00007523 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007524 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00007525 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00007526 case Stmt::CXXStaticCastExprClass:
7527 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00007528 case Stmt::CXXConstCastExprClass:
7529 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007530 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00007531 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00007532 case CK_LValueToRValue:
7533 case CK_NoOp:
7534 case CK_BaseToDerived:
7535 case CK_DerivedToBase:
7536 case CK_UncheckedDerivedToBase:
7537 case CK_Dynamic:
7538 case CK_CPointerToObjCPointerCast:
7539 case CK_BlockPointerToObjCPointerCast:
7540 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007541 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007542
7543 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007544 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007545
Richard Trieudadefde2014-07-02 04:39:38 +00007546 case CK_BitCast:
7547 if (SubExpr->getType()->isAnyPointerType() ||
7548 SubExpr->getType()->isBlockPointerType() ||
7549 SubExpr->getType()->isObjCQualifiedIdType())
7550 return EvalAddr(SubExpr, refVars, ParentDecl);
7551 else
7552 return nullptr;
7553
Eli Friedman8195ad72012-02-23 23:04:32 +00007554 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007555 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00007556 }
Chris Lattner934edb22007-12-28 05:31:15 +00007557 }
Mike Stump11289f42009-09-09 15:08:12 +00007558
Douglas Gregorfe314812011-06-21 17:03:29 +00007559 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007560 if (const Expr *Result =
7561 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7562 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00007563 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00007564 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007565
Chris Lattner934edb22007-12-28 05:31:15 +00007566 // Everything else: we simply don't reason about them.
7567 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007568 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00007569 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007570}
Mike Stump11289f42009-09-09 15:08:12 +00007571
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007572/// EvalVal - This function is complements EvalAddr in the mutual recursion.
7573/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007574static const Expr *EvalVal(const Expr *E,
7575 SmallVectorImpl<const DeclRefExpr *> &refVars,
7576 const Decl *ParentDecl) {
7577 do {
7578 // We should only be called for evaluating non-pointer expressions, or
7579 // expressions with a pointer type that are not used as references but
7580 // instead
7581 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00007582
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007583 // Our "symbolic interpreter" is just a dispatch off the currently
7584 // viewed AST node. We then recursively traverse the AST by calling
7585 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00007586
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007587 E = E->IgnoreParens();
7588 switch (E->getStmtClass()) {
7589 case Stmt::ImplicitCastExprClass: {
7590 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7591 if (IE->getValueKind() == VK_LValue) {
7592 E = IE->getSubExpr();
7593 continue;
7594 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007595 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007596 }
Richard Smith40f08eb2014-01-30 22:05:38 +00007597
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007598 case Stmt::ExprWithCleanupsClass:
7599 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7600 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007601
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007602 case Stmt::DeclRefExprClass: {
7603 // When we hit a DeclRefExpr we are looking at code that refers to a
7604 // variable's name. If it's not a reference variable we check if it has
7605 // local storage within the function, and if so, return the expression.
7606 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7607
7608 // If we leave the immediate function, the lifetime isn't about to end.
7609 if (DR->refersToEnclosingVariableOrCapture())
7610 return nullptr;
7611
7612 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7613 // Check if it refers to itself, e.g. "int& i = i;".
7614 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007615 return DR;
7616
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007617 if (V->hasLocalStorage()) {
7618 if (!V->getType()->isReferenceType())
7619 return DR;
7620
7621 // Reference variable, follow through to the expression that
7622 // it points to.
7623 if (V->hasInit()) {
7624 // Add the reference variable to the "trail".
7625 refVars.push_back(DR);
7626 return EvalVal(V->getInit(), refVars, V);
7627 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007628 }
7629 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007630
7631 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007632 }
Mike Stump11289f42009-09-09 15:08:12 +00007633
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007634 case Stmt::UnaryOperatorClass: {
7635 // The only unary operator that make sense to handle here
7636 // is Deref. All others don't resolve to a "name." This includes
7637 // handling all sorts of rvalues passed to a unary operator.
7638 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007639
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007640 if (U->getOpcode() == UO_Deref)
7641 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007642
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007643 return nullptr;
7644 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007645
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007646 case Stmt::ArraySubscriptExprClass: {
7647 // Array subscripts are potential references to data on the stack. We
7648 // retrieve the DeclRefExpr* for the array variable if it indeed
7649 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00007650 const auto *ASE = cast<ArraySubscriptExpr>(E);
7651 if (ASE->isTypeDependent())
7652 return nullptr;
7653 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007654 }
Mike Stump11289f42009-09-09 15:08:12 +00007655
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007656 case Stmt::OMPArraySectionExprClass: {
7657 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7658 ParentDecl);
7659 }
Mike Stump11289f42009-09-09 15:08:12 +00007660
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007661 case Stmt::ConditionalOperatorClass: {
7662 // For conditional operators we need to see if either the LHS or RHS are
7663 // non-NULL Expr's. If one is non-NULL, we return it.
7664 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007665
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007666 // Handle the GNU extension for missing LHS.
7667 if (const Expr *LHSExpr = C->getLHS()) {
7668 // In C++, we can have a throw-expression, which has 'void' type.
7669 if (!LHSExpr->getType()->isVoidType())
7670 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7671 return LHS;
7672 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007673
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007674 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007675 if (C->getRHS()->getType()->isVoidType())
7676 return nullptr;
7677
7678 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007679 }
7680
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007681 // Accesses to members are potential references to data on the stack.
7682 case Stmt::MemberExprClass: {
7683 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00007684
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007685 // Check for indirect access. We only want direct field accesses.
7686 if (M->isArrow())
7687 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007688
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007689 // Check whether the member type is itself a reference, in which case
7690 // we're not going to refer to the member, but to what the member refers
7691 // to.
7692 if (M->getMemberDecl()->getType()->isReferenceType())
7693 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007694
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007695 return EvalVal(M->getBase(), refVars, ParentDecl);
7696 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00007697
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007698 case Stmt::MaterializeTemporaryExprClass:
7699 if (const Expr *Result =
7700 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7701 refVars, ParentDecl))
7702 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007703 return E;
7704
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007705 default:
7706 // Check that we don't return or take the address of a reference to a
7707 // temporary. This is only useful in C++.
7708 if (!E->isTypeDependent() && E->isRValue())
7709 return E;
7710
7711 // Everything else: we simply don't reason about them.
7712 return nullptr;
7713 }
7714 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007715}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007716
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007717void
7718Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7719 SourceLocation ReturnLoc,
7720 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00007721 const AttrVec *Attrs,
7722 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007723 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7724
7725 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00007726 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7727 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00007728 CheckNonNullExpr(*this, RetValExp))
7729 Diag(ReturnLoc, diag::warn_null_ret)
7730 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00007731
7732 // C++11 [basic.stc.dynamic.allocation]p4:
7733 // If an allocation function declared with a non-throwing
7734 // exception-specification fails to allocate storage, it shall return
7735 // a null pointer. Any other allocation function that fails to allocate
7736 // storage shall indicate failure only by throwing an exception [...]
7737 if (FD) {
7738 OverloadedOperatorKind Op = FD->getOverloadedOperator();
7739 if (Op == OO_New || Op == OO_Array_New) {
7740 const FunctionProtoType *Proto
7741 = FD->getType()->castAs<FunctionProtoType>();
7742 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7743 CheckNonNullExpr(*this, RetValExp))
7744 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7745 << FD << getLangOpts().CPlusPlus11;
7746 }
7747 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007748}
7749
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007750//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7751
7752/// Check for comparisons of floating point operands using != and ==.
7753/// Issue a warning if these are no self-comparisons, as they are not likely
7754/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00007755void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00007756 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7757 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007758
7759 // Special case: check for x == x (which is OK).
7760 // Do not emit warnings for such cases.
7761 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7762 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7763 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00007764 return;
Mike Stump11289f42009-09-09 15:08:12 +00007765
Ted Kremenekeda40e22007-11-29 00:59:04 +00007766 // Special case: check for comparisons against literals that can be exactly
7767 // represented by APFloat. In such cases, do not emit a warning. This
7768 // is a heuristic: often comparison against such literals are used to
7769 // detect if a value in a variable has not changed. This clearly can
7770 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00007771 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7772 if (FLL->isExact())
7773 return;
7774 } else
7775 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7776 if (FLR->isExact())
7777 return;
Mike Stump11289f42009-09-09 15:08:12 +00007778
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007779 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00007780 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007781 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007782 return;
Mike Stump11289f42009-09-09 15:08:12 +00007783
David Blaikie1f4ff152012-07-16 20:47:22 +00007784 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007785 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007786 return;
Mike Stump11289f42009-09-09 15:08:12 +00007787
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007788 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00007789 Diag(Loc, diag::warn_floatingpoint_eq)
7790 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007791}
John McCallca01b222010-01-04 23:21:16 +00007792
John McCall70aa5392010-01-06 05:24:50 +00007793//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7794//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00007795
John McCall70aa5392010-01-06 05:24:50 +00007796namespace {
John McCallca01b222010-01-04 23:21:16 +00007797
John McCall70aa5392010-01-06 05:24:50 +00007798/// Structure recording the 'active' range of an integer-valued
7799/// expression.
7800struct IntRange {
7801 /// The number of bits active in the int.
7802 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00007803
John McCall70aa5392010-01-06 05:24:50 +00007804 /// True if the int is known not to have negative values.
7805 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00007806
John McCall70aa5392010-01-06 05:24:50 +00007807 IntRange(unsigned Width, bool NonNegative)
7808 : Width(Width), NonNegative(NonNegative)
7809 {}
John McCallca01b222010-01-04 23:21:16 +00007810
John McCall817d4af2010-11-10 23:38:19 +00007811 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00007812 static IntRange forBoolType() {
7813 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00007814 }
7815
John McCall817d4af2010-11-10 23:38:19 +00007816 /// Returns the range of an opaque value of the given integral type.
7817 static IntRange forValueOfType(ASTContext &C, QualType T) {
7818 return forValueOfCanonicalType(C,
7819 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00007820 }
7821
John McCall817d4af2010-11-10 23:38:19 +00007822 /// Returns the range of an opaque value of a canonical integral type.
7823 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00007824 assert(T->isCanonicalUnqualified());
7825
7826 if (const VectorType *VT = dyn_cast<VectorType>(T))
7827 T = VT->getElementType().getTypePtr();
7828 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7829 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007830 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7831 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00007832
David Majnemer6a426652013-06-07 22:07:20 +00007833 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00007834 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00007835 EnumDecl *Enum = ET->getDecl();
7836 if (!Enum->isCompleteDefinition())
7837 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00007838
David Majnemer6a426652013-06-07 22:07:20 +00007839 unsigned NumPositive = Enum->getNumPositiveBits();
7840 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00007841
David Majnemer6a426652013-06-07 22:07:20 +00007842 if (NumNegative == 0)
7843 return IntRange(NumPositive, true/*NonNegative*/);
7844 else
7845 return IntRange(std::max(NumPositive + 1, NumNegative),
7846 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00007847 }
John McCall70aa5392010-01-06 05:24:50 +00007848
7849 const BuiltinType *BT = cast<BuiltinType>(T);
7850 assert(BT->isInteger());
7851
7852 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7853 }
7854
John McCall817d4af2010-11-10 23:38:19 +00007855 /// Returns the "target" range of a canonical integral type, i.e.
7856 /// the range of values expressible in the type.
7857 ///
7858 /// This matches forValueOfCanonicalType except that enums have the
7859 /// full range of their type, not the range of their enumerators.
7860 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7861 assert(T->isCanonicalUnqualified());
7862
7863 if (const VectorType *VT = dyn_cast<VectorType>(T))
7864 T = VT->getElementType().getTypePtr();
7865 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7866 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007867 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7868 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007869 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00007870 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007871
7872 const BuiltinType *BT = cast<BuiltinType>(T);
7873 assert(BT->isInteger());
7874
7875 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7876 }
7877
7878 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00007879 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00007880 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00007881 L.NonNegative && R.NonNegative);
7882 }
7883
John McCall817d4af2010-11-10 23:38:19 +00007884 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00007885 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00007886 return IntRange(std::min(L.Width, R.Width),
7887 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00007888 }
7889};
7890
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007891IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007892 if (value.isSigned() && value.isNegative())
7893 return IntRange(value.getMinSignedBits(), false);
7894
7895 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00007896 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007897
7898 // isNonNegative() just checks the sign bit without considering
7899 // signedness.
7900 return IntRange(value.getActiveBits(), true);
7901}
7902
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007903IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7904 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007905 if (result.isInt())
7906 return GetValueRange(C, result.getInt(), MaxWidth);
7907
7908 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00007909 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7910 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7911 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7912 R = IntRange::join(R, El);
7913 }
John McCall70aa5392010-01-06 05:24:50 +00007914 return R;
7915 }
7916
7917 if (result.isComplexInt()) {
7918 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7919 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7920 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00007921 }
7922
7923 // This can happen with lossless casts to intptr_t of "based" lvalues.
7924 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00007925 // FIXME: The only reason we need to pass the type in here is to get
7926 // the sign right on this one case. It would be nice if APValue
7927 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007928 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00007929 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00007930}
John McCall70aa5392010-01-06 05:24:50 +00007931
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007932QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007933 QualType Ty = E->getType();
7934 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7935 Ty = AtomicRHS->getValueType();
7936 return Ty;
7937}
7938
John McCall70aa5392010-01-06 05:24:50 +00007939/// Pseudo-evaluate the given integer expression, estimating the
7940/// range of values it might take.
7941///
7942/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007943IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007944 E = E->IgnoreParens();
7945
7946 // Try a full evaluation first.
7947 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007948 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00007949 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007950
7951 // I think we only want to look through implicit casts here; if the
7952 // user has an explicit widening cast, we should treat the value as
7953 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007954 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00007955 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00007956 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7957
Eli Friedmane6d33952013-07-08 20:20:06 +00007958 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00007959
George Burgess IVdf1ed002016-01-13 01:52:39 +00007960 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7961 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00007962
John McCall70aa5392010-01-06 05:24:50 +00007963 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00007964 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00007965 return OutputTypeRange;
7966
7967 IntRange SubRange
7968 = GetExprRange(C, CE->getSubExpr(),
7969 std::min(MaxWidth, OutputTypeRange.Width));
7970
7971 // Bail out if the subexpr's range is as wide as the cast type.
7972 if (SubRange.Width >= OutputTypeRange.Width)
7973 return OutputTypeRange;
7974
7975 // Otherwise, we take the smaller width, and we're non-negative if
7976 // either the output type or the subexpr is.
7977 return IntRange(SubRange.Width,
7978 SubRange.NonNegative || OutputTypeRange.NonNegative);
7979 }
7980
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007981 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007982 // If we can fold the condition, just take that operand.
7983 bool CondResult;
7984 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7985 return GetExprRange(C, CondResult ? CO->getTrueExpr()
7986 : CO->getFalseExpr(),
7987 MaxWidth);
7988
7989 // Otherwise, conservatively merge.
7990 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7991 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7992 return IntRange::join(L, R);
7993 }
7994
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007995 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007996 switch (BO->getOpcode()) {
7997
7998 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00007999 case BO_LAnd:
8000 case BO_LOr:
8001 case BO_LT:
8002 case BO_GT:
8003 case BO_LE:
8004 case BO_GE:
8005 case BO_EQ:
8006 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00008007 return IntRange::forBoolType();
8008
John McCallc3688382011-07-13 06:35:24 +00008009 // The type of the assignments is the type of the LHS, so the RHS
8010 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00008011 case BO_MulAssign:
8012 case BO_DivAssign:
8013 case BO_RemAssign:
8014 case BO_AddAssign:
8015 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00008016 case BO_XorAssign:
8017 case BO_OrAssign:
8018 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00008019 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00008020
John McCallc3688382011-07-13 06:35:24 +00008021 // Simple assignments just pass through the RHS, which will have
8022 // been coerced to the LHS type.
8023 case BO_Assign:
8024 // TODO: bitfields?
8025 return GetExprRange(C, BO->getRHS(), MaxWidth);
8026
John McCall70aa5392010-01-06 05:24:50 +00008027 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008028 case BO_PtrMemD:
8029 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00008030 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008031
John McCall2ce81ad2010-01-06 22:07:33 +00008032 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00008033 case BO_And:
8034 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00008035 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8036 GetExprRange(C, BO->getRHS(), MaxWidth));
8037
John McCall70aa5392010-01-06 05:24:50 +00008038 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00008039 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00008040 // ...except that we want to treat '1 << (blah)' as logically
8041 // positive. It's an important idiom.
8042 if (IntegerLiteral *I
8043 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8044 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008045 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00008046 return IntRange(R.Width, /*NonNegative*/ true);
8047 }
8048 }
8049 // fallthrough
8050
John McCalle3027922010-08-25 11:45:40 +00008051 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00008052 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008053
John McCall2ce81ad2010-01-06 22:07:33 +00008054 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00008055 case BO_Shr:
8056 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00008057 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8058
8059 // If the shift amount is a positive constant, drop the width by
8060 // that much.
8061 llvm::APSInt shift;
8062 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8063 shift.isNonNegative()) {
8064 unsigned zext = shift.getZExtValue();
8065 if (zext >= L.Width)
8066 L.Width = (L.NonNegative ? 0 : 1);
8067 else
8068 L.Width -= zext;
8069 }
8070
8071 return L;
8072 }
8073
8074 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008075 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008076 return GetExprRange(C, BO->getRHS(), MaxWidth);
8077
John McCall2ce81ad2010-01-06 22:07:33 +00008078 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008079 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008080 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008081 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008082 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008083
John McCall51431812011-07-14 22:39:48 +00008084 // The width of a division result is mostly determined by the size
8085 // of the LHS.
8086 case BO_Div: {
8087 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008088 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008089 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8090
8091 // If the divisor is constant, use that.
8092 llvm::APSInt divisor;
8093 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8094 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8095 if (log2 >= L.Width)
8096 L.Width = (L.NonNegative ? 0 : 1);
8097 else
8098 L.Width = std::min(L.Width - log2, MaxWidth);
8099 return L;
8100 }
8101
8102 // Otherwise, just use the LHS's width.
8103 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8104 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8105 }
8106
8107 // The result of a remainder can't be larger than the result of
8108 // either side.
8109 case BO_Rem: {
8110 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008111 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008112 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8113 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8114
8115 IntRange meet = IntRange::meet(L, R);
8116 meet.Width = std::min(meet.Width, MaxWidth);
8117 return meet;
8118 }
8119
8120 // The default behavior is okay for these.
8121 case BO_Mul:
8122 case BO_Add:
8123 case BO_Xor:
8124 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008125 break;
8126 }
8127
John McCall51431812011-07-14 22:39:48 +00008128 // The default case is to treat the operation as if it were closed
8129 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008130 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8131 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8132 return IntRange::join(L, R);
8133 }
8134
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008135 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008136 switch (UO->getOpcode()) {
8137 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008138 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008139 return IntRange::forBoolType();
8140
8141 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008142 case UO_Deref:
8143 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00008144 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008145
8146 default:
8147 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8148 }
8149 }
8150
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008151 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00008152 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8153
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008154 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00008155 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00008156 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00008157
Eli Friedmane6d33952013-07-08 20:20:06 +00008158 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008159}
John McCall263a48b2010-01-04 23:31:57 +00008160
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008161IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008162 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00008163}
8164
John McCall263a48b2010-01-04 23:31:57 +00008165/// Checks whether the given value, which currently has the given
8166/// source semantics, has the same value when coerced through the
8167/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008168bool IsSameFloatAfterCast(const llvm::APFloat &value,
8169 const llvm::fltSemantics &Src,
8170 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008171 llvm::APFloat truncated = value;
8172
8173 bool ignored;
8174 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8175 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8176
8177 return truncated.bitwiseIsEqual(value);
8178}
8179
8180/// Checks whether the given value, which currently has the given
8181/// source semantics, has the same value when coerced through the
8182/// target semantics.
8183///
8184/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008185bool IsSameFloatAfterCast(const APValue &value,
8186 const llvm::fltSemantics &Src,
8187 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008188 if (value.isFloat())
8189 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8190
8191 if (value.isVector()) {
8192 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8193 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8194 return false;
8195 return true;
8196 }
8197
8198 assert(value.isComplexFloat());
8199 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8200 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8201}
8202
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008203void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008204
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008205bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00008206 // Suppress cases where we are comparing against an enum constant.
8207 if (const DeclRefExpr *DR =
8208 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8209 if (isa<EnumConstantDecl>(DR->getDecl()))
8210 return false;
8211
8212 // Suppress cases where the '0' value is expanded from a macro.
8213 if (E->getLocStart().isMacroID())
8214 return false;
8215
John McCallcc7e5bf2010-05-06 08:58:33 +00008216 llvm::APSInt Value;
8217 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8218}
8219
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008220bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00008221 // Strip off implicit integral promotions.
8222 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008223 if (ICE->getCastKind() != CK_IntegralCast &&
8224 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00008225 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008226 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00008227 }
8228
8229 return E->getType()->isEnumeralType();
8230}
8231
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008232void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00008233 // Disable warning in template instantiations.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008234 if (S.inTemplateInstantiation())
Richard Trieu36594562013-11-01 21:47:19 +00008235 return;
8236
John McCalle3027922010-08-25 11:45:40 +00008237 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00008238 if (E->isValueDependent())
8239 return;
8240
John McCalle3027922010-08-25 11:45:40 +00008241 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008242 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008243 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008244 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008245 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008246 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008247 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008248 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008249 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008250 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008251 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008252 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008253 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008254 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008255 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008256 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8257 }
8258}
8259
Benjamin Kramer7320b992016-06-15 14:20:56 +00008260void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8261 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008262 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00008263 // Disable warning in template instantiations.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008264 if (S.inTemplateInstantiation())
Richard Trieudd51d742013-11-01 21:19:43 +00008265 return;
8266
Richard Trieu0f097742014-04-04 04:13:47 +00008267 // TODO: Investigate using GetExprRange() to get tighter bounds
8268 // on the bit ranges.
8269 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00008270 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00008271 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00008272 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8273 unsigned OtherWidth = OtherRange.Width;
8274
8275 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8276
Richard Trieu560910c2012-11-14 22:50:24 +00008277 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00008278 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00008279 return;
8280
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008281 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00008282 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008283
Richard Trieu0f097742014-04-04 04:13:47 +00008284 // Used for diagnostic printout.
8285 enum {
8286 LiteralConstant = 0,
8287 CXXBoolLiteralTrue,
8288 CXXBoolLiteralFalse
8289 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008290
Richard Trieu0f097742014-04-04 04:13:47 +00008291 if (!OtherIsBooleanType) {
8292 QualType ConstantT = Constant->getType();
8293 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00008294
Richard Trieu0f097742014-04-04 04:13:47 +00008295 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8296 return;
8297 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8298 "comparison with non-integer type");
8299
8300 bool ConstantSigned = ConstantT->isSignedIntegerType();
8301 bool CommonSigned = CommonT->isSignedIntegerType();
8302
8303 bool EqualityOnly = false;
8304
8305 if (CommonSigned) {
8306 // The common type is signed, therefore no signed to unsigned conversion.
8307 if (!OtherRange.NonNegative) {
8308 // Check that the constant is representable in type OtherT.
8309 if (ConstantSigned) {
8310 if (OtherWidth >= Value.getMinSignedBits())
8311 return;
8312 } else { // !ConstantSigned
8313 if (OtherWidth >= Value.getActiveBits() + 1)
8314 return;
8315 }
8316 } else { // !OtherSigned
8317 // Check that the constant is representable in type OtherT.
8318 // Negative values are out of range.
8319 if (ConstantSigned) {
8320 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8321 return;
8322 } else { // !ConstantSigned
8323 if (OtherWidth >= Value.getActiveBits())
8324 return;
8325 }
Richard Trieu560910c2012-11-14 22:50:24 +00008326 }
Richard Trieu0f097742014-04-04 04:13:47 +00008327 } else { // !CommonSigned
8328 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00008329 if (OtherWidth >= Value.getActiveBits())
8330 return;
Craig Toppercf360162014-06-18 05:13:11 +00008331 } else { // OtherSigned
8332 assert(!ConstantSigned &&
8333 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00008334 // Check to see if the constant is representable in OtherT.
8335 if (OtherWidth > Value.getActiveBits())
8336 return;
8337 // Check to see if the constant is equivalent to a negative value
8338 // cast to CommonT.
8339 if (S.Context.getIntWidth(ConstantT) ==
8340 S.Context.getIntWidth(CommonT) &&
8341 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8342 return;
8343 // The constant value rests between values that OtherT can represent
8344 // after conversion. Relational comparison still works, but equality
8345 // comparisons will be tautological.
8346 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008347 }
8348 }
Richard Trieu0f097742014-04-04 04:13:47 +00008349
8350 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8351
8352 if (op == BO_EQ || op == BO_NE) {
8353 IsTrue = op == BO_NE;
8354 } else if (EqualityOnly) {
8355 return;
8356 } else if (RhsConstant) {
8357 if (op == BO_GT || op == BO_GE)
8358 IsTrue = !PositiveConstant;
8359 else // op == BO_LT || op == BO_LE
8360 IsTrue = PositiveConstant;
8361 } else {
8362 if (op == BO_LT || op == BO_LE)
8363 IsTrue = !PositiveConstant;
8364 else // op == BO_GT || op == BO_GE
8365 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008366 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008367 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00008368 // Other isKnownToHaveBooleanValue
8369 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8370 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8371 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8372
8373 static const struct LinkedConditions {
8374 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8375 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8376 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8377 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8378 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8379 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8380
8381 } TruthTable = {
8382 // Constant on LHS. | Constant on RHS. |
8383 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
8384 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8385 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8386 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8387 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8388 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8389 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8390 };
8391
8392 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8393
8394 enum ConstantValue ConstVal = Zero;
8395 if (Value.isUnsigned() || Value.isNonNegative()) {
8396 if (Value == 0) {
8397 LiteralOrBoolConstant =
8398 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8399 ConstVal = Zero;
8400 } else if (Value == 1) {
8401 LiteralOrBoolConstant =
8402 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8403 ConstVal = One;
8404 } else {
8405 LiteralOrBoolConstant = LiteralConstant;
8406 ConstVal = GT_One;
8407 }
8408 } else {
8409 ConstVal = LT_Zero;
8410 }
8411
8412 CompareBoolWithConstantResult CmpRes;
8413
8414 switch (op) {
8415 case BO_LT:
8416 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8417 break;
8418 case BO_GT:
8419 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8420 break;
8421 case BO_LE:
8422 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8423 break;
8424 case BO_GE:
8425 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8426 break;
8427 case BO_EQ:
8428 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8429 break;
8430 case BO_NE:
8431 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8432 break;
8433 default:
8434 CmpRes = Unkwn;
8435 break;
8436 }
8437
8438 if (CmpRes == AFals) {
8439 IsTrue = false;
8440 } else if (CmpRes == ATrue) {
8441 IsTrue = true;
8442 } else {
8443 return;
8444 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008445 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008446
8447 // If this is a comparison to an enum constant, include that
8448 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00008449 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008450 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8451 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8452
8453 SmallString<64> PrettySourceValue;
8454 llvm::raw_svector_ostream OS(PrettySourceValue);
8455 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00008456 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008457 else
8458 OS << Value;
8459
Richard Trieu0f097742014-04-04 04:13:47 +00008460 S.DiagRuntimeBehavior(
8461 E->getOperatorLoc(), E,
8462 S.PDiag(diag::warn_out_of_range_compare)
8463 << OS.str() << LiteralOrBoolConstant
8464 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8465 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008466}
8467
John McCallcc7e5bf2010-05-06 08:58:33 +00008468/// Analyze the operands of the given comparison. Implements the
8469/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008470void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00008471 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8472 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008473}
John McCall263a48b2010-01-04 23:31:57 +00008474
John McCallca01b222010-01-04 23:21:16 +00008475/// \brief Implements -Wsign-compare.
8476///
Richard Trieu82402a02011-09-15 21:56:47 +00008477/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008478void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008479 // The type the comparison is being performed in.
8480 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00008481
8482 // Only analyze comparison operators where both sides have been converted to
8483 // the same type.
8484 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8485 return AnalyzeImpConvsInComparison(S, E);
8486
8487 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00008488 if (E->isValueDependent())
8489 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008490
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008491 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8492 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008493
8494 bool IsComparisonConstant = false;
8495
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008496 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008497 // of 'true' or 'false'.
8498 if (T->isIntegralType(S.Context)) {
8499 llvm::APSInt RHSValue;
8500 bool IsRHSIntegralLiteral =
8501 RHS->isIntegerConstantExpr(RHSValue, S.Context);
8502 llvm::APSInt LHSValue;
8503 bool IsLHSIntegralLiteral =
8504 LHS->isIntegerConstantExpr(LHSValue, S.Context);
8505 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8506 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8507 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8508 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8509 else
8510 IsComparisonConstant =
8511 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008512 } else if (!T->hasUnsignedIntegerRepresentation())
8513 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008514
John McCallcc7e5bf2010-05-06 08:58:33 +00008515 // We don't do anything special if this isn't an unsigned integral
8516 // comparison: we're only interested in integral comparisons, and
8517 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00008518 //
8519 // We also don't care about value-dependent expressions or expressions
8520 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008521 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00008522 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008523
John McCallcc7e5bf2010-05-06 08:58:33 +00008524 // Check to see if one of the (unmodified) operands is of different
8525 // signedness.
8526 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00008527 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8528 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00008529 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00008530 signedOperand = LHS;
8531 unsignedOperand = RHS;
8532 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8533 signedOperand = RHS;
8534 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00008535 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00008536 CheckTrivialUnsignedComparison(S, E);
8537 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008538 }
8539
John McCallcc7e5bf2010-05-06 08:58:33 +00008540 // Otherwise, calculate the effective range of the signed operand.
8541 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00008542
John McCallcc7e5bf2010-05-06 08:58:33 +00008543 // Go ahead and analyze implicit conversions in the operands. Note
8544 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00008545 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8546 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00008547
John McCallcc7e5bf2010-05-06 08:58:33 +00008548 // If the signed range is non-negative, -Wsign-compare won't fire,
8549 // but we should still check for comparisons which are always true
8550 // or false.
8551 if (signedRange.NonNegative)
8552 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008553
8554 // For (in)equality comparisons, if the unsigned operand is a
8555 // constant which cannot collide with a overflowed signed operand,
8556 // then reinterpreting the signed operand as unsigned will not
8557 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00008558 if (E->isEqualityOp()) {
8559 unsigned comparisonWidth = S.Context.getIntWidth(T);
8560 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00008561
John McCallcc7e5bf2010-05-06 08:58:33 +00008562 // We should never be unable to prove that the unsigned operand is
8563 // non-negative.
8564 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8565
8566 if (unsignedRange.Width < comparisonWidth)
8567 return;
8568 }
8569
Douglas Gregorbfb4a212012-05-01 01:53:49 +00008570 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8571 S.PDiag(diag::warn_mixed_sign_comparison)
8572 << LHS->getType() << RHS->getType()
8573 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00008574}
8575
John McCall1f425642010-11-11 03:21:53 +00008576/// Analyzes an attempt to assign the given value to a bitfield.
8577///
8578/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008579bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8580 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00008581 assert(Bitfield->isBitField());
8582 if (Bitfield->isInvalidDecl())
8583 return false;
8584
John McCalldeebbcf2010-11-11 05:33:51 +00008585 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00008586 QualType BitfieldType = Bitfield->getType();
8587 if (BitfieldType->isBooleanType())
8588 return false;
8589
8590 if (BitfieldType->isEnumeralType()) {
8591 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
8592 // If the underlying enum type was not explicitly specified as an unsigned
8593 // type and the enum contain only positive values, MSVC++ will cause an
8594 // inconsistency by storing this as a signed type.
8595 if (S.getLangOpts().CPlusPlus11 &&
8596 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
8597 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
8598 BitfieldEnumDecl->getNumNegativeBits() == 0) {
8599 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
8600 << BitfieldEnumDecl->getNameAsString();
8601 }
8602 }
8603
John McCalldeebbcf2010-11-11 05:33:51 +00008604 if (Bitfield->getType()->isBooleanType())
8605 return false;
8606
Douglas Gregor789adec2011-02-04 13:09:01 +00008607 // Ignore value- or type-dependent expressions.
8608 if (Bitfield->getBitWidth()->isValueDependent() ||
8609 Bitfield->getBitWidth()->isTypeDependent() ||
8610 Init->isValueDependent() ||
8611 Init->isTypeDependent())
8612 return false;
8613
John McCall1f425642010-11-11 03:21:53 +00008614 Expr *OriginalInit = Init->IgnoreParenImpCasts();
8615
Richard Smith5fab0c92011-12-28 19:48:30 +00008616 llvm::APSInt Value;
8617 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00008618 return false;
8619
John McCall1f425642010-11-11 03:21:53 +00008620 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00008621 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00008622
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008623 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00008624 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008625 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8626 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00008627
John McCall1f425642010-11-11 03:21:53 +00008628 if (OriginalWidth <= FieldWidth)
8629 return false;
8630
Eli Friedmanc267a322012-01-26 23:11:39 +00008631 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00008632 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00008633 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00008634
Eli Friedmanc267a322012-01-26 23:11:39 +00008635 // Check whether the stored value is equal to the original value.
8636 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00008637 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00008638 return false;
8639
Eli Friedmanc267a322012-01-26 23:11:39 +00008640 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00008641 // therefore don't strictly fit into a signed bitfield of width 1.
8642 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00008643 return false;
8644
John McCall1f425642010-11-11 03:21:53 +00008645 std::string PrettyValue = Value.toString(10);
8646 std::string PrettyTrunc = TruncatedValue.toString(10);
8647
8648 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8649 << PrettyValue << PrettyTrunc << OriginalInit->getType()
8650 << Init->getSourceRange();
8651
8652 return true;
8653}
8654
John McCalld2a53122010-11-09 23:24:47 +00008655/// Analyze the given simple or compound assignment for warning-worthy
8656/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008657void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00008658 // Just recurse on the LHS.
8659 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8660
8661 // We want to recurse on the RHS as normal unless we're assigning to
8662 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00008663 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008664 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00008665 E->getOperatorLoc())) {
8666 // Recurse, ignoring any implicit conversions on the RHS.
8667 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8668 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00008669 }
8670 }
8671
8672 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8673}
8674
John McCall263a48b2010-01-04 23:31:57 +00008675/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008676void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8677 SourceLocation CContext, unsigned diag,
8678 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008679 if (pruneControlFlow) {
8680 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8681 S.PDiag(diag)
8682 << SourceType << T << E->getSourceRange()
8683 << SourceRange(CContext));
8684 return;
8685 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00008686 S.Diag(E->getExprLoc(), diag)
8687 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8688}
8689
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008690/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008691void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8692 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008693 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008694}
8695
Richard Trieube234c32016-04-21 21:04:55 +00008696
8697/// Diagnose an implicit cast from a floating point value to an integer value.
8698void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8699
8700 SourceLocation CContext) {
8701 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00008702 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00008703
8704 Expr *InnerE = E->IgnoreParenImpCasts();
8705 // We also want to warn on, e.g., "int i = -1.234"
8706 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8707 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8708 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8709
8710 const bool IsLiteral =
8711 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8712
8713 llvm::APFloat Value(0.0);
8714 bool IsConstant =
8715 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8716 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00008717 return DiagnoseImpCast(S, E, T, CContext,
8718 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00008719 }
8720
Chandler Carruth016ef402011-04-10 08:36:24 +00008721 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00008722
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00008723 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8724 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00008725 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8726 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00008727 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00008728 if (IsLiteral) return;
8729 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8730 PruneWarnings);
8731 }
8732
8733 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00008734 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00008735 // Warn on floating point literal to integer.
8736 DiagID = diag::warn_impcast_literal_float_to_integer;
8737 } else if (IntegerValue == 0) {
8738 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
8739 return DiagnoseImpCast(S, E, T, CContext,
8740 diag::warn_impcast_float_integer, PruneWarnings);
8741 }
8742 // Warn on non-zero to zero conversion.
8743 DiagID = diag::warn_impcast_float_to_integer_zero;
8744 } else {
8745 if (IntegerValue.isUnsigned()) {
8746 if (!IntegerValue.isMaxValue()) {
8747 return DiagnoseImpCast(S, E, T, CContext,
8748 diag::warn_impcast_float_integer, PruneWarnings);
8749 }
8750 } else { // IntegerValue.isSigned()
8751 if (!IntegerValue.isMaxSignedValue() &&
8752 !IntegerValue.isMinSignedValue()) {
8753 return DiagnoseImpCast(S, E, T, CContext,
8754 diag::warn_impcast_float_integer, PruneWarnings);
8755 }
8756 }
8757 // Warn on evaluatable floating point expression to integer conversion.
8758 DiagID = diag::warn_impcast_float_to_integer;
8759 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008760
Eli Friedman07185912013-08-29 23:44:43 +00008761 // FIXME: Force the precision of the source value down so we don't print
8762 // digits which are usually useless (we don't really care here if we
8763 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
8764 // would automatically print the shortest representation, but it's a bit
8765 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00008766 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00008767 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
8768 precision = (precision * 59 + 195) / 196;
8769 Value.toString(PrettySourceValue, precision);
8770
David Blaikie9b88cc02012-05-15 17:18:27 +00008771 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00008772 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00008773 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00008774 else
David Blaikie9b88cc02012-05-15 17:18:27 +00008775 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00008776
Richard Trieube234c32016-04-21 21:04:55 +00008777 if (PruneWarnings) {
8778 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8779 S.PDiag(DiagID)
8780 << E->getType() << T.getUnqualifiedType()
8781 << PrettySourceValue << PrettyTargetValue
8782 << E->getSourceRange() << SourceRange(CContext));
8783 } else {
8784 S.Diag(E->getExprLoc(), DiagID)
8785 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8786 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8787 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008788}
8789
John McCall18a2c2c2010-11-09 22:22:12 +00008790std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8791 if (!Range.Width) return "0";
8792
8793 llvm::APSInt ValueInRange = Value;
8794 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00008795 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00008796 return ValueInRange.toString(10);
8797}
8798
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008799bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008800 if (!isa<ImplicitCastExpr>(Ex))
8801 return false;
8802
8803 Expr *InnerE = Ex->IgnoreParenImpCasts();
8804 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8805 const Type *Source =
8806 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8807 if (Target->isDependentType())
8808 return false;
8809
8810 const BuiltinType *FloatCandidateBT =
8811 dyn_cast<BuiltinType>(ToBool ? Source : Target);
8812 const Type *BoolCandidateType = ToBool ? Target : Source;
8813
8814 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8815 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8816}
8817
8818void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8819 SourceLocation CC) {
8820 unsigned NumArgs = TheCall->getNumArgs();
8821 for (unsigned i = 0; i < NumArgs; ++i) {
8822 Expr *CurrA = TheCall->getArg(i);
8823 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8824 continue;
8825
8826 bool IsSwapped = ((i > 0) &&
8827 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8828 IsSwapped |= ((i < (NumArgs - 1)) &&
8829 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8830 if (IsSwapped) {
8831 // Warn on this floating-point to bool conversion.
8832 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8833 CurrA->getType(), CC,
8834 diag::warn_impcast_floating_point_to_bool);
8835 }
8836 }
8837}
8838
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008839void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00008840 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
8841 E->getExprLoc()))
8842 return;
8843
Richard Trieu09d6b802016-01-08 23:35:06 +00008844 // Don't warn on functions which have return type nullptr_t.
8845 if (isa<CallExpr>(E))
8846 return;
8847
Richard Trieu5b993502014-10-15 03:42:06 +00008848 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
8849 const Expr::NullPointerConstantKind NullKind =
8850 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
8851 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
8852 return;
8853
8854 // Return if target type is a safe conversion.
8855 if (T->isAnyPointerType() || T->isBlockPointerType() ||
8856 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8857 return;
8858
8859 SourceLocation Loc = E->getSourceRange().getBegin();
8860
Richard Trieu0a5e1662016-02-13 00:58:53 +00008861 // Venture through the macro stacks to get to the source of macro arguments.
8862 // The new location is a better location than the complete location that was
8863 // passed in.
8864 while (S.SourceMgr.isMacroArgExpansion(Loc))
8865 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8866
8867 while (S.SourceMgr.isMacroArgExpansion(CC))
8868 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8869
Richard Trieu5b993502014-10-15 03:42:06 +00008870 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00008871 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8872 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8873 Loc, S.SourceMgr, S.getLangOpts());
8874 if (MacroName == "NULL")
8875 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00008876 }
8877
8878 // Only warn if the null and context location are in the same macro expansion.
8879 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8880 return;
8881
8882 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8883 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8884 << FixItHint::CreateReplacement(Loc,
8885 S.getFixItZeroLiteralForType(T, Loc));
8886}
8887
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008888void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8889 ObjCArrayLiteral *ArrayLiteral);
8890void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8891 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00008892
8893/// Check a single element within a collection literal against the
8894/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008895void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8896 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008897 // Skip a bitcast to 'id' or qualified 'id'.
8898 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8899 if (ICE->getCastKind() == CK_BitCast &&
8900 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8901 Element = ICE->getSubExpr();
8902 }
8903
8904 QualType ElementType = Element->getType();
8905 ExprResult ElementResult(Element);
8906 if (ElementType->getAs<ObjCObjectPointerType>() &&
8907 S.CheckSingleAssignmentConstraints(TargetElementType,
8908 ElementResult,
8909 false, false)
8910 != Sema::Compatible) {
8911 S.Diag(Element->getLocStart(),
8912 diag::warn_objc_collection_literal_element)
8913 << ElementType << ElementKind << TargetElementType
8914 << Element->getSourceRange();
8915 }
8916
8917 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8918 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8919 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8920 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8921}
8922
8923/// Check an Objective-C array literal being converted to the given
8924/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008925void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8926 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008927 if (!S.NSArrayDecl)
8928 return;
8929
8930 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8931 if (!TargetObjCPtr)
8932 return;
8933
8934 if (TargetObjCPtr->isUnspecialized() ||
8935 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8936 != S.NSArrayDecl->getCanonicalDecl())
8937 return;
8938
8939 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8940 if (TypeArgs.size() != 1)
8941 return;
8942
8943 QualType TargetElementType = TypeArgs[0];
8944 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8945 checkObjCCollectionLiteralElement(S, TargetElementType,
8946 ArrayLiteral->getElement(I),
8947 0);
8948 }
8949}
8950
8951/// Check an Objective-C dictionary literal being converted to the given
8952/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008953void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8954 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008955 if (!S.NSDictionaryDecl)
8956 return;
8957
8958 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8959 if (!TargetObjCPtr)
8960 return;
8961
8962 if (TargetObjCPtr->isUnspecialized() ||
8963 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8964 != S.NSDictionaryDecl->getCanonicalDecl())
8965 return;
8966
8967 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8968 if (TypeArgs.size() != 2)
8969 return;
8970
8971 QualType TargetKeyType = TypeArgs[0];
8972 QualType TargetObjectType = TypeArgs[1];
8973 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8974 auto Element = DictionaryLiteral->getKeyValueElement(I);
8975 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8976 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8977 }
8978}
8979
Richard Trieufc404c72016-02-05 23:02:38 +00008980// Helper function to filter out cases for constant width constant conversion.
8981// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008982bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8983 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00008984 // If initializing from a constant, and the constant starts with '0',
8985 // then it is a binary, octal, or hexadecimal. Allow these constants
8986 // to fill all the bits, even if there is a sign change.
8987 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8988 const char FirstLiteralCharacter =
8989 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8990 if (FirstLiteralCharacter == '0')
8991 return false;
8992 }
8993
8994 // If the CC location points to a '{', and the type is char, then assume
8995 // assume it is an array initialization.
8996 if (CC.isValid() && T->isCharType()) {
8997 const char FirstContextCharacter =
8998 S.getSourceManager().getCharacterData(CC)[0];
8999 if (FirstContextCharacter == '{')
9000 return false;
9001 }
9002
9003 return true;
9004}
9005
John McCallcc7e5bf2010-05-06 08:58:33 +00009006void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00009007 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009008 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00009009
John McCallcc7e5bf2010-05-06 08:58:33 +00009010 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9011 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9012 if (Source == Target) return;
9013 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00009014
Chandler Carruthc22845a2011-07-26 05:40:03 +00009015 // If the conversion context location is invalid don't complain. We also
9016 // don't want to emit a warning if the issue occurs from the expansion of
9017 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9018 // delay this check as long as possible. Once we detect we are in that
9019 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009020 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00009021 return;
9022
Richard Trieu021baa32011-09-23 20:10:00 +00009023 // Diagnose implicit casts to bool.
9024 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9025 if (isa<StringLiteral>(E))
9026 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00009027 // and expressions, for instance, assert(0 && "error here"), are
9028 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00009029 return DiagnoseImpCast(S, E, T, CC,
9030 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00009031 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9032 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9033 // This covers the literal expressions that evaluate to Objective-C
9034 // objects.
9035 return DiagnoseImpCast(S, E, T, CC,
9036 diag::warn_impcast_objective_c_literal_to_bool);
9037 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009038 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9039 // Warn on pointer to bool conversion that is always true.
9040 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9041 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00009042 }
Richard Trieu021baa32011-09-23 20:10:00 +00009043 }
John McCall263a48b2010-01-04 23:31:57 +00009044
Douglas Gregor5054cb02015-07-07 03:58:22 +00009045 // Check implicit casts from Objective-C collection literals to specialized
9046 // collection types, e.g., NSArray<NSString *> *.
9047 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9048 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9049 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9050 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9051
John McCall263a48b2010-01-04 23:31:57 +00009052 // Strip vector types.
9053 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009054 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009055 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009056 return;
John McCallacf0ee52010-10-08 02:01:28 +00009057 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009058 }
Chris Lattneree7286f2011-06-14 04:51:15 +00009059
9060 // If the vector cast is cast between two vectors of the same size, it is
9061 // a bitcast, not a conversion.
9062 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9063 return;
John McCall263a48b2010-01-04 23:31:57 +00009064
9065 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9066 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9067 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00009068 if (auto VecTy = dyn_cast<VectorType>(Target))
9069 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00009070
9071 // Strip complex types.
9072 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009073 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009074 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009075 return;
9076
John McCallacf0ee52010-10-08 02:01:28 +00009077 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009078 }
John McCall263a48b2010-01-04 23:31:57 +00009079
9080 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9081 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9082 }
9083
9084 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9085 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9086
9087 // If the source is floating point...
9088 if (SourceBT && SourceBT->isFloatingPoint()) {
9089 // ...and the target is floating point...
9090 if (TargetBT && TargetBT->isFloatingPoint()) {
9091 // ...then warn if we're dropping FP rank.
9092
9093 // Builtin FP kinds are ordered by increasing FP rank.
9094 if (SourceBT->getKind() > TargetBT->getKind()) {
9095 // Don't warn about float constants that are precisely
9096 // representable in the target type.
9097 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009098 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00009099 // Value might be a float, a float vector, or a float complex.
9100 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00009101 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9102 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00009103 return;
9104 }
9105
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009106 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009107 return;
9108
John McCallacf0ee52010-10-08 02:01:28 +00009109 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00009110 }
9111 // ... or possibly if we're increasing rank, too
9112 else if (TargetBT->getKind() > SourceBT->getKind()) {
9113 if (S.SourceMgr.isInSystemMacro(CC))
9114 return;
9115
9116 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00009117 }
9118 return;
9119 }
9120
Richard Trieube234c32016-04-21 21:04:55 +00009121 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00009122 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009123 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009124 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00009125
Richard Trieube234c32016-04-21 21:04:55 +00009126 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00009127 }
John McCall263a48b2010-01-04 23:31:57 +00009128
Richard Smith54894fd2015-12-30 01:06:52 +00009129 // Detect the case where a call result is converted from floating-point to
9130 // to bool, and the final argument to the call is converted from bool, to
9131 // discover this typo:
9132 //
9133 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9134 //
9135 // FIXME: This is an incredibly special case; is there some more general
9136 // way to detect this class of misplaced-parentheses bug?
9137 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009138 // Check last argument of function call to see if it is an
9139 // implicit cast from a type matching the type the result
9140 // is being cast to.
9141 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00009142 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009143 Expr *LastA = CEx->getArg(NumArgs - 1);
9144 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00009145 if (isa<ImplicitCastExpr>(LastA) &&
9146 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009147 // Warn on this floating-point to bool conversion
9148 DiagnoseImpCast(S, E, T, CC,
9149 diag::warn_impcast_floating_point_to_bool);
9150 }
9151 }
9152 }
John McCall263a48b2010-01-04 23:31:57 +00009153 return;
9154 }
9155
Richard Trieu5b993502014-10-15 03:42:06 +00009156 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00009157
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009158 S.DiscardMisalignedMemberAddress(Target, E);
9159
David Blaikie9366d2b2012-06-19 21:19:06 +00009160 if (!Source->isIntegerType() || !Target->isIntegerType())
9161 return;
9162
David Blaikie7555b6a2012-05-15 16:56:36 +00009163 // TODO: remove this early return once the false positives for constant->bool
9164 // in templates, macros, etc, are reduced or removed.
9165 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9166 return;
9167
John McCallcc7e5bf2010-05-06 08:58:33 +00009168 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00009169 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00009170
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009171 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00009172 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009173 // TODO: this should happen for bitfield stores, too.
9174 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00009175 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009176 if (S.SourceMgr.isInSystemMacro(CC))
9177 return;
9178
John McCall18a2c2c2010-11-09 22:22:12 +00009179 std::string PrettySourceValue = Value.toString(10);
9180 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009181
Ted Kremenek33ba9952011-10-22 02:37:33 +00009182 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9183 S.PDiag(diag::warn_impcast_integer_precision_constant)
9184 << PrettySourceValue << PrettyTargetValue
9185 << E->getType() << T << E->getSourceRange()
9186 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00009187 return;
9188 }
9189
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009190 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9191 if (S.SourceMgr.isInSystemMacro(CC))
9192 return;
9193
David Blaikie9455da02012-04-12 22:40:54 +00009194 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00009195 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9196 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00009197 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00009198 }
9199
Richard Trieudcb55572016-01-29 23:51:16 +00009200 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9201 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9202 // Warn when doing a signed to signed conversion, warn if the positive
9203 // source value is exactly the width of the target type, which will
9204 // cause a negative value to be stored.
9205
9206 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00009207 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9208 !S.SourceMgr.isInSystemMacro(CC)) {
9209 if (isSameWidthConstantConversion(S, E, T, CC)) {
9210 std::string PrettySourceValue = Value.toString(10);
9211 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00009212
Richard Trieufc404c72016-02-05 23:02:38 +00009213 S.DiagRuntimeBehavior(
9214 E->getExprLoc(), E,
9215 S.PDiag(diag::warn_impcast_integer_precision_constant)
9216 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9217 << E->getSourceRange() << clang::SourceRange(CC));
9218 return;
Richard Trieudcb55572016-01-29 23:51:16 +00009219 }
9220 }
Richard Trieufc404c72016-02-05 23:02:38 +00009221
Richard Trieudcb55572016-01-29 23:51:16 +00009222 // Fall through for non-constants to give a sign conversion warning.
9223 }
9224
John McCallcc7e5bf2010-05-06 08:58:33 +00009225 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9226 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9227 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009228 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009229 return;
9230
John McCallcc7e5bf2010-05-06 08:58:33 +00009231 unsigned DiagID = diag::warn_impcast_integer_sign;
9232
9233 // Traditionally, gcc has warned about this under -Wsign-compare.
9234 // We also want to warn about it in -Wconversion.
9235 // So if -Wconversion is off, use a completely identical diagnostic
9236 // in the sign-compare group.
9237 // The conditional-checking code will
9238 if (ICContext) {
9239 DiagID = diag::warn_impcast_integer_sign_conditional;
9240 *ICContext = true;
9241 }
9242
John McCallacf0ee52010-10-08 02:01:28 +00009243 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00009244 }
9245
Douglas Gregora78f1932011-02-22 02:45:07 +00009246 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00009247 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9248 // type, to give us better diagnostics.
9249 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009250 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00009251 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9252 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9253 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9254 SourceType = S.Context.getTypeDeclType(Enum);
9255 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9256 }
9257 }
9258
Douglas Gregora78f1932011-02-22 02:45:07 +00009259 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9260 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00009261 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9262 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009263 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009264 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009265 return;
9266
Douglas Gregor364f7db2011-03-12 00:14:31 +00009267 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00009268 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009269 }
John McCall263a48b2010-01-04 23:31:57 +00009270}
9271
David Blaikie18e9ac72012-05-15 21:57:38 +00009272void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9273 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009274
9275void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00009276 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009277 E = E->IgnoreParenImpCasts();
9278
9279 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00009280 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009281
John McCallacf0ee52010-10-08 02:01:28 +00009282 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009283 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009284 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00009285}
9286
David Blaikie18e9ac72012-05-15 21:57:38 +00009287void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9288 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00009289 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009290
9291 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00009292 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9293 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009294
9295 // If -Wconversion would have warned about either of the candidates
9296 // for a signedness conversion to the context type...
9297 if (!Suspicious) return;
9298
9299 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009300 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00009301 return;
9302
John McCallcc7e5bf2010-05-06 08:58:33 +00009303 // ...then check whether it would have warned about either of the
9304 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00009305 if (E->getType() == T) return;
9306
9307 Suspicious = false;
9308 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9309 E->getType(), CC, &Suspicious);
9310 if (!Suspicious)
9311 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00009312 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009313}
9314
Richard Trieu65724892014-11-15 06:37:39 +00009315/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9316/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009317void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00009318 if (S.getLangOpts().Bool)
9319 return;
9320 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9321}
9322
John McCallcc7e5bf2010-05-06 08:58:33 +00009323/// AnalyzeImplicitConversions - Find and report any interesting
9324/// implicit conversions in the given expression. There are a couple
9325/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009326void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00009327 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00009328 Expr *E = OrigE->IgnoreParenImpCasts();
9329
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00009330 if (E->isTypeDependent() || E->isValueDependent())
9331 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00009332
John McCallcc7e5bf2010-05-06 08:58:33 +00009333 // For conditional operators, we analyze the arguments as if they
9334 // were being fed directly into the output.
9335 if (isa<ConditionalOperator>(E)) {
9336 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00009337 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009338 return;
9339 }
9340
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009341 // Check implicit argument conversions for function calls.
9342 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9343 CheckImplicitArgumentConversions(S, Call, CC);
9344
John McCallcc7e5bf2010-05-06 08:58:33 +00009345 // Go ahead and check any implicit conversions we might have skipped.
9346 // The non-canonical typecheck is just an optimization;
9347 // CheckImplicitConversion will filter out dead implicit conversions.
9348 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009349 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009350
9351 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00009352
9353 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9354 // The bound subexpressions in a PseudoObjectExpr are not reachable
9355 // as transitive children.
9356 // FIXME: Use a more uniform representation for this.
9357 for (auto *SE : POE->semantics())
9358 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9359 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00009360 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00009361
John McCallcc7e5bf2010-05-06 08:58:33 +00009362 // Skip past explicit casts.
9363 if (isa<ExplicitCastExpr>(E)) {
9364 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00009365 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009366 }
9367
John McCalld2a53122010-11-09 23:24:47 +00009368 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9369 // Do a somewhat different check with comparison operators.
9370 if (BO->isComparisonOp())
9371 return AnalyzeComparison(S, BO);
9372
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009373 // And with simple assignments.
9374 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00009375 return AnalyzeAssignment(S, BO);
9376 }
John McCallcc7e5bf2010-05-06 08:58:33 +00009377
9378 // These break the otherwise-useful invariant below. Fortunately,
9379 // we don't really need to recurse into them, because any internal
9380 // expressions should have been analyzed already when they were
9381 // built into statements.
9382 if (isa<StmtExpr>(E)) return;
9383
9384 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00009385 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00009386
9387 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00009388 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00009389 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00009390 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00009391 for (Stmt *SubStmt : E->children()) {
9392 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00009393 if (!ChildExpr)
9394 continue;
9395
Richard Trieu955231d2014-01-25 01:10:35 +00009396 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00009397 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00009398 // Ignore checking string literals that are in logical and operators.
9399 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00009400 continue;
9401 AnalyzeImplicitConversions(S, ChildExpr, CC);
9402 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009403
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009404 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00009405 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9406 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009407 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00009408
9409 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9410 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009411 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009412 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009413
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009414 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9415 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00009416 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009417}
9418
9419} // end anonymous namespace
9420
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009421/// Diagnose integer type and any valid implicit convertion to it.
9422static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9423 // Taking into account implicit conversions,
9424 // allow any integer.
9425 if (!E->getType()->isIntegerType()) {
9426 S.Diag(E->getLocStart(),
9427 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9428 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009429 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009430 // Potentially emit standard warnings for implicit conversions if enabled
9431 // using -Wconversion.
9432 CheckImplicitConversion(S, E, IntT, E->getLocStart());
9433 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009434}
9435
Richard Trieuc1888e02014-06-28 23:25:37 +00009436// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9437// Returns true when emitting a warning about taking the address of a reference.
9438static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00009439 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00009440 E = E->IgnoreParenImpCasts();
9441
9442 const FunctionDecl *FD = nullptr;
9443
9444 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9445 if (!DRE->getDecl()->getType()->isReferenceType())
9446 return false;
9447 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9448 if (!M->getMemberDecl()->getType()->isReferenceType())
9449 return false;
9450 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00009451 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00009452 return false;
9453 FD = Call->getDirectCallee();
9454 } else {
9455 return false;
9456 }
9457
9458 SemaRef.Diag(E->getExprLoc(), PD);
9459
9460 // If possible, point to location of function.
9461 if (FD) {
9462 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9463 }
9464
9465 return true;
9466}
9467
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009468// Returns true if the SourceLocation is expanded from any macro body.
9469// Returns false if the SourceLocation is invalid, is from not in a macro
9470// expansion, or is from expanded from a top-level macro argument.
9471static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9472 if (Loc.isInvalid())
9473 return false;
9474
9475 while (Loc.isMacroID()) {
9476 if (SM.isMacroBodyExpansion(Loc))
9477 return true;
9478 Loc = SM.getImmediateMacroCallerLoc(Loc);
9479 }
9480
9481 return false;
9482}
9483
Richard Trieu3bb8b562014-02-26 02:36:06 +00009484/// \brief Diagnose pointers that are always non-null.
9485/// \param E the expression containing the pointer
9486/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9487/// compared to a null pointer
9488/// \param IsEqual True when the comparison is equal to a null pointer
9489/// \param Range Extra SourceRange to highlight in the diagnostic
9490void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9491 Expr::NullPointerConstantKind NullKind,
9492 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00009493 if (!E)
9494 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009495
9496 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009497 if (E->getExprLoc().isMacroID()) {
9498 const SourceManager &SM = getSourceManager();
9499 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9500 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00009501 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009502 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009503 E = E->IgnoreImpCasts();
9504
9505 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9506
Richard Trieuf7432752014-06-06 21:39:26 +00009507 if (isa<CXXThisExpr>(E)) {
9508 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9509 : diag::warn_this_bool_conversion;
9510 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9511 return;
9512 }
9513
Richard Trieu3bb8b562014-02-26 02:36:06 +00009514 bool IsAddressOf = false;
9515
9516 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9517 if (UO->getOpcode() != UO_AddrOf)
9518 return;
9519 IsAddressOf = true;
9520 E = UO->getSubExpr();
9521 }
9522
Richard Trieuc1888e02014-06-28 23:25:37 +00009523 if (IsAddressOf) {
9524 unsigned DiagID = IsCompare
9525 ? diag::warn_address_of_reference_null_compare
9526 : diag::warn_address_of_reference_bool_conversion;
9527 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9528 << IsEqual;
9529 if (CheckForReference(*this, E, PD)) {
9530 return;
9531 }
9532 }
9533
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009534 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9535 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00009536 std::string Str;
9537 llvm::raw_string_ostream S(Str);
9538 E->printPretty(S, nullptr, getPrintingPolicy());
9539 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9540 : diag::warn_cast_nonnull_to_bool;
9541 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9542 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009543 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00009544 };
9545
9546 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9547 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9548 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009549 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9550 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009551 return;
9552 }
9553 }
9554 }
9555
Richard Trieu3bb8b562014-02-26 02:36:06 +00009556 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00009557 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009558 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9559 D = R->getDecl();
9560 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9561 D = M->getMemberDecl();
9562 }
9563
9564 // Weak Decls can be null.
9565 if (!D || D->isWeak())
9566 return;
George Burgess IV850269a2015-12-08 22:02:00 +00009567
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009568 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00009569 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9570 if (getCurFunction() &&
9571 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009572 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9573 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009574 return;
9575 }
9576
9577 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +00009578 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +00009579 assert(ParamIter != FD->param_end());
9580 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9581
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009582 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9583 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009584 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +00009585 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009586 }
George Burgess IV850269a2015-12-08 22:02:00 +00009587
9588 for (unsigned ArgNo : NonNull->args()) {
9589 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009590 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009591 return;
9592 }
George Burgess IV850269a2015-12-08 22:02:00 +00009593 }
9594 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009595 }
9596 }
George Burgess IV850269a2015-12-08 22:02:00 +00009597 }
9598
Richard Trieu3bb8b562014-02-26 02:36:06 +00009599 QualType T = D->getType();
9600 const bool IsArray = T->isArrayType();
9601 const bool IsFunction = T->isFunctionType();
9602
Richard Trieuc1888e02014-06-28 23:25:37 +00009603 // Address of function is used to silence the function warning.
9604 if (IsAddressOf && IsFunction) {
9605 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009606 }
9607
9608 // Found nothing.
9609 if (!IsAddressOf && !IsFunction && !IsArray)
9610 return;
9611
9612 // Pretty print the expression for the diagnostic.
9613 std::string Str;
9614 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00009615 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00009616
9617 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9618 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00009619 enum {
9620 AddressOf,
9621 FunctionPointer,
9622 ArrayPointer
9623 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009624 if (IsAddressOf)
9625 DiagType = AddressOf;
9626 else if (IsFunction)
9627 DiagType = FunctionPointer;
9628 else if (IsArray)
9629 DiagType = ArrayPointer;
9630 else
9631 llvm_unreachable("Could not determine diagnostic.");
9632 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9633 << Range << IsEqual;
9634
9635 if (!IsFunction)
9636 return;
9637
9638 // Suggest '&' to silence the function warning.
9639 Diag(E->getExprLoc(), diag::note_function_warning_silence)
9640 << FixItHint::CreateInsertion(E->getLocStart(), "&");
9641
9642 // Check to see if '()' fixit should be emitted.
9643 QualType ReturnType;
9644 UnresolvedSet<4> NonTemplateOverloads;
9645 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9646 if (ReturnType.isNull())
9647 return;
9648
9649 if (IsCompare) {
9650 // There are two cases here. If there is null constant, the only suggest
9651 // for a pointer return type. If the null is 0, then suggest if the return
9652 // type is a pointer or an integer type.
9653 if (!ReturnType->isPointerType()) {
9654 if (NullKind == Expr::NPCK_ZeroExpression ||
9655 NullKind == Expr::NPCK_ZeroLiteral) {
9656 if (!ReturnType->isIntegerType())
9657 return;
9658 } else {
9659 return;
9660 }
9661 }
9662 } else { // !IsCompare
9663 // For function to bool, only suggest if the function pointer has bool
9664 // return type.
9665 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9666 return;
9667 }
9668 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00009669 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00009670}
9671
John McCallcc7e5bf2010-05-06 08:58:33 +00009672/// Diagnoses "dangerous" implicit conversions within the given
9673/// expression (which is a full expression). Implements -Wconversion
9674/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009675///
9676/// \param CC the "context" location of the implicit conversion, i.e.
9677/// the most location of the syntactic entity requiring the implicit
9678/// conversion
9679void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009680 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00009681 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00009682 return;
9683
9684 // Don't diagnose for value- or type-dependent expressions.
9685 if (E->isTypeDependent() || E->isValueDependent())
9686 return;
9687
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009688 // Check for array bounds violations in cases where the check isn't triggered
9689 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9690 // ArraySubscriptExpr is on the RHS of a variable initialization.
9691 CheckArrayAccess(E);
9692
John McCallacf0ee52010-10-08 02:01:28 +00009693 // This is not the right CC for (e.g.) a variable initialization.
9694 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009695}
9696
Richard Trieu65724892014-11-15 06:37:39 +00009697/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9698/// Input argument E is a logical expression.
9699void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9700 ::CheckBoolLikeConversion(*this, E, CC);
9701}
9702
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009703/// Diagnose when expression is an integer constant expression and its evaluation
9704/// results in integer overflow
9705void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00009706 // Use a work list to deal with nested struct initializers.
9707 SmallVector<Expr *, 2> Exprs(1, E);
9708
9709 do {
9710 Expr *E = Exprs.pop_back_val();
9711
9712 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9713 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9714 continue;
9715 }
9716
9717 if (auto InitList = dyn_cast<InitListExpr>(E))
9718 Exprs.append(InitList->inits().begin(), InitList->inits().end());
9719 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009720}
9721
Richard Smithc406cb72013-01-17 01:17:56 +00009722namespace {
9723/// \brief Visitor for expressions which looks for unsequenced operations on the
9724/// same object.
9725class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009726 typedef EvaluatedExprVisitor<SequenceChecker> Base;
9727
Richard Smithc406cb72013-01-17 01:17:56 +00009728 /// \brief A tree of sequenced regions within an expression. Two regions are
9729 /// unsequenced if one is an ancestor or a descendent of the other. When we
9730 /// finish processing an expression with sequencing, such as a comma
9731 /// expression, we fold its tree nodes into its parent, since they are
9732 /// unsequenced with respect to nodes we will visit later.
9733 class SequenceTree {
9734 struct Value {
9735 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9736 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +00009737 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +00009738 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009739 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00009740
9741 public:
9742 /// \brief A region within an expression which may be sequenced with respect
9743 /// to some other region.
9744 class Seq {
9745 explicit Seq(unsigned N) : Index(N) {}
9746 unsigned Index;
9747 friend class SequenceTree;
9748 public:
9749 Seq() : Index(0) {}
9750 };
9751
9752 SequenceTree() { Values.push_back(Value(0)); }
9753 Seq root() const { return Seq(0); }
9754
9755 /// \brief Create a new sequence of operations, which is an unsequenced
9756 /// subset of \p Parent. This sequence of operations is sequenced with
9757 /// respect to other children of \p Parent.
9758 Seq allocate(Seq Parent) {
9759 Values.push_back(Value(Parent.Index));
9760 return Seq(Values.size() - 1);
9761 }
9762
9763 /// \brief Merge a sequence of operations into its parent.
9764 void merge(Seq S) {
9765 Values[S.Index].Merged = true;
9766 }
9767
9768 /// \brief Determine whether two operations are unsequenced. This operation
9769 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9770 /// should have been merged into its parent as appropriate.
9771 bool isUnsequenced(Seq Cur, Seq Old) {
9772 unsigned C = representative(Cur.Index);
9773 unsigned Target = representative(Old.Index);
9774 while (C >= Target) {
9775 if (C == Target)
9776 return true;
9777 C = Values[C].Parent;
9778 }
9779 return false;
9780 }
9781
9782 private:
9783 /// \brief Pick a representative for a sequence.
9784 unsigned representative(unsigned K) {
9785 if (Values[K].Merged)
9786 // Perform path compression as we go.
9787 return Values[K].Parent = representative(Values[K].Parent);
9788 return K;
9789 }
9790 };
9791
9792 /// An object for which we can track unsequenced uses.
9793 typedef NamedDecl *Object;
9794
9795 /// Different flavors of object usage which we track. We only track the
9796 /// least-sequenced usage of each kind.
9797 enum UsageKind {
9798 /// A read of an object. Multiple unsequenced reads are OK.
9799 UK_Use,
9800 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00009801 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00009802 UK_ModAsValue,
9803 /// A modification of an object which is not sequenced before the value
9804 /// computation of the expression, such as n++.
9805 UK_ModAsSideEffect,
9806
9807 UK_Count = UK_ModAsSideEffect + 1
9808 };
9809
9810 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00009811 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00009812 Expr *Use;
9813 SequenceTree::Seq Seq;
9814 };
9815
9816 struct UsageInfo {
9817 UsageInfo() : Diagnosed(false) {}
9818 Usage Uses[UK_Count];
9819 /// Have we issued a diagnostic for this variable already?
9820 bool Diagnosed;
9821 };
9822 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9823
9824 Sema &SemaRef;
9825 /// Sequenced regions within the expression.
9826 SequenceTree Tree;
9827 /// Declaration modifications and references which we have seen.
9828 UsageInfoMap UsageMap;
9829 /// The region we are currently within.
9830 SequenceTree::Seq Region;
9831 /// Filled in with declarations which were modified as a side-effect
9832 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009833 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00009834 /// Expressions to check later. We defer checking these to reduce
9835 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009836 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00009837
9838 /// RAII object wrapping the visitation of a sequenced subexpression of an
9839 /// expression. At the end of this process, the side-effects of the evaluation
9840 /// become sequenced with respect to the value computation of the result, so
9841 /// we downgrade any UK_ModAsSideEffect within the evaluation to
9842 /// UK_ModAsValue.
9843 struct SequencedSubexpression {
9844 SequencedSubexpression(SequenceChecker &Self)
9845 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9846 Self.ModAsSideEffect = &ModAsSideEffect;
9847 }
9848 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +00009849 for (auto &M : llvm::reverse(ModAsSideEffect)) {
9850 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +00009851 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +00009852 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9853 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +00009854 }
9855 Self.ModAsSideEffect = OldModAsSideEffect;
9856 }
9857
9858 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009859 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9860 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00009861 };
9862
Richard Smith40238f02013-06-20 22:21:56 +00009863 /// RAII object wrapping the visitation of a subexpression which we might
9864 /// choose to evaluate as a constant. If any subexpression is evaluated and
9865 /// found to be non-constant, this allows us to suppress the evaluation of
9866 /// the outer expression.
9867 class EvaluationTracker {
9868 public:
9869 EvaluationTracker(SequenceChecker &Self)
9870 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9871 Self.EvalTracker = this;
9872 }
9873 ~EvaluationTracker() {
9874 Self.EvalTracker = Prev;
9875 if (Prev)
9876 Prev->EvalOK &= EvalOK;
9877 }
9878
9879 bool evaluate(const Expr *E, bool &Result) {
9880 if (!EvalOK || E->isValueDependent())
9881 return false;
9882 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9883 return EvalOK;
9884 }
9885
9886 private:
9887 SequenceChecker &Self;
9888 EvaluationTracker *Prev;
9889 bool EvalOK;
9890 } *EvalTracker;
9891
Richard Smithc406cb72013-01-17 01:17:56 +00009892 /// \brief Find the object which is produced by the specified expression,
9893 /// if any.
9894 Object getObject(Expr *E, bool Mod) const {
9895 E = E->IgnoreParenCasts();
9896 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9897 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9898 return getObject(UO->getSubExpr(), Mod);
9899 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9900 if (BO->getOpcode() == BO_Comma)
9901 return getObject(BO->getRHS(), Mod);
9902 if (Mod && BO->isAssignmentOp())
9903 return getObject(BO->getLHS(), Mod);
9904 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9905 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9906 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9907 return ME->getMemberDecl();
9908 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9909 // FIXME: If this is a reference, map through to its value.
9910 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00009911 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00009912 }
9913
9914 /// \brief Note that an object was modified or used by an expression.
9915 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9916 Usage &U = UI.Uses[UK];
9917 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9918 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9919 ModAsSideEffect->push_back(std::make_pair(O, U));
9920 U.Use = Ref;
9921 U.Seq = Region;
9922 }
9923 }
9924 /// \brief Check whether a modification or use conflicts with a prior usage.
9925 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9926 bool IsModMod) {
9927 if (UI.Diagnosed)
9928 return;
9929
9930 const Usage &U = UI.Uses[OtherKind];
9931 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9932 return;
9933
9934 Expr *Mod = U.Use;
9935 Expr *ModOrUse = Ref;
9936 if (OtherKind == UK_Use)
9937 std::swap(Mod, ModOrUse);
9938
9939 SemaRef.Diag(Mod->getExprLoc(),
9940 IsModMod ? diag::warn_unsequenced_mod_mod
9941 : diag::warn_unsequenced_mod_use)
9942 << O << SourceRange(ModOrUse->getExprLoc());
9943 UI.Diagnosed = true;
9944 }
9945
9946 void notePreUse(Object O, Expr *Use) {
9947 UsageInfo &U = UsageMap[O];
9948 // Uses conflict with other modifications.
9949 checkUsage(O, U, Use, UK_ModAsValue, false);
9950 }
9951 void notePostUse(Object O, Expr *Use) {
9952 UsageInfo &U = UsageMap[O];
9953 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9954 addUsage(U, O, Use, UK_Use);
9955 }
9956
9957 void notePreMod(Object O, Expr *Mod) {
9958 UsageInfo &U = UsageMap[O];
9959 // Modifications conflict with other modifications and with uses.
9960 checkUsage(O, U, Mod, UK_ModAsValue, true);
9961 checkUsage(O, U, Mod, UK_Use, false);
9962 }
9963 void notePostMod(Object O, Expr *Use, UsageKind UK) {
9964 UsageInfo &U = UsageMap[O];
9965 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9966 addUsage(U, O, Use, UK);
9967 }
9968
9969public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009970 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00009971 : Base(S.Context), SemaRef(S), Region(Tree.root()),
9972 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009973 Visit(E);
9974 }
9975
9976 void VisitStmt(Stmt *S) {
9977 // Skip all statements which aren't expressions for now.
9978 }
9979
9980 void VisitExpr(Expr *E) {
9981 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00009982 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00009983 }
9984
9985 void VisitCastExpr(CastExpr *E) {
9986 Object O = Object();
9987 if (E->getCastKind() == CK_LValueToRValue)
9988 O = getObject(E->getSubExpr(), false);
9989
9990 if (O)
9991 notePreUse(O, E);
9992 VisitExpr(E);
9993 if (O)
9994 notePostUse(O, E);
9995 }
9996
9997 void VisitBinComma(BinaryOperator *BO) {
9998 // C++11 [expr.comma]p1:
9999 // Every value computation and side effect associated with the left
10000 // expression is sequenced before every value computation and side
10001 // effect associated with the right expression.
10002 SequenceTree::Seq LHS = Tree.allocate(Region);
10003 SequenceTree::Seq RHS = Tree.allocate(Region);
10004 SequenceTree::Seq OldRegion = Region;
10005
10006 {
10007 SequencedSubexpression SeqLHS(*this);
10008 Region = LHS;
10009 Visit(BO->getLHS());
10010 }
10011
10012 Region = RHS;
10013 Visit(BO->getRHS());
10014
10015 Region = OldRegion;
10016
10017 // Forget that LHS and RHS are sequenced. They are both unsequenced
10018 // with respect to other stuff.
10019 Tree.merge(LHS);
10020 Tree.merge(RHS);
10021 }
10022
10023 void VisitBinAssign(BinaryOperator *BO) {
10024 // The modification is sequenced after the value computation of the LHS
10025 // and RHS, so check it before inspecting the operands and update the
10026 // map afterwards.
10027 Object O = getObject(BO->getLHS(), true);
10028 if (!O)
10029 return VisitExpr(BO);
10030
10031 notePreMod(O, BO);
10032
10033 // C++11 [expr.ass]p7:
10034 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10035 // only once.
10036 //
10037 // Therefore, for a compound assignment operator, O is considered used
10038 // everywhere except within the evaluation of E1 itself.
10039 if (isa<CompoundAssignOperator>(BO))
10040 notePreUse(O, BO);
10041
10042 Visit(BO->getLHS());
10043
10044 if (isa<CompoundAssignOperator>(BO))
10045 notePostUse(O, BO);
10046
10047 Visit(BO->getRHS());
10048
Richard Smith83e37bee2013-06-26 23:16:51 +000010049 // C++11 [expr.ass]p1:
10050 // the assignment is sequenced [...] before the value computation of the
10051 // assignment expression.
10052 // C11 6.5.16/3 has no such rule.
10053 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10054 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010055 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010056
Richard Smithc406cb72013-01-17 01:17:56 +000010057 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10058 VisitBinAssign(CAO);
10059 }
10060
10061 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10062 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10063 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10064 Object O = getObject(UO->getSubExpr(), true);
10065 if (!O)
10066 return VisitExpr(UO);
10067
10068 notePreMod(O, UO);
10069 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000010070 // C++11 [expr.pre.incr]p1:
10071 // the expression ++x is equivalent to x+=1
10072 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10073 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010074 }
10075
10076 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10077 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10078 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10079 Object O = getObject(UO->getSubExpr(), true);
10080 if (!O)
10081 return VisitExpr(UO);
10082
10083 notePreMod(O, UO);
10084 Visit(UO->getSubExpr());
10085 notePostMod(O, UO, UK_ModAsSideEffect);
10086 }
10087
10088 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10089 void VisitBinLOr(BinaryOperator *BO) {
10090 // The side-effects of the LHS of an '&&' are sequenced before the
10091 // value computation of the RHS, and hence before the value computation
10092 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10093 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000010094 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010095 {
10096 SequencedSubexpression Sequenced(*this);
10097 Visit(BO->getLHS());
10098 }
10099
10100 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010101 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010102 if (!Result)
10103 Visit(BO->getRHS());
10104 } else {
10105 // Check for unsequenced operations in the RHS, treating it as an
10106 // entirely separate evaluation.
10107 //
10108 // FIXME: If there are operations in the RHS which are unsequenced
10109 // with respect to operations outside the RHS, and those operations
10110 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000010111 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010112 }
Richard Smithc406cb72013-01-17 01:17:56 +000010113 }
10114 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000010115 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010116 {
10117 SequencedSubexpression Sequenced(*this);
10118 Visit(BO->getLHS());
10119 }
10120
10121 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010122 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010123 if (Result)
10124 Visit(BO->getRHS());
10125 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000010126 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010127 }
Richard Smithc406cb72013-01-17 01:17:56 +000010128 }
10129
10130 // Only visit the condition, unless we can be sure which subexpression will
10131 // be chosen.
10132 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000010133 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000010134 {
10135 SequencedSubexpression Sequenced(*this);
10136 Visit(CO->getCond());
10137 }
Richard Smithc406cb72013-01-17 01:17:56 +000010138
10139 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010140 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000010141 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010142 else {
Richard Smithd33f5202013-01-17 23:18:09 +000010143 WorkList.push_back(CO->getTrueExpr());
10144 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010145 }
Richard Smithc406cb72013-01-17 01:17:56 +000010146 }
10147
Richard Smithe3dbfe02013-06-30 10:40:20 +000010148 void VisitCallExpr(CallExpr *CE) {
10149 // C++11 [intro.execution]p15:
10150 // When calling a function [...], every value computation and side effect
10151 // associated with any argument expression, or with the postfix expression
10152 // designating the called function, is sequenced before execution of every
10153 // expression or statement in the body of the function [and thus before
10154 // the value computation of its result].
10155 SequencedSubexpression Sequenced(*this);
10156 Base::VisitCallExpr(CE);
10157
10158 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10159 }
10160
Richard Smithc406cb72013-01-17 01:17:56 +000010161 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010162 // This is a call, so all subexpressions are sequenced before the result.
10163 SequencedSubexpression Sequenced(*this);
10164
Richard Smithc406cb72013-01-17 01:17:56 +000010165 if (!CCE->isListInitialization())
10166 return VisitExpr(CCE);
10167
10168 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010169 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010170 SequenceTree::Seq Parent = Region;
10171 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10172 E = CCE->arg_end();
10173 I != E; ++I) {
10174 Region = Tree.allocate(Parent);
10175 Elts.push_back(Region);
10176 Visit(*I);
10177 }
10178
10179 // Forget that the initializers are sequenced.
10180 Region = Parent;
10181 for (unsigned I = 0; I < Elts.size(); ++I)
10182 Tree.merge(Elts[I]);
10183 }
10184
10185 void VisitInitListExpr(InitListExpr *ILE) {
10186 if (!SemaRef.getLangOpts().CPlusPlus11)
10187 return VisitExpr(ILE);
10188
10189 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010190 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010191 SequenceTree::Seq Parent = Region;
10192 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10193 Expr *E = ILE->getInit(I);
10194 if (!E) continue;
10195 Region = Tree.allocate(Parent);
10196 Elts.push_back(Region);
10197 Visit(E);
10198 }
10199
10200 // Forget that the initializers are sequenced.
10201 Region = Parent;
10202 for (unsigned I = 0; I < Elts.size(); ++I)
10203 Tree.merge(Elts[I]);
10204 }
10205};
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010206} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +000010207
10208void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010209 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000010210 WorkList.push_back(E);
10211 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000010212 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000010213 SequenceChecker(*this, Item, WorkList);
10214 }
Richard Smithc406cb72013-01-17 01:17:56 +000010215}
10216
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010217void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10218 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010219 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000010220 if (!E->isInstantiationDependent())
10221 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010222 if (!IsConstexpr && !E->isValueDependent())
10223 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010224 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000010225}
10226
John McCall1f425642010-11-11 03:21:53 +000010227void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10228 FieldDecl *BitField,
10229 Expr *Init) {
10230 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10231}
10232
David Majnemer61a5bbf2015-04-07 22:08:51 +000010233static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10234 SourceLocation Loc) {
10235 if (!PType->isVariablyModifiedType())
10236 return;
10237 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10238 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10239 return;
10240 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000010241 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10242 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10243 return;
10244 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000010245 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10246 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10247 return;
10248 }
10249
10250 const ArrayType *AT = S.Context.getAsArrayType(PType);
10251 if (!AT)
10252 return;
10253
10254 if (AT->getSizeModifier() != ArrayType::Star) {
10255 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10256 return;
10257 }
10258
10259 S.Diag(Loc, diag::err_array_star_in_function_definition);
10260}
10261
Mike Stump0c2ec772010-01-21 03:59:47 +000010262/// CheckParmsForFunctionDef - Check that the parameters of the given
10263/// function are appropriate for the definition of a function. This
10264/// takes care of any checks that cannot be performed on the
10265/// declaration itself, e.g., that the types of each of the function
10266/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000010267bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000010268 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010269 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000010270 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010271 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10272 // function declarator that is part of a function definition of
10273 // that function shall not have incomplete type.
10274 //
10275 // This is also C++ [dcl.fct]p6.
10276 if (!Param->isInvalidDecl() &&
10277 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010278 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010279 Param->setInvalidDecl();
10280 HasInvalidParm = true;
10281 }
10282
10283 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10284 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000010285 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000010286 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000010287 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000010288 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000010289 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000010290
10291 // C99 6.7.5.3p12:
10292 // If the function declarator is not part of a definition of that
10293 // function, parameters may have incomplete type and may use the [*]
10294 // notation in their sequences of declarator specifiers to specify
10295 // variable length array types.
10296 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000010297 // FIXME: This diagnostic should point the '[*]' if source-location
10298 // information is added for it.
10299 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010300
10301 // MSVC destroys objects passed by value in the callee. Therefore a
10302 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010303 // object's destructor. However, we don't perform any direct access check
10304 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +000010305 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10306 .getCXXABI()
10307 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +000010308 if (!Param->isInvalidDecl()) {
10309 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10310 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10311 if (!ClassDecl->isInvalidDecl() &&
10312 !ClassDecl->hasIrrelevantDestructor() &&
10313 !ClassDecl->isDependentContext()) {
10314 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10315 MarkFunctionReferenced(Param->getLocation(), Destructor);
10316 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10317 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010318 }
10319 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010320 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010321
10322 // Parameters with the pass_object_size attribute only need to be marked
10323 // constant at function definitions. Because we lack information about
10324 // whether we're on a declaration or definition when we're instantiating the
10325 // attribute, we need to check for constness here.
10326 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10327 if (!Param->getType().isConstQualified())
10328 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10329 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000010330 }
10331
10332 return HasInvalidParm;
10333}
John McCall2b5c1b22010-08-12 21:44:57 +000010334
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010335/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10336/// or MemberExpr.
10337static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10338 ASTContext &Context) {
10339 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10340 return Context.getDeclAlign(DRE->getDecl());
10341
10342 if (const auto *ME = dyn_cast<MemberExpr>(E))
10343 return Context.getDeclAlign(ME->getMemberDecl());
10344
10345 return TypeAlign;
10346}
10347
John McCall2b5c1b22010-08-12 21:44:57 +000010348/// CheckCastAlign - Implements -Wcast-align, which warns when a
10349/// pointer cast increases the alignment requirements.
10350void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10351 // This is actually a lot of work to potentially be doing on every
10352 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010353 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000010354 return;
10355
10356 // Ignore dependent types.
10357 if (T->isDependentType() || Op->getType()->isDependentType())
10358 return;
10359
10360 // Require that the destination be a pointer type.
10361 const PointerType *DestPtr = T->getAs<PointerType>();
10362 if (!DestPtr) return;
10363
10364 // If the destination has alignment 1, we're done.
10365 QualType DestPointee = DestPtr->getPointeeType();
10366 if (DestPointee->isIncompleteType()) return;
10367 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10368 if (DestAlign.isOne()) return;
10369
10370 // Require that the source be a pointer type.
10371 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10372 if (!SrcPtr) return;
10373 QualType SrcPointee = SrcPtr->getPointeeType();
10374
10375 // Whitelist casts from cv void*. We already implicitly
10376 // whitelisted casts to cv void*, since they have alignment 1.
10377 // Also whitelist casts involving incomplete types, which implicitly
10378 // includes 'void'.
10379 if (SrcPointee->isIncompleteType()) return;
10380
10381 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010382
10383 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10384 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10385 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10386 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10387 if (UO->getOpcode() == UO_AddrOf)
10388 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10389 }
10390
John McCall2b5c1b22010-08-12 21:44:57 +000010391 if (SrcAlign >= DestAlign) return;
10392
10393 Diag(TRange.getBegin(), diag::warn_cast_align)
10394 << Op->getType() << T
10395 << static_cast<unsigned>(SrcAlign.getQuantity())
10396 << static_cast<unsigned>(DestAlign.getQuantity())
10397 << TRange << Op->getSourceRange();
10398}
10399
Chandler Carruth28389f02011-08-05 09:10:50 +000010400/// \brief Check whether this array fits the idiom of a size-one tail padded
10401/// array member of a struct.
10402///
10403/// We avoid emitting out-of-bounds access warnings for such arrays as they are
10404/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000010405static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000010406 const NamedDecl *ND) {
10407 if (Size != 1 || !ND) return false;
10408
10409 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10410 if (!FD) return false;
10411
10412 // Don't consider sizes resulting from macro expansions or template argument
10413 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000010414
10415 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010416 while (TInfo) {
10417 TypeLoc TL = TInfo->getTypeLoc();
10418 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000010419 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10420 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010421 TInfo = TDL->getTypeSourceInfo();
10422 continue;
10423 }
David Blaikie6adc78e2013-02-18 22:06:02 +000010424 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10425 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000010426 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10427 return false;
10428 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010429 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000010430 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010431
10432 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000010433 if (!RD) return false;
10434 if (RD->isUnion()) return false;
10435 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10436 if (!CRD->isStandardLayout()) return false;
10437 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010438
Benjamin Kramer8c543672011-08-06 03:04:42 +000010439 // See if this is the last field decl in the record.
10440 const Decl *D = FD;
10441 while ((D = D->getNextDeclInContext()))
10442 if (isa<FieldDecl>(D))
10443 return false;
10444 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000010445}
10446
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010447void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010448 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000010449 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010450 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010451 if (IndexExpr->isValueDependent())
10452 return;
10453
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010454 const Type *EffectiveType =
10455 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010456 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010457 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010458 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010459 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000010460 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000010461
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010462 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000010463 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000010464 return;
Richard Smith13f67182011-12-16 19:31:14 +000010465 if (IndexNegated)
10466 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000010467
Craig Topperc3ec1492014-05-26 06:22:03 +000010468 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000010469 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10470 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +000010471 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +000010472 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +000010473
Ted Kremeneke4b316c2011-02-23 23:06:04 +000010474 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010475 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000010476 if (!size.isStrictlyPositive())
10477 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010478
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010479 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000010480 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010481 // Make sure we're comparing apples to apples when comparing index to size
10482 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10483 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000010484 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000010485 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010486 if (ptrarith_typesize != array_typesize) {
10487 // There's a cast to a different size type involved
10488 uint64_t ratio = array_typesize / ptrarith_typesize;
10489 // TODO: Be smarter about handling cases where array_typesize is not a
10490 // multiple of ptrarith_typesize
10491 if (ptrarith_typesize * ratio == array_typesize)
10492 size *= llvm::APInt(size.getBitWidth(), ratio);
10493 }
10494 }
10495
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010496 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010497 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010498 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010499 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010500
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010501 // For array subscripting the index must be less than size, but for pointer
10502 // arithmetic also allow the index (offset) to be equal to size since
10503 // computing the next address after the end of the array is legal and
10504 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010505 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000010506 return;
10507
10508 // Also don't warn for arrays of size 1 which are members of some
10509 // structure. These are often used to approximate flexible arrays in C89
10510 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010511 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000010512 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010513
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010514 // Suppress the warning if the subscript expression (as identified by the
10515 // ']' location) and the index expression are both from macro expansions
10516 // within a system header.
10517 if (ASE) {
10518 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10519 ASE->getRBracketLoc());
10520 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10521 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10522 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000010523 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010524 return;
10525 }
10526 }
10527
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010528 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010529 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010530 DiagID = diag::warn_array_index_exceeds_bounds;
10531
10532 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10533 PDiag(DiagID) << index.toString(10, true)
10534 << size.toString(10, true)
10535 << (unsigned)size.getLimitedValue(~0U)
10536 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010537 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010538 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010539 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010540 DiagID = diag::warn_ptr_arith_precedes_bounds;
10541 if (index.isNegative()) index = -index;
10542 }
10543
10544 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10545 PDiag(DiagID) << index.toString(10, true)
10546 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000010547 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000010548
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000010549 if (!ND) {
10550 // Try harder to find a NamedDecl to point at in the note.
10551 while (const ArraySubscriptExpr *ASE =
10552 dyn_cast<ArraySubscriptExpr>(BaseExpr))
10553 BaseExpr = ASE->getBase()->IgnoreParenCasts();
10554 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10555 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10556 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10557 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10558 }
10559
Chandler Carruth1af88f12011-02-17 21:10:52 +000010560 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010561 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10562 PDiag(diag::note_array_index_out_of_bounds)
10563 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000010564}
10565
Ted Kremenekdf26df72011-03-01 18:41:00 +000010566void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010567 int AllowOnePastEnd = 0;
10568 while (expr) {
10569 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000010570 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010571 case Stmt::ArraySubscriptExprClass: {
10572 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010573 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010574 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +000010575 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010576 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010577 case Stmt::OMPArraySectionExprClass: {
10578 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10579 if (ASE->getLowerBound())
10580 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10581 /*ASE=*/nullptr, AllowOnePastEnd > 0);
10582 return;
10583 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010584 case Stmt::UnaryOperatorClass: {
10585 // Only unwrap the * and & unary operators
10586 const UnaryOperator *UO = cast<UnaryOperator>(expr);
10587 expr = UO->getSubExpr();
10588 switch (UO->getOpcode()) {
10589 case UO_AddrOf:
10590 AllowOnePastEnd++;
10591 break;
10592 case UO_Deref:
10593 AllowOnePastEnd--;
10594 break;
10595 default:
10596 return;
10597 }
10598 break;
10599 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010600 case Stmt::ConditionalOperatorClass: {
10601 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10602 if (const Expr *lhs = cond->getLHS())
10603 CheckArrayAccess(lhs);
10604 if (const Expr *rhs = cond->getRHS())
10605 CheckArrayAccess(rhs);
10606 return;
10607 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000010608 case Stmt::CXXOperatorCallExprClass: {
10609 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
10610 for (const auto *Arg : OCE->arguments())
10611 CheckArrayAccess(Arg);
10612 return;
10613 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010614 default:
10615 return;
10616 }
Peter Collingbourne91147592011-04-15 00:35:48 +000010617 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010618}
John McCall31168b02011-06-15 23:02:42 +000010619
10620//===--- CHECK: Objective-C retain cycles ----------------------------------//
10621
10622namespace {
10623 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +000010624 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +000010625 VarDecl *Variable;
10626 SourceRange Range;
10627 SourceLocation Loc;
10628 bool Indirect;
10629
10630 void setLocsFrom(Expr *e) {
10631 Loc = e->getExprLoc();
10632 Range = e->getSourceRange();
10633 }
10634 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010635} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010636
10637/// Consider whether capturing the given variable can possibly lead to
10638/// a retain cycle.
10639static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010640 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000010641 // lifetime. In MRR, it's captured strongly if the variable is
10642 // __block and has an appropriate type.
10643 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10644 return false;
10645
10646 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010647 if (ref)
10648 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000010649 return true;
10650}
10651
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010652static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000010653 while (true) {
10654 e = e->IgnoreParens();
10655 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10656 switch (cast->getCastKind()) {
10657 case CK_BitCast:
10658 case CK_LValueBitCast:
10659 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000010660 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000010661 e = cast->getSubExpr();
10662 continue;
10663
John McCall31168b02011-06-15 23:02:42 +000010664 default:
10665 return false;
10666 }
10667 }
10668
10669 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10670 ObjCIvarDecl *ivar = ref->getDecl();
10671 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10672 return false;
10673
10674 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010675 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000010676 return false;
10677
10678 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10679 owner.Indirect = true;
10680 return true;
10681 }
10682
10683 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10684 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10685 if (!var) return false;
10686 return considerVariable(var, ref, owner);
10687 }
10688
John McCall31168b02011-06-15 23:02:42 +000010689 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10690 if (member->isArrow()) return false;
10691
10692 // Don't count this as an indirect ownership.
10693 e = member->getBase();
10694 continue;
10695 }
10696
John McCallfe96e0b2011-11-06 09:01:30 +000010697 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10698 // Only pay attention to pseudo-objects on property references.
10699 ObjCPropertyRefExpr *pre
10700 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10701 ->IgnoreParens());
10702 if (!pre) return false;
10703 if (pre->isImplicitProperty()) return false;
10704 ObjCPropertyDecl *property = pre->getExplicitProperty();
10705 if (!property->isRetaining() &&
10706 !(property->getPropertyIvarDecl() &&
10707 property->getPropertyIvarDecl()->getType()
10708 .getObjCLifetime() == Qualifiers::OCL_Strong))
10709 return false;
10710
10711 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010712 if (pre->isSuperReceiver()) {
10713 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10714 if (!owner.Variable)
10715 return false;
10716 owner.Loc = pre->getLocation();
10717 owner.Range = pre->getSourceRange();
10718 return true;
10719 }
John McCallfe96e0b2011-11-06 09:01:30 +000010720 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10721 ->getSourceExpr());
10722 continue;
10723 }
10724
John McCall31168b02011-06-15 23:02:42 +000010725 // Array ivars?
10726
10727 return false;
10728 }
10729}
10730
10731namespace {
10732 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10733 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10734 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010735 Context(Context), Variable(variable), Capturer(nullptr),
10736 VarWillBeReased(false) {}
10737 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000010738 VarDecl *Variable;
10739 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010740 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +000010741
10742 void VisitDeclRefExpr(DeclRefExpr *ref) {
10743 if (ref->getDecl() == Variable && !Capturer)
10744 Capturer = ref;
10745 }
10746
John McCall31168b02011-06-15 23:02:42 +000010747 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10748 if (Capturer) return;
10749 Visit(ref->getBase());
10750 if (Capturer && ref->isFreeIvar())
10751 Capturer = ref;
10752 }
10753
10754 void VisitBlockExpr(BlockExpr *block) {
10755 // Look inside nested blocks
10756 if (block->getBlockDecl()->capturesVariable(Variable))
10757 Visit(block->getBlockDecl()->getBody());
10758 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000010759
10760 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
10761 if (Capturer) return;
10762 if (OVE->getSourceExpr())
10763 Visit(OVE->getSourceExpr());
10764 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010765 void VisitBinaryOperator(BinaryOperator *BinOp) {
10766 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
10767 return;
10768 Expr *LHS = BinOp->getLHS();
10769 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
10770 if (DRE->getDecl() != Variable)
10771 return;
10772 if (Expr *RHS = BinOp->getRHS()) {
10773 RHS = RHS->IgnoreParenCasts();
10774 llvm::APSInt Value;
10775 VarWillBeReased =
10776 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
10777 }
10778 }
10779 }
John McCall31168b02011-06-15 23:02:42 +000010780 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010781} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010782
10783/// Check whether the given argument is a block which captures a
10784/// variable.
10785static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
10786 assert(owner.Variable && owner.Loc.isValid());
10787
10788 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000010789
10790 // Look through [^{...} copy] and Block_copy(^{...}).
10791 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
10792 Selector Cmd = ME->getSelector();
10793 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
10794 e = ME->getInstanceReceiver();
10795 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000010796 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000010797 e = e->IgnoreParenCasts();
10798 }
10799 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
10800 if (CE->getNumArgs() == 1) {
10801 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000010802 if (Fn) {
10803 const IdentifierInfo *FnI = Fn->getIdentifier();
10804 if (FnI && FnI->isStr("_Block_copy")) {
10805 e = CE->getArg(0)->IgnoreParenCasts();
10806 }
10807 }
Jordan Rose67e887c2012-09-17 17:54:30 +000010808 }
10809 }
10810
John McCall31168b02011-06-15 23:02:42 +000010811 BlockExpr *block = dyn_cast<BlockExpr>(e);
10812 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000010813 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000010814
10815 FindCaptureVisitor visitor(S.Context, owner.Variable);
10816 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010817 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000010818}
10819
10820static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10821 RetainCycleOwner &owner) {
10822 assert(capturer);
10823 assert(owner.Variable && owner.Loc.isValid());
10824
10825 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10826 << owner.Variable << capturer->getSourceRange();
10827 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10828 << owner.Indirect << owner.Range;
10829}
10830
10831/// Check for a keyword selector that starts with the word 'add' or
10832/// 'set'.
10833static bool isSetterLikeSelector(Selector sel) {
10834 if (sel.isUnarySelector()) return false;
10835
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010836 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000010837 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010838 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000010839 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010840 else if (str.startswith("add")) {
10841 // Specially whitelist 'addOperationWithBlock:'.
10842 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
10843 return false;
10844 str = str.substr(3);
10845 }
John McCall31168b02011-06-15 23:02:42 +000010846 else
10847 return false;
10848
10849 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000010850 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000010851}
10852
Benjamin Kramer3a743452015-03-09 15:03:32 +000010853static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
10854 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010855 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
10856 Message->getReceiverInterface(),
10857 NSAPI::ClassId_NSMutableArray);
10858 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010859 return None;
10860 }
10861
10862 Selector Sel = Message->getSelector();
10863
10864 Optional<NSAPI::NSArrayMethodKind> MKOpt =
10865 S.NSAPIObj->getNSArrayMethodKind(Sel);
10866 if (!MKOpt) {
10867 return None;
10868 }
10869
10870 NSAPI::NSArrayMethodKind MK = *MKOpt;
10871
10872 switch (MK) {
10873 case NSAPI::NSMutableArr_addObject:
10874 case NSAPI::NSMutableArr_insertObjectAtIndex:
10875 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
10876 return 0;
10877 case NSAPI::NSMutableArr_replaceObjectAtIndex:
10878 return 1;
10879
10880 default:
10881 return None;
10882 }
10883
10884 return None;
10885}
10886
10887static
10888Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10889 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010890 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10891 Message->getReceiverInterface(),
10892 NSAPI::ClassId_NSMutableDictionary);
10893 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010894 return None;
10895 }
10896
10897 Selector Sel = Message->getSelector();
10898
10899 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10900 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10901 if (!MKOpt) {
10902 return None;
10903 }
10904
10905 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10906
10907 switch (MK) {
10908 case NSAPI::NSMutableDict_setObjectForKey:
10909 case NSAPI::NSMutableDict_setValueForKey:
10910 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10911 return 0;
10912
10913 default:
10914 return None;
10915 }
10916
10917 return None;
10918}
10919
10920static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010921 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10922 Message->getReceiverInterface(),
10923 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000010924
Alex Denisov5dfac812015-08-06 04:51:14 +000010925 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10926 Message->getReceiverInterface(),
10927 NSAPI::ClassId_NSMutableOrderedSet);
10928 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010929 return None;
10930 }
10931
10932 Selector Sel = Message->getSelector();
10933
10934 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10935 if (!MKOpt) {
10936 return None;
10937 }
10938
10939 NSAPI::NSSetMethodKind MK = *MKOpt;
10940
10941 switch (MK) {
10942 case NSAPI::NSMutableSet_addObject:
10943 case NSAPI::NSOrderedSet_setObjectAtIndex:
10944 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10945 case NSAPI::NSOrderedSet_insertObjectAtIndex:
10946 return 0;
10947 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10948 return 1;
10949 }
10950
10951 return None;
10952}
10953
10954void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10955 if (!Message->isInstanceMessage()) {
10956 return;
10957 }
10958
10959 Optional<int> ArgOpt;
10960
10961 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10962 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10963 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10964 return;
10965 }
10966
10967 int ArgIndex = *ArgOpt;
10968
Alex Denisove1d882c2015-03-04 17:55:52 +000010969 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10970 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10971 Arg = OE->getSourceExpr()->IgnoreImpCasts();
10972 }
10973
Alex Denisov5dfac812015-08-06 04:51:14 +000010974 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010975 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010976 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010977 Diag(Message->getSourceRange().getBegin(),
10978 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000010979 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000010980 }
10981 }
Alex Denisov5dfac812015-08-06 04:51:14 +000010982 } else {
10983 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10984
10985 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10986 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10987 }
10988
10989 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10990 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10991 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10992 ValueDecl *Decl = ReceiverRE->getDecl();
10993 Diag(Message->getSourceRange().getBegin(),
10994 diag::warn_objc_circular_container)
10995 << Decl->getName() << Decl->getName();
10996 if (!ArgRE->isObjCSelfExpr()) {
10997 Diag(Decl->getLocation(),
10998 diag::note_objc_circular_container_declared_here)
10999 << Decl->getName();
11000 }
11001 }
11002 }
11003 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11004 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11005 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11006 ObjCIvarDecl *Decl = IvarRE->getDecl();
11007 Diag(Message->getSourceRange().getBegin(),
11008 diag::warn_objc_circular_container)
11009 << Decl->getName() << Decl->getName();
11010 Diag(Decl->getLocation(),
11011 diag::note_objc_circular_container_declared_here)
11012 << Decl->getName();
11013 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011014 }
11015 }
11016 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011017}
11018
John McCall31168b02011-06-15 23:02:42 +000011019/// Check a message send to see if it's likely to cause a retain cycle.
11020void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11021 // Only check instance methods whose selector looks like a setter.
11022 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11023 return;
11024
11025 // Try to find a variable that the receiver is strongly owned by.
11026 RetainCycleOwner owner;
11027 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011028 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000011029 return;
11030 } else {
11031 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11032 owner.Variable = getCurMethodDecl()->getSelfDecl();
11033 owner.Loc = msg->getSuperLoc();
11034 owner.Range = msg->getSuperLoc();
11035 }
11036
11037 // Check whether the receiver is captured by any of the arguments.
11038 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
11039 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
11040 return diagnoseRetainCycle(*this, capturer, owner);
11041}
11042
11043/// Check a property assign to see if it's likely to cause a retain cycle.
11044void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11045 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011046 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000011047 return;
11048
11049 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11050 diagnoseRetainCycle(*this, capturer, owner);
11051}
11052
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011053void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11054 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000011055 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011056 return;
11057
11058 // Because we don't have an expression for the variable, we have to set the
11059 // location explicitly here.
11060 Owner.Loc = Var->getLocation();
11061 Owner.Range = Var->getSourceRange();
11062
11063 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11064 diagnoseRetainCycle(*this, Capturer, Owner);
11065}
11066
Ted Kremenek9304da92012-12-21 08:04:28 +000011067static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11068 Expr *RHS, bool isProperty) {
11069 // Check if RHS is an Objective-C object literal, which also can get
11070 // immediately zapped in a weak reference. Note that we explicitly
11071 // allow ObjCStringLiterals, since those are designed to never really die.
11072 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011073
Ted Kremenek64873352012-12-21 22:46:35 +000011074 // This enum needs to match with the 'select' in
11075 // warn_objc_arc_literal_assign (off-by-1).
11076 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11077 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11078 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011079
11080 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000011081 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000011082 << (isProperty ? 0 : 1)
11083 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011084
11085 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000011086}
11087
Ted Kremenekc1f014a2012-12-21 19:45:30 +000011088static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11089 Qualifiers::ObjCLifetime LT,
11090 Expr *RHS, bool isProperty) {
11091 // Strip off any implicit cast added to get to the one ARC-specific.
11092 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11093 if (cast->getCastKind() == CK_ARCConsumeObject) {
11094 S.Diag(Loc, diag::warn_arc_retained_assign)
11095 << (LT == Qualifiers::OCL_ExplicitNone)
11096 << (isProperty ? 0 : 1)
11097 << RHS->getSourceRange();
11098 return true;
11099 }
11100 RHS = cast->getSubExpr();
11101 }
11102
11103 if (LT == Qualifiers::OCL_Weak &&
11104 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11105 return true;
11106
11107 return false;
11108}
11109
Ted Kremenekb36234d2012-12-21 08:04:20 +000011110bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11111 QualType LHS, Expr *RHS) {
11112 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11113
11114 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11115 return false;
11116
11117 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11118 return true;
11119
11120 return false;
11121}
11122
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011123void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11124 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011125 QualType LHSType;
11126 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011127 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011128 ObjCPropertyRefExpr *PRE
11129 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11130 if (PRE && !PRE->isImplicitProperty()) {
11131 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11132 if (PD)
11133 LHSType = PD->getType();
11134 }
11135
11136 if (LHSType.isNull())
11137 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000011138
11139 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11140
11141 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011142 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000011143 getCurFunction()->markSafeWeakUse(LHS);
11144 }
11145
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011146 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11147 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000011148
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011149 // FIXME. Check for other life times.
11150 if (LT != Qualifiers::OCL_None)
11151 return;
11152
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011153 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011154 if (PRE->isImplicitProperty())
11155 return;
11156 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11157 if (!PD)
11158 return;
11159
Bill Wendling44426052012-12-20 19:22:21 +000011160 unsigned Attributes = PD->getPropertyAttributes();
11161 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011162 // when 'assign' attribute was not explicitly specified
11163 // by user, ignore it and rely on property type itself
11164 // for lifetime info.
11165 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11166 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11167 LHSType->isObjCRetainableType())
11168 return;
11169
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011170 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000011171 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011172 Diag(Loc, diag::warn_arc_retained_property_assign)
11173 << RHS->getSourceRange();
11174 return;
11175 }
11176 RHS = cast->getSubExpr();
11177 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011178 }
Bill Wendling44426052012-12-20 19:22:21 +000011179 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000011180 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11181 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000011182 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011183 }
11184}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011185
11186//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11187
11188namespace {
11189bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11190 SourceLocation StmtLoc,
11191 const NullStmt *Body) {
11192 // Do not warn if the body is a macro that expands to nothing, e.g:
11193 //
11194 // #define CALL(x)
11195 // if (condition)
11196 // CALL(0);
11197 //
11198 if (Body->hasLeadingEmptyMacro())
11199 return false;
11200
11201 // Get line numbers of statement and body.
11202 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000011203 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011204 &StmtLineInvalid);
11205 if (StmtLineInvalid)
11206 return false;
11207
11208 bool BodyLineInvalid;
11209 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11210 &BodyLineInvalid);
11211 if (BodyLineInvalid)
11212 return false;
11213
11214 // Warn if null statement and body are on the same line.
11215 if (StmtLine != BodyLine)
11216 return false;
11217
11218 return true;
11219}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011220} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011221
11222void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11223 const Stmt *Body,
11224 unsigned DiagID) {
11225 // Since this is a syntactic check, don't emit diagnostic for template
11226 // instantiations, this just adds noise.
11227 if (CurrentInstantiationScope)
11228 return;
11229
11230 // The body should be a null statement.
11231 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11232 if (!NBody)
11233 return;
11234
11235 // Do the usual checks.
11236 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11237 return;
11238
11239 Diag(NBody->getSemiLoc(), DiagID);
11240 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11241}
11242
11243void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11244 const Stmt *PossibleBody) {
11245 assert(!CurrentInstantiationScope); // Ensured by caller
11246
11247 SourceLocation StmtLoc;
11248 const Stmt *Body;
11249 unsigned DiagID;
11250 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11251 StmtLoc = FS->getRParenLoc();
11252 Body = FS->getBody();
11253 DiagID = diag::warn_empty_for_body;
11254 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11255 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11256 Body = WS->getBody();
11257 DiagID = diag::warn_empty_while_body;
11258 } else
11259 return; // Neither `for' nor `while'.
11260
11261 // The body should be a null statement.
11262 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11263 if (!NBody)
11264 return;
11265
11266 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011267 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011268 return;
11269
11270 // Do the usual checks.
11271 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11272 return;
11273
11274 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11275 // noise level low, emit diagnostics only if for/while is followed by a
11276 // CompoundStmt, e.g.:
11277 // for (int i = 0; i < n; i++);
11278 // {
11279 // a(i);
11280 // }
11281 // or if for/while is followed by a statement with more indentation
11282 // than for/while itself:
11283 // for (int i = 0; i < n; i++);
11284 // a(i);
11285 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11286 if (!ProbableTypo) {
11287 bool BodyColInvalid;
11288 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11289 PossibleBody->getLocStart(),
11290 &BodyColInvalid);
11291 if (BodyColInvalid)
11292 return;
11293
11294 bool StmtColInvalid;
11295 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11296 S->getLocStart(),
11297 &StmtColInvalid);
11298 if (StmtColInvalid)
11299 return;
11300
11301 if (BodyCol > StmtCol)
11302 ProbableTypo = true;
11303 }
11304
11305 if (ProbableTypo) {
11306 Diag(NBody->getSemiLoc(), DiagID);
11307 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11308 }
11309}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011310
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011311//===--- CHECK: Warn on self move with std::move. -------------------------===//
11312
11313/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11314void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11315 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011316 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11317 return;
11318
Richard Smith51ec0cf2017-02-21 01:17:38 +000011319 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011320 return;
11321
11322 // Strip parens and casts away.
11323 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11324 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11325
11326 // Check for a call expression
11327 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11328 if (!CE || CE->getNumArgs() != 1)
11329 return;
11330
11331 // Check for a call to std::move
11332 const FunctionDecl *FD = CE->getDirectCallee();
11333 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11334 !FD->getIdentifier()->isStr("move"))
11335 return;
11336
11337 // Get argument from std::move
11338 RHSExpr = CE->getArg(0);
11339
11340 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11341 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11342
11343 // Two DeclRefExpr's, check that the decls are the same.
11344 if (LHSDeclRef && RHSDeclRef) {
11345 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11346 return;
11347 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11348 RHSDeclRef->getDecl()->getCanonicalDecl())
11349 return;
11350
11351 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11352 << LHSExpr->getSourceRange()
11353 << RHSExpr->getSourceRange();
11354 return;
11355 }
11356
11357 // Member variables require a different approach to check for self moves.
11358 // MemberExpr's are the same if every nested MemberExpr refers to the same
11359 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11360 // the base Expr's are CXXThisExpr's.
11361 const Expr *LHSBase = LHSExpr;
11362 const Expr *RHSBase = RHSExpr;
11363 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11364 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11365 if (!LHSME || !RHSME)
11366 return;
11367
11368 while (LHSME && RHSME) {
11369 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11370 RHSME->getMemberDecl()->getCanonicalDecl())
11371 return;
11372
11373 LHSBase = LHSME->getBase();
11374 RHSBase = RHSME->getBase();
11375 LHSME = dyn_cast<MemberExpr>(LHSBase);
11376 RHSME = dyn_cast<MemberExpr>(RHSBase);
11377 }
11378
11379 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11380 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11381 if (LHSDeclRef && RHSDeclRef) {
11382 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11383 return;
11384 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11385 RHSDeclRef->getDecl()->getCanonicalDecl())
11386 return;
11387
11388 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11389 << LHSExpr->getSourceRange()
11390 << RHSExpr->getSourceRange();
11391 return;
11392 }
11393
11394 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11395 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11396 << LHSExpr->getSourceRange()
11397 << RHSExpr->getSourceRange();
11398}
11399
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011400//===--- Layout compatibility ----------------------------------------------//
11401
11402namespace {
11403
11404bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11405
11406/// \brief Check if two enumeration types are layout-compatible.
11407bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11408 // C++11 [dcl.enum] p8:
11409 // Two enumeration types are layout-compatible if they have the same
11410 // underlying type.
11411 return ED1->isComplete() && ED2->isComplete() &&
11412 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11413}
11414
11415/// \brief Check if two fields are layout-compatible.
11416bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11417 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11418 return false;
11419
11420 if (Field1->isBitField() != Field2->isBitField())
11421 return false;
11422
11423 if (Field1->isBitField()) {
11424 // Make sure that the bit-fields are the same length.
11425 unsigned Bits1 = Field1->getBitWidthValue(C);
11426 unsigned Bits2 = Field2->getBitWidthValue(C);
11427
11428 if (Bits1 != Bits2)
11429 return false;
11430 }
11431
11432 return true;
11433}
11434
11435/// \brief Check if two standard-layout structs are layout-compatible.
11436/// (C++11 [class.mem] p17)
11437bool isLayoutCompatibleStruct(ASTContext &C,
11438 RecordDecl *RD1,
11439 RecordDecl *RD2) {
11440 // If both records are C++ classes, check that base classes match.
11441 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11442 // If one of records is a CXXRecordDecl we are in C++ mode,
11443 // thus the other one is a CXXRecordDecl, too.
11444 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11445 // Check number of base classes.
11446 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11447 return false;
11448
11449 // Check the base classes.
11450 for (CXXRecordDecl::base_class_const_iterator
11451 Base1 = D1CXX->bases_begin(),
11452 BaseEnd1 = D1CXX->bases_end(),
11453 Base2 = D2CXX->bases_begin();
11454 Base1 != BaseEnd1;
11455 ++Base1, ++Base2) {
11456 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11457 return false;
11458 }
11459 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11460 // If only RD2 is a C++ class, it should have zero base classes.
11461 if (D2CXX->getNumBases() > 0)
11462 return false;
11463 }
11464
11465 // Check the fields.
11466 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11467 Field2End = RD2->field_end(),
11468 Field1 = RD1->field_begin(),
11469 Field1End = RD1->field_end();
11470 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11471 if (!isLayoutCompatible(C, *Field1, *Field2))
11472 return false;
11473 }
11474 if (Field1 != Field1End || Field2 != Field2End)
11475 return false;
11476
11477 return true;
11478}
11479
11480/// \brief Check if two standard-layout unions are layout-compatible.
11481/// (C++11 [class.mem] p18)
11482bool isLayoutCompatibleUnion(ASTContext &C,
11483 RecordDecl *RD1,
11484 RecordDecl *RD2) {
11485 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011486 for (auto *Field2 : RD2->fields())
11487 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011488
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011489 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011490 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11491 I = UnmatchedFields.begin(),
11492 E = UnmatchedFields.end();
11493
11494 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011495 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011496 bool Result = UnmatchedFields.erase(*I);
11497 (void) Result;
11498 assert(Result);
11499 break;
11500 }
11501 }
11502 if (I == E)
11503 return false;
11504 }
11505
11506 return UnmatchedFields.empty();
11507}
11508
11509bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11510 if (RD1->isUnion() != RD2->isUnion())
11511 return false;
11512
11513 if (RD1->isUnion())
11514 return isLayoutCompatibleUnion(C, RD1, RD2);
11515 else
11516 return isLayoutCompatibleStruct(C, RD1, RD2);
11517}
11518
11519/// \brief Check if two types are layout-compatible in C++11 sense.
11520bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11521 if (T1.isNull() || T2.isNull())
11522 return false;
11523
11524 // C++11 [basic.types] p11:
11525 // If two types T1 and T2 are the same type, then T1 and T2 are
11526 // layout-compatible types.
11527 if (C.hasSameType(T1, T2))
11528 return true;
11529
11530 T1 = T1.getCanonicalType().getUnqualifiedType();
11531 T2 = T2.getCanonicalType().getUnqualifiedType();
11532
11533 const Type::TypeClass TC1 = T1->getTypeClass();
11534 const Type::TypeClass TC2 = T2->getTypeClass();
11535
11536 if (TC1 != TC2)
11537 return false;
11538
11539 if (TC1 == Type::Enum) {
11540 return isLayoutCompatible(C,
11541 cast<EnumType>(T1)->getDecl(),
11542 cast<EnumType>(T2)->getDecl());
11543 } else if (TC1 == Type::Record) {
11544 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11545 return false;
11546
11547 return isLayoutCompatible(C,
11548 cast<RecordType>(T1)->getDecl(),
11549 cast<RecordType>(T2)->getDecl());
11550 }
11551
11552 return false;
11553}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011554} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011555
11556//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11557
11558namespace {
11559/// \brief Given a type tag expression find the type tag itself.
11560///
11561/// \param TypeExpr Type tag expression, as it appears in user's code.
11562///
11563/// \param VD Declaration of an identifier that appears in a type tag.
11564///
11565/// \param MagicValue Type tag magic value.
11566bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11567 const ValueDecl **VD, uint64_t *MagicValue) {
11568 while(true) {
11569 if (!TypeExpr)
11570 return false;
11571
11572 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11573
11574 switch (TypeExpr->getStmtClass()) {
11575 case Stmt::UnaryOperatorClass: {
11576 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11577 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11578 TypeExpr = UO->getSubExpr();
11579 continue;
11580 }
11581 return false;
11582 }
11583
11584 case Stmt::DeclRefExprClass: {
11585 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11586 *VD = DRE->getDecl();
11587 return true;
11588 }
11589
11590 case Stmt::IntegerLiteralClass: {
11591 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11592 llvm::APInt MagicValueAPInt = IL->getValue();
11593 if (MagicValueAPInt.getActiveBits() <= 64) {
11594 *MagicValue = MagicValueAPInt.getZExtValue();
11595 return true;
11596 } else
11597 return false;
11598 }
11599
11600 case Stmt::BinaryConditionalOperatorClass:
11601 case Stmt::ConditionalOperatorClass: {
11602 const AbstractConditionalOperator *ACO =
11603 cast<AbstractConditionalOperator>(TypeExpr);
11604 bool Result;
11605 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11606 if (Result)
11607 TypeExpr = ACO->getTrueExpr();
11608 else
11609 TypeExpr = ACO->getFalseExpr();
11610 continue;
11611 }
11612 return false;
11613 }
11614
11615 case Stmt::BinaryOperatorClass: {
11616 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11617 if (BO->getOpcode() == BO_Comma) {
11618 TypeExpr = BO->getRHS();
11619 continue;
11620 }
11621 return false;
11622 }
11623
11624 default:
11625 return false;
11626 }
11627 }
11628}
11629
11630/// \brief Retrieve the C type corresponding to type tag TypeExpr.
11631///
11632/// \param TypeExpr Expression that specifies a type tag.
11633///
11634/// \param MagicValues Registered magic values.
11635///
11636/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11637/// kind.
11638///
11639/// \param TypeInfo Information about the corresponding C type.
11640///
11641/// \returns true if the corresponding C type was found.
11642bool GetMatchingCType(
11643 const IdentifierInfo *ArgumentKind,
11644 const Expr *TypeExpr, const ASTContext &Ctx,
11645 const llvm::DenseMap<Sema::TypeTagMagicValue,
11646 Sema::TypeTagData> *MagicValues,
11647 bool &FoundWrongKind,
11648 Sema::TypeTagData &TypeInfo) {
11649 FoundWrongKind = false;
11650
11651 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000011652 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011653
11654 uint64_t MagicValue;
11655
11656 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11657 return false;
11658
11659 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000011660 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011661 if (I->getArgumentKind() != ArgumentKind) {
11662 FoundWrongKind = true;
11663 return false;
11664 }
11665 TypeInfo.Type = I->getMatchingCType();
11666 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11667 TypeInfo.MustBeNull = I->getMustBeNull();
11668 return true;
11669 }
11670 return false;
11671 }
11672
11673 if (!MagicValues)
11674 return false;
11675
11676 llvm::DenseMap<Sema::TypeTagMagicValue,
11677 Sema::TypeTagData>::const_iterator I =
11678 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11679 if (I == MagicValues->end())
11680 return false;
11681
11682 TypeInfo = I->second;
11683 return true;
11684}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011685} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011686
11687void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11688 uint64_t MagicValue, QualType Type,
11689 bool LayoutCompatible,
11690 bool MustBeNull) {
11691 if (!TypeTagForDatatypeMagicValues)
11692 TypeTagForDatatypeMagicValues.reset(
11693 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11694
11695 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11696 (*TypeTagForDatatypeMagicValues)[Magic] =
11697 TypeTagData(Type, LayoutCompatible, MustBeNull);
11698}
11699
11700namespace {
11701bool IsSameCharType(QualType T1, QualType T2) {
11702 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11703 if (!BT1)
11704 return false;
11705
11706 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11707 if (!BT2)
11708 return false;
11709
11710 BuiltinType::Kind T1Kind = BT1->getKind();
11711 BuiltinType::Kind T2Kind = BT2->getKind();
11712
11713 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
11714 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
11715 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11716 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11717}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011718} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011719
11720void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11721 const Expr * const *ExprArgs) {
11722 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11723 bool IsPointerAttr = Attr->getIsPointer();
11724
11725 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11726 bool FoundWrongKind;
11727 TypeTagData TypeInfo;
11728 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11729 TypeTagForDatatypeMagicValues.get(),
11730 FoundWrongKind, TypeInfo)) {
11731 if (FoundWrongKind)
11732 Diag(TypeTagExpr->getExprLoc(),
11733 diag::warn_type_tag_for_datatype_wrong_kind)
11734 << TypeTagExpr->getSourceRange();
11735 return;
11736 }
11737
11738 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11739 if (IsPointerAttr) {
11740 // Skip implicit cast of pointer to `void *' (as a function argument).
11741 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000011742 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000011743 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011744 ArgumentExpr = ICE->getSubExpr();
11745 }
11746 QualType ArgumentType = ArgumentExpr->getType();
11747
11748 // Passing a `void*' pointer shouldn't trigger a warning.
11749 if (IsPointerAttr && ArgumentType->isVoidPointerType())
11750 return;
11751
11752 if (TypeInfo.MustBeNull) {
11753 // Type tag with matching void type requires a null pointer.
11754 if (!ArgumentExpr->isNullPointerConstant(Context,
11755 Expr::NPC_ValueDependentIsNotNull)) {
11756 Diag(ArgumentExpr->getExprLoc(),
11757 diag::warn_type_safety_null_pointer_required)
11758 << ArgumentKind->getName()
11759 << ArgumentExpr->getSourceRange()
11760 << TypeTagExpr->getSourceRange();
11761 }
11762 return;
11763 }
11764
11765 QualType RequiredType = TypeInfo.Type;
11766 if (IsPointerAttr)
11767 RequiredType = Context.getPointerType(RequiredType);
11768
11769 bool mismatch = false;
11770 if (!TypeInfo.LayoutCompatible) {
11771 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
11772
11773 // C++11 [basic.fundamental] p1:
11774 // Plain char, signed char, and unsigned char are three distinct types.
11775 //
11776 // But we treat plain `char' as equivalent to `signed char' or `unsigned
11777 // char' depending on the current char signedness mode.
11778 if (mismatch)
11779 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
11780 RequiredType->getPointeeType())) ||
11781 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
11782 mismatch = false;
11783 } else
11784 if (IsPointerAttr)
11785 mismatch = !isLayoutCompatible(Context,
11786 ArgumentType->getPointeeType(),
11787 RequiredType->getPointeeType());
11788 else
11789 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
11790
11791 if (mismatch)
11792 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000011793 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011794 << TypeInfo.LayoutCompatible << RequiredType
11795 << ArgumentExpr->getSourceRange()
11796 << TypeTagExpr->getSourceRange();
11797}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011798
11799void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11800 CharUnits Alignment) {
11801 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
11802}
11803
11804void Sema::DiagnoseMisalignedMembers() {
11805 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000011806 const NamedDecl *ND = m.RD;
11807 if (ND->getName().empty()) {
11808 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
11809 ND = TD;
11810 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011811 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000011812 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011813 }
11814 MisalignedMembers.clear();
11815}
11816
11817void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011818 E = E->IgnoreParens();
11819 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011820 return;
11821 if (isa<UnaryOperator>(E) &&
11822 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
11823 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11824 if (isa<MemberExpr>(Op)) {
11825 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
11826 MisalignedMember(Op));
11827 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011828 (T->isIntegerType() ||
11829 (T->isPointerType() &&
11830 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011831 MisalignedMembers.erase(MA);
11832 }
11833 }
11834}
11835
11836void Sema::RefersToMemberWithReducedAlignment(
11837 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000011838 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
11839 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011840 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011841 if (!ME)
11842 return;
11843
11844 // For a chain of MemberExpr like "a.b.c.d" this list
11845 // will keep FieldDecl's like [d, c, b].
11846 SmallVector<FieldDecl *, 4> ReverseMemberChain;
11847 const MemberExpr *TopME = nullptr;
11848 bool AnyIsPacked = false;
11849 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011850 QualType BaseType = ME->getBase()->getType();
11851 if (ME->isArrow())
11852 BaseType = BaseType->getPointeeType();
11853 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
11854
11855 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011856 auto *FD = dyn_cast<FieldDecl>(MD);
11857 // We do not care about non-data members.
11858 if (!FD || FD->isInvalidDecl())
11859 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011860
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011861 AnyIsPacked =
11862 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
11863 ReverseMemberChain.push_back(FD);
11864
11865 TopME = ME;
11866 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
11867 } while (ME);
11868 assert(TopME && "We did not compute a topmost MemberExpr!");
11869
11870 // Not the scope of this diagnostic.
11871 if (!AnyIsPacked)
11872 return;
11873
11874 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
11875 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
11876 // TODO: The innermost base of the member expression may be too complicated.
11877 // For now, just disregard these cases. This is left for future
11878 // improvement.
11879 if (!DRE && !isa<CXXThisExpr>(TopBase))
11880 return;
11881
11882 // Alignment expected by the whole expression.
11883 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
11884
11885 // No need to do anything else with this case.
11886 if (ExpectedAlignment.isOne())
11887 return;
11888
11889 // Synthesize offset of the whole access.
11890 CharUnits Offset;
11891 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
11892 I++) {
11893 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
11894 }
11895
11896 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
11897 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
11898 ReverseMemberChain.back()->getParent()->getTypeForDecl());
11899
11900 // The base expression of the innermost MemberExpr may give
11901 // stronger guarantees than the class containing the member.
11902 if (DRE && !TopME->isArrow()) {
11903 const ValueDecl *VD = DRE->getDecl();
11904 if (!VD->getType()->isReferenceType())
11905 CompleteObjectAlignment =
11906 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
11907 }
11908
11909 // Check if the synthesized offset fulfills the alignment.
11910 if (Offset % ExpectedAlignment != 0 ||
11911 // It may fulfill the offset it but the effective alignment may still be
11912 // lower than the expected expression alignment.
11913 CompleteObjectAlignment < ExpectedAlignment) {
11914 // If this happens, we want to determine a sensible culprit of this.
11915 // Intuitively, watching the chain of member expressions from right to
11916 // left, we start with the required alignment (as required by the field
11917 // type) but some packed attribute in that chain has reduced the alignment.
11918 // It may happen that another packed structure increases it again. But if
11919 // we are here such increase has not been enough. So pointing the first
11920 // FieldDecl that either is packed or else its RecordDecl is,
11921 // seems reasonable.
11922 FieldDecl *FD = nullptr;
11923 CharUnits Alignment;
11924 for (FieldDecl *FDI : ReverseMemberChain) {
11925 if (FDI->hasAttr<PackedAttr>() ||
11926 FDI->getParent()->hasAttr<PackedAttr>()) {
11927 FD = FDI;
11928 Alignment = std::min(
11929 Context.getTypeAlignInChars(FD->getType()),
11930 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
11931 break;
11932 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011933 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011934 assert(FD && "We did not find a packed FieldDecl!");
11935 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011936 }
11937}
11938
11939void Sema::CheckAddressOfPackedMember(Expr *rhs) {
11940 using namespace std::placeholders;
11941 RefersToMemberWithReducedAlignment(
11942 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
11943 _2, _3, _4));
11944}
11945