blob: 912b52b88b8c72f0f171f0cc4aa6921499597bde [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;
1622 case Mips::BI__builtin_msa_sld_b:
1623 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1624 // These intrinsics take an unsigned 3 bit immediate.
1625 case Mips::BI__builtin_msa_copy_s_h:
1626 case Mips::BI__builtin_msa_copy_u_h:
1627 case Mips::BI__builtin_msa_insve_h:
1628 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1629 case Mips::BI__builtin_msa_sld_h:
1630 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1631 // These intrinsics take an unsigned 2 bit immediate.
1632 case Mips::BI__builtin_msa_copy_s_w:
1633 case Mips::BI__builtin_msa_copy_u_w:
1634 case Mips::BI__builtin_msa_insve_w:
1635 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1636 case Mips::BI__builtin_msa_sld_w:
1637 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1638 // These intrinsics take an unsigned 1 bit immediate.
1639 case Mips::BI__builtin_msa_copy_s_d:
1640 case Mips::BI__builtin_msa_copy_u_d:
1641 case Mips::BI__builtin_msa_insve_d:
1642 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1643 case Mips::BI__builtin_msa_sld_d:
1644 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1645 // Memory offsets and immediate loads.
1646 // These intrinsics take a signed 10 bit immediate.
1647 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 127; break;
1648 case Mips::BI__builtin_msa_ldi_h:
1649 case Mips::BI__builtin_msa_ldi_w:
1650 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1651 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1652 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1653 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1654 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1655 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1656 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1657 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1658 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001659 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001660
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001661 if (!m)
1662 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1663
1664 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1665 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001666}
1667
Kit Bartone50adcb2015-03-30 19:40:59 +00001668bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1669 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001670 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1671 BuiltinID == PPC::BI__builtin_divdeu ||
1672 BuiltinID == PPC::BI__builtin_bpermd;
1673 bool IsTarget64Bit = Context.getTargetInfo()
1674 .getTypeWidth(Context
1675 .getTargetInfo()
1676 .getIntPtrType()) == 64;
1677 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1678 BuiltinID == PPC::BI__builtin_divweu ||
1679 BuiltinID == PPC::BI__builtin_divde ||
1680 BuiltinID == PPC::BI__builtin_divdeu;
1681
1682 if (Is64BitBltin && !IsTarget64Bit)
1683 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1684 << TheCall->getSourceRange();
1685
1686 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1687 (BuiltinID == PPC::BI__builtin_bpermd &&
1688 !Context.getTargetInfo().hasFeature("bpermd")))
1689 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1690 << TheCall->getSourceRange();
1691
Kit Bartone50adcb2015-03-30 19:40:59 +00001692 switch (BuiltinID) {
1693 default: return false;
1694 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1695 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1696 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1697 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1698 case PPC::BI__builtin_tbegin:
1699 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1700 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1701 case PPC::BI__builtin_tabortwc:
1702 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1703 case PPC::BI__builtin_tabortwci:
1704 case PPC::BI__builtin_tabortdci:
1705 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1706 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1707 }
1708 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1709}
1710
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001711bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1712 CallExpr *TheCall) {
1713 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1714 Expr *Arg = TheCall->getArg(0);
1715 llvm::APSInt AbortCode(32);
1716 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1717 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1718 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1719 << Arg->getSourceRange();
1720 }
1721
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001722 // For intrinsics which take an immediate value as part of the instruction,
1723 // range check them here.
1724 unsigned i = 0, l = 0, u = 0;
1725 switch (BuiltinID) {
1726 default: return false;
1727 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1728 case SystemZ::BI__builtin_s390_verimb:
1729 case SystemZ::BI__builtin_s390_verimh:
1730 case SystemZ::BI__builtin_s390_verimf:
1731 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1732 case SystemZ::BI__builtin_s390_vfaeb:
1733 case SystemZ::BI__builtin_s390_vfaeh:
1734 case SystemZ::BI__builtin_s390_vfaef:
1735 case SystemZ::BI__builtin_s390_vfaebs:
1736 case SystemZ::BI__builtin_s390_vfaehs:
1737 case SystemZ::BI__builtin_s390_vfaefs:
1738 case SystemZ::BI__builtin_s390_vfaezb:
1739 case SystemZ::BI__builtin_s390_vfaezh:
1740 case SystemZ::BI__builtin_s390_vfaezf:
1741 case SystemZ::BI__builtin_s390_vfaezbs:
1742 case SystemZ::BI__builtin_s390_vfaezhs:
1743 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1744 case SystemZ::BI__builtin_s390_vfidb:
1745 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1746 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1747 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1748 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1749 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1750 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1751 case SystemZ::BI__builtin_s390_vstrcb:
1752 case SystemZ::BI__builtin_s390_vstrch:
1753 case SystemZ::BI__builtin_s390_vstrcf:
1754 case SystemZ::BI__builtin_s390_vstrczb:
1755 case SystemZ::BI__builtin_s390_vstrczh:
1756 case SystemZ::BI__builtin_s390_vstrczf:
1757 case SystemZ::BI__builtin_s390_vstrcbs:
1758 case SystemZ::BI__builtin_s390_vstrchs:
1759 case SystemZ::BI__builtin_s390_vstrcfs:
1760 case SystemZ::BI__builtin_s390_vstrczbs:
1761 case SystemZ::BI__builtin_s390_vstrczhs:
1762 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1763 }
1764 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001765}
1766
Craig Topper5ba2c502015-11-07 08:08:31 +00001767/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1768/// This checks that the target supports __builtin_cpu_supports and
1769/// that the string argument is constant and valid.
1770static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1771 Expr *Arg = TheCall->getArg(0);
1772
1773 // Check if the argument is a string literal.
1774 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1775 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1776 << Arg->getSourceRange();
1777
1778 // Check the contents of the string.
1779 StringRef Feature =
1780 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1781 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1782 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1783 << Arg->getSourceRange();
1784 return false;
1785}
1786
Craig Toppera7e253e2016-09-23 04:48:31 +00001787// Check if the rounding mode is legal.
1788bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1789 // Indicates if this instruction has rounding control or just SAE.
1790 bool HasRC = false;
1791
1792 unsigned ArgNum = 0;
1793 switch (BuiltinID) {
1794 default:
1795 return false;
1796 case X86::BI__builtin_ia32_vcvttsd2si32:
1797 case X86::BI__builtin_ia32_vcvttsd2si64:
1798 case X86::BI__builtin_ia32_vcvttsd2usi32:
1799 case X86::BI__builtin_ia32_vcvttsd2usi64:
1800 case X86::BI__builtin_ia32_vcvttss2si32:
1801 case X86::BI__builtin_ia32_vcvttss2si64:
1802 case X86::BI__builtin_ia32_vcvttss2usi32:
1803 case X86::BI__builtin_ia32_vcvttss2usi64:
1804 ArgNum = 1;
1805 break;
1806 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1807 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1808 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1809 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1810 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1811 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1812 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1813 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1814 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1815 case X86::BI__builtin_ia32_exp2pd_mask:
1816 case X86::BI__builtin_ia32_exp2ps_mask:
1817 case X86::BI__builtin_ia32_getexppd512_mask:
1818 case X86::BI__builtin_ia32_getexpps512_mask:
1819 case X86::BI__builtin_ia32_rcp28pd_mask:
1820 case X86::BI__builtin_ia32_rcp28ps_mask:
1821 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1822 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1823 case X86::BI__builtin_ia32_vcomisd:
1824 case X86::BI__builtin_ia32_vcomiss:
1825 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1826 ArgNum = 3;
1827 break;
1828 case X86::BI__builtin_ia32_cmppd512_mask:
1829 case X86::BI__builtin_ia32_cmpps512_mask:
1830 case X86::BI__builtin_ia32_cmpsd_mask:
1831 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001832 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001833 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1834 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001835 case X86::BI__builtin_ia32_maxpd512_mask:
1836 case X86::BI__builtin_ia32_maxps512_mask:
1837 case X86::BI__builtin_ia32_maxsd_round_mask:
1838 case X86::BI__builtin_ia32_maxss_round_mask:
1839 case X86::BI__builtin_ia32_minpd512_mask:
1840 case X86::BI__builtin_ia32_minps512_mask:
1841 case X86::BI__builtin_ia32_minsd_round_mask:
1842 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001843 case X86::BI__builtin_ia32_rcp28sd_round_mask:
1844 case X86::BI__builtin_ia32_rcp28ss_round_mask:
1845 case X86::BI__builtin_ia32_reducepd512_mask:
1846 case X86::BI__builtin_ia32_reduceps512_mask:
1847 case X86::BI__builtin_ia32_rndscalepd_mask:
1848 case X86::BI__builtin_ia32_rndscaleps_mask:
1849 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1850 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1851 ArgNum = 4;
1852 break;
1853 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001854 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001855 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001856 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001857 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001858 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001859 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001860 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001861 case X86::BI__builtin_ia32_rangepd512_mask:
1862 case X86::BI__builtin_ia32_rangeps512_mask:
1863 case X86::BI__builtin_ia32_rangesd128_round_mask:
1864 case X86::BI__builtin_ia32_rangess128_round_mask:
1865 case X86::BI__builtin_ia32_reducesd_mask:
1866 case X86::BI__builtin_ia32_reducess_mask:
1867 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1868 case X86::BI__builtin_ia32_rndscaless_round_mask:
1869 ArgNum = 5;
1870 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00001871 case X86::BI__builtin_ia32_vcvtsd2si64:
1872 case X86::BI__builtin_ia32_vcvtsd2si32:
1873 case X86::BI__builtin_ia32_vcvtsd2usi32:
1874 case X86::BI__builtin_ia32_vcvtsd2usi64:
1875 case X86::BI__builtin_ia32_vcvtss2si32:
1876 case X86::BI__builtin_ia32_vcvtss2si64:
1877 case X86::BI__builtin_ia32_vcvtss2usi32:
1878 case X86::BI__builtin_ia32_vcvtss2usi64:
1879 ArgNum = 1;
1880 HasRC = true;
1881 break;
Craig Topper8e066312016-11-07 07:01:09 +00001882 case X86::BI__builtin_ia32_cvtsi2sd64:
1883 case X86::BI__builtin_ia32_cvtsi2ss32:
1884 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00001885 case X86::BI__builtin_ia32_cvtusi2sd64:
1886 case X86::BI__builtin_ia32_cvtusi2ss32:
1887 case X86::BI__builtin_ia32_cvtusi2ss64:
1888 ArgNum = 2;
1889 HasRC = true;
1890 break;
1891 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1892 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1893 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1894 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1895 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1896 case X86::BI__builtin_ia32_cvtps2qq512_mask:
1897 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1898 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1899 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1900 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1901 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001902 case X86::BI__builtin_ia32_sqrtpd512_mask:
1903 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001904 ArgNum = 3;
1905 HasRC = true;
1906 break;
1907 case X86::BI__builtin_ia32_addpd512_mask:
1908 case X86::BI__builtin_ia32_addps512_mask:
1909 case X86::BI__builtin_ia32_divpd512_mask:
1910 case X86::BI__builtin_ia32_divps512_mask:
1911 case X86::BI__builtin_ia32_mulpd512_mask:
1912 case X86::BI__builtin_ia32_mulps512_mask:
1913 case X86::BI__builtin_ia32_subpd512_mask:
1914 case X86::BI__builtin_ia32_subps512_mask:
1915 case X86::BI__builtin_ia32_addss_round_mask:
1916 case X86::BI__builtin_ia32_addsd_round_mask:
1917 case X86::BI__builtin_ia32_divss_round_mask:
1918 case X86::BI__builtin_ia32_divsd_round_mask:
1919 case X86::BI__builtin_ia32_mulss_round_mask:
1920 case X86::BI__builtin_ia32_mulsd_round_mask:
1921 case X86::BI__builtin_ia32_subss_round_mask:
1922 case X86::BI__builtin_ia32_subsd_round_mask:
1923 case X86::BI__builtin_ia32_scalefpd512_mask:
1924 case X86::BI__builtin_ia32_scalefps512_mask:
1925 case X86::BI__builtin_ia32_scalefsd_round_mask:
1926 case X86::BI__builtin_ia32_scalefss_round_mask:
1927 case X86::BI__builtin_ia32_getmantpd512_mask:
1928 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001929 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
1930 case X86::BI__builtin_ia32_sqrtsd_round_mask:
1931 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001932 case X86::BI__builtin_ia32_vfmaddpd512_mask:
1933 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1934 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1935 case X86::BI__builtin_ia32_vfmaddps512_mask:
1936 case X86::BI__builtin_ia32_vfmaddps512_mask3:
1937 case X86::BI__builtin_ia32_vfmaddps512_maskz:
1938 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1939 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1940 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1941 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1942 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1943 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1944 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1945 case X86::BI__builtin_ia32_vfmsubps512_mask3:
1946 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1947 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1948 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1949 case X86::BI__builtin_ia32_vfnmaddps512_mask:
1950 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1951 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1952 case X86::BI__builtin_ia32_vfnmsubps512_mask:
1953 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1954 case X86::BI__builtin_ia32_vfmaddsd3_mask:
1955 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1956 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1957 case X86::BI__builtin_ia32_vfmaddss3_mask:
1958 case X86::BI__builtin_ia32_vfmaddss3_maskz:
1959 case X86::BI__builtin_ia32_vfmaddss3_mask3:
1960 ArgNum = 4;
1961 HasRC = true;
1962 break;
1963 case X86::BI__builtin_ia32_getmantsd_round_mask:
1964 case X86::BI__builtin_ia32_getmantss_round_mask:
1965 ArgNum = 5;
1966 HasRC = true;
1967 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00001968 }
1969
1970 llvm::APSInt Result;
1971
1972 // We can't check the value of a dependent argument.
1973 Expr *Arg = TheCall->getArg(ArgNum);
1974 if (Arg->isTypeDependent() || Arg->isValueDependent())
1975 return false;
1976
1977 // Check constant-ness first.
1978 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1979 return true;
1980
1981 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1982 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1983 // combined with ROUND_NO_EXC.
1984 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1985 Result == 8/*ROUND_NO_EXC*/ ||
1986 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1987 return false;
1988
1989 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1990 << Arg->getSourceRange();
1991}
1992
Craig Topperf0ddc892016-09-23 04:48:27 +00001993bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1994 if (BuiltinID == X86::BI__builtin_cpu_supports)
1995 return SemaBuiltinCpuSupports(*this, TheCall);
1996
1997 if (BuiltinID == X86::BI__builtin_ms_va_start)
1998 return SemaBuiltinMSVAStart(TheCall);
1999
Craig Toppera7e253e2016-09-23 04:48:31 +00002000 // If the intrinsic has rounding or SAE make sure its valid.
2001 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2002 return true;
2003
Craig Topperf0ddc892016-09-23 04:48:27 +00002004 // For intrinsics which take an immediate value as part of the instruction,
2005 // range check them here.
2006 int i = 0, l = 0, u = 0;
2007 switch (BuiltinID) {
2008 default:
2009 return false;
Richard Trieucc3949d2016-02-18 22:34:54 +00002010 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00002011 i = 1; l = 0; u = 3;
2012 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002013 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00002014 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2015 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2016 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2017 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002018 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002019 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002020 case X86::BI__builtin_ia32_vpermil2pd:
2021 case X86::BI__builtin_ia32_vpermil2pd256:
2022 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002023 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002024 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002025 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002026 case X86::BI__builtin_ia32_cmpb128_mask:
2027 case X86::BI__builtin_ia32_cmpw128_mask:
2028 case X86::BI__builtin_ia32_cmpd128_mask:
2029 case X86::BI__builtin_ia32_cmpq128_mask:
2030 case X86::BI__builtin_ia32_cmpb256_mask:
2031 case X86::BI__builtin_ia32_cmpw256_mask:
2032 case X86::BI__builtin_ia32_cmpd256_mask:
2033 case X86::BI__builtin_ia32_cmpq256_mask:
2034 case X86::BI__builtin_ia32_cmpb512_mask:
2035 case X86::BI__builtin_ia32_cmpw512_mask:
2036 case X86::BI__builtin_ia32_cmpd512_mask:
2037 case X86::BI__builtin_ia32_cmpq512_mask:
2038 case X86::BI__builtin_ia32_ucmpb128_mask:
2039 case X86::BI__builtin_ia32_ucmpw128_mask:
2040 case X86::BI__builtin_ia32_ucmpd128_mask:
2041 case X86::BI__builtin_ia32_ucmpq128_mask:
2042 case X86::BI__builtin_ia32_ucmpb256_mask:
2043 case X86::BI__builtin_ia32_ucmpw256_mask:
2044 case X86::BI__builtin_ia32_ucmpd256_mask:
2045 case X86::BI__builtin_ia32_ucmpq256_mask:
2046 case X86::BI__builtin_ia32_ucmpb512_mask:
2047 case X86::BI__builtin_ia32_ucmpw512_mask:
2048 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002049 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002050 case X86::BI__builtin_ia32_vpcomub:
2051 case X86::BI__builtin_ia32_vpcomuw:
2052 case X86::BI__builtin_ia32_vpcomud:
2053 case X86::BI__builtin_ia32_vpcomuq:
2054 case X86::BI__builtin_ia32_vpcomb:
2055 case X86::BI__builtin_ia32_vpcomw:
2056 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002057 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00002058 i = 2; l = 0; u = 7;
2059 break;
2060 case X86::BI__builtin_ia32_roundps:
2061 case X86::BI__builtin_ia32_roundpd:
2062 case X86::BI__builtin_ia32_roundps256:
2063 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002064 i = 1; l = 0; u = 15;
2065 break;
2066 case X86::BI__builtin_ia32_roundss:
2067 case X86::BI__builtin_ia32_roundsd:
2068 case X86::BI__builtin_ia32_rangepd128_mask:
2069 case X86::BI__builtin_ia32_rangepd256_mask:
2070 case X86::BI__builtin_ia32_rangepd512_mask:
2071 case X86::BI__builtin_ia32_rangeps128_mask:
2072 case X86::BI__builtin_ia32_rangeps256_mask:
2073 case X86::BI__builtin_ia32_rangeps512_mask:
2074 case X86::BI__builtin_ia32_getmantsd_round_mask:
2075 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002076 i = 2; l = 0; u = 15;
2077 break;
2078 case X86::BI__builtin_ia32_cmpps:
2079 case X86::BI__builtin_ia32_cmpss:
2080 case X86::BI__builtin_ia32_cmppd:
2081 case X86::BI__builtin_ia32_cmpsd:
2082 case X86::BI__builtin_ia32_cmpps256:
2083 case X86::BI__builtin_ia32_cmppd256:
2084 case X86::BI__builtin_ia32_cmpps128_mask:
2085 case X86::BI__builtin_ia32_cmppd128_mask:
2086 case X86::BI__builtin_ia32_cmpps256_mask:
2087 case X86::BI__builtin_ia32_cmppd256_mask:
2088 case X86::BI__builtin_ia32_cmpps512_mask:
2089 case X86::BI__builtin_ia32_cmppd512_mask:
2090 case X86::BI__builtin_ia32_cmpsd_mask:
2091 case X86::BI__builtin_ia32_cmpss_mask:
2092 i = 2; l = 0; u = 31;
2093 break;
2094 case X86::BI__builtin_ia32_xabort:
2095 i = 0; l = -128; u = 255;
2096 break;
2097 case X86::BI__builtin_ia32_pshufw:
2098 case X86::BI__builtin_ia32_aeskeygenassist128:
2099 i = 1; l = -128; u = 255;
2100 break;
2101 case X86::BI__builtin_ia32_vcvtps2ph:
2102 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper39c87102016-05-18 03:18:12 +00002103 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2104 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2105 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2106 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2107 case X86::BI__builtin_ia32_rndscaleps_mask:
2108 case X86::BI__builtin_ia32_rndscalepd_mask:
2109 case X86::BI__builtin_ia32_reducepd128_mask:
2110 case X86::BI__builtin_ia32_reducepd256_mask:
2111 case X86::BI__builtin_ia32_reducepd512_mask:
2112 case X86::BI__builtin_ia32_reduceps128_mask:
2113 case X86::BI__builtin_ia32_reduceps256_mask:
2114 case X86::BI__builtin_ia32_reduceps512_mask:
2115 case X86::BI__builtin_ia32_prold512_mask:
2116 case X86::BI__builtin_ia32_prolq512_mask:
2117 case X86::BI__builtin_ia32_prold128_mask:
2118 case X86::BI__builtin_ia32_prold256_mask:
2119 case X86::BI__builtin_ia32_prolq128_mask:
2120 case X86::BI__builtin_ia32_prolq256_mask:
2121 case X86::BI__builtin_ia32_prord128_mask:
2122 case X86::BI__builtin_ia32_prord256_mask:
2123 case X86::BI__builtin_ia32_prorq128_mask:
2124 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002125 case X86::BI__builtin_ia32_fpclasspd128_mask:
2126 case X86::BI__builtin_ia32_fpclasspd256_mask:
2127 case X86::BI__builtin_ia32_fpclassps128_mask:
2128 case X86::BI__builtin_ia32_fpclassps256_mask:
2129 case X86::BI__builtin_ia32_fpclassps512_mask:
2130 case X86::BI__builtin_ia32_fpclasspd512_mask:
2131 case X86::BI__builtin_ia32_fpclasssd_mask:
2132 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002133 i = 1; l = 0; u = 255;
2134 break;
2135 case X86::BI__builtin_ia32_palignr:
2136 case X86::BI__builtin_ia32_insertps128:
2137 case X86::BI__builtin_ia32_dpps:
2138 case X86::BI__builtin_ia32_dppd:
2139 case X86::BI__builtin_ia32_dpps256:
2140 case X86::BI__builtin_ia32_mpsadbw128:
2141 case X86::BI__builtin_ia32_mpsadbw256:
2142 case X86::BI__builtin_ia32_pcmpistrm128:
2143 case X86::BI__builtin_ia32_pcmpistri128:
2144 case X86::BI__builtin_ia32_pcmpistria128:
2145 case X86::BI__builtin_ia32_pcmpistric128:
2146 case X86::BI__builtin_ia32_pcmpistrio128:
2147 case X86::BI__builtin_ia32_pcmpistris128:
2148 case X86::BI__builtin_ia32_pcmpistriz128:
2149 case X86::BI__builtin_ia32_pclmulqdq128:
2150 case X86::BI__builtin_ia32_vperm2f128_pd256:
2151 case X86::BI__builtin_ia32_vperm2f128_ps256:
2152 case X86::BI__builtin_ia32_vperm2f128_si256:
2153 case X86::BI__builtin_ia32_permti256:
2154 i = 2; l = -128; u = 255;
2155 break;
2156 case X86::BI__builtin_ia32_palignr128:
2157 case X86::BI__builtin_ia32_palignr256:
Craig Topper39c87102016-05-18 03:18:12 +00002158 case X86::BI__builtin_ia32_palignr512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002159 case X86::BI__builtin_ia32_vcomisd:
2160 case X86::BI__builtin_ia32_vcomiss:
2161 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2162 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2163 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2164 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002165 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2166 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2167 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2168 i = 2; l = 0; u = 255;
2169 break;
2170 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2171 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2172 case X86::BI__builtin_ia32_fixupimmps512_mask:
2173 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2174 case X86::BI__builtin_ia32_fixupimmsd_mask:
2175 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2176 case X86::BI__builtin_ia32_fixupimmss_mask:
2177 case X86::BI__builtin_ia32_fixupimmss_maskz:
2178 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2179 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2180 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2181 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2182 case X86::BI__builtin_ia32_fixupimmps128_mask:
2183 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2184 case X86::BI__builtin_ia32_fixupimmps256_mask:
2185 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2186 case X86::BI__builtin_ia32_pternlogd512_mask:
2187 case X86::BI__builtin_ia32_pternlogd512_maskz:
2188 case X86::BI__builtin_ia32_pternlogq512_mask:
2189 case X86::BI__builtin_ia32_pternlogq512_maskz:
2190 case X86::BI__builtin_ia32_pternlogd128_mask:
2191 case X86::BI__builtin_ia32_pternlogd128_maskz:
2192 case X86::BI__builtin_ia32_pternlogd256_mask:
2193 case X86::BI__builtin_ia32_pternlogd256_maskz:
2194 case X86::BI__builtin_ia32_pternlogq128_mask:
2195 case X86::BI__builtin_ia32_pternlogq128_maskz:
2196 case X86::BI__builtin_ia32_pternlogq256_mask:
2197 case X86::BI__builtin_ia32_pternlogq256_maskz:
2198 i = 3; l = 0; u = 255;
2199 break;
2200 case X86::BI__builtin_ia32_pcmpestrm128:
2201 case X86::BI__builtin_ia32_pcmpestri128:
2202 case X86::BI__builtin_ia32_pcmpestria128:
2203 case X86::BI__builtin_ia32_pcmpestric128:
2204 case X86::BI__builtin_ia32_pcmpestrio128:
2205 case X86::BI__builtin_ia32_pcmpestris128:
2206 case X86::BI__builtin_ia32_pcmpestriz128:
2207 i = 4; l = -128; u = 255;
2208 break;
2209 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2210 case X86::BI__builtin_ia32_rndscaless_round_mask:
2211 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002212 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002213 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002214 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002215}
2216
Richard Smith55ce3522012-06-25 20:30:08 +00002217/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2218/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2219/// Returns true when the format fits the function and the FormatStringInfo has
2220/// been populated.
2221bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2222 FormatStringInfo *FSI) {
2223 FSI->HasVAListArg = Format->getFirstArg() == 0;
2224 FSI->FormatIdx = Format->getFormatIdx() - 1;
2225 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002226
Richard Smith55ce3522012-06-25 20:30:08 +00002227 // The way the format attribute works in GCC, the implicit this argument
2228 // of member functions is counted. However, it doesn't appear in our own
2229 // lists, so decrement format_idx in that case.
2230 if (IsCXXMember) {
2231 if(FSI->FormatIdx == 0)
2232 return false;
2233 --FSI->FormatIdx;
2234 if (FSI->FirstDataArg != 0)
2235 --FSI->FirstDataArg;
2236 }
2237 return true;
2238}
Mike Stump11289f42009-09-09 15:08:12 +00002239
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002240/// Checks if a the given expression evaluates to null.
2241///
2242/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002243static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002244 // If the expression has non-null type, it doesn't evaluate to null.
2245 if (auto nullability
2246 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2247 if (*nullability == NullabilityKind::NonNull)
2248 return false;
2249 }
2250
Ted Kremeneka146db32014-01-17 06:24:47 +00002251 // As a special case, transparent unions initialized with zero are
2252 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002253 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002254 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2255 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002256 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002257 if (const InitListExpr *ILE =
2258 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002259 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002260 }
2261
2262 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002263 return (!Expr->isValueDependent() &&
2264 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2265 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002266}
2267
2268static void CheckNonNullArgument(Sema &S,
2269 const Expr *ArgExpr,
2270 SourceLocation CallSiteLoc) {
2271 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002272 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2273 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002274}
2275
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002276bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2277 FormatStringInfo FSI;
2278 if ((GetFormatStringType(Format) == FST_NSString) &&
2279 getFormatStringInfo(Format, false, &FSI)) {
2280 Idx = FSI.FormatIdx;
2281 return true;
2282 }
2283 return false;
2284}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002285/// \brief Diagnose use of %s directive in an NSString which is being passed
2286/// as formatting string to formatting method.
2287static void
2288DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2289 const NamedDecl *FDecl,
2290 Expr **Args,
2291 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002292 unsigned Idx = 0;
2293 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002294 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2295 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002296 Idx = 2;
2297 Format = true;
2298 }
2299 else
2300 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2301 if (S.GetFormatNSStringIdx(I, Idx)) {
2302 Format = true;
2303 break;
2304 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002305 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002306 if (!Format || NumArgs <= Idx)
2307 return;
2308 const Expr *FormatExpr = Args[Idx];
2309 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2310 FormatExpr = CSCE->getSubExpr();
2311 const StringLiteral *FormatString;
2312 if (const ObjCStringLiteral *OSL =
2313 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2314 FormatString = OSL->getString();
2315 else
2316 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2317 if (!FormatString)
2318 return;
2319 if (S.FormatStringHasSArg(FormatString)) {
2320 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2321 << "%s" << 1 << 1;
2322 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2323 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002324 }
2325}
2326
Douglas Gregorb4866e82015-06-19 18:13:19 +00002327/// Determine whether the given type has a non-null nullability annotation.
2328static bool isNonNullType(ASTContext &ctx, QualType type) {
2329 if (auto nullability = type->getNullability(ctx))
2330 return *nullability == NullabilityKind::NonNull;
2331
2332 return false;
2333}
2334
Ted Kremenek2bc73332014-01-17 06:24:43 +00002335static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002336 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002337 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002338 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002339 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002340 assert((FDecl || Proto) && "Need a function declaration or prototype");
2341
Ted Kremenek9aedc152014-01-17 06:24:56 +00002342 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002343 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002344 if (FDecl) {
2345 // Handle the nonnull attribute on the function/method declaration itself.
2346 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2347 if (!NonNull->args_size()) {
2348 // Easy case: all pointer arguments are nonnull.
2349 for (const auto *Arg : Args)
2350 if (S.isValidPointerAttrType(Arg->getType()))
2351 CheckNonNullArgument(S, Arg, CallSiteLoc);
2352 return;
2353 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002354
Douglas Gregorb4866e82015-06-19 18:13:19 +00002355 for (unsigned Val : NonNull->args()) {
2356 if (Val >= Args.size())
2357 continue;
2358 if (NonNullArgs.empty())
2359 NonNullArgs.resize(Args.size());
2360 NonNullArgs.set(Val);
2361 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002362 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002363 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002364
Douglas Gregorb4866e82015-06-19 18:13:19 +00002365 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2366 // Handle the nonnull attribute on the parameters of the
2367 // function/method.
2368 ArrayRef<ParmVarDecl*> parms;
2369 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2370 parms = FD->parameters();
2371 else
2372 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2373
2374 unsigned ParamIndex = 0;
2375 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2376 I != E; ++I, ++ParamIndex) {
2377 const ParmVarDecl *PVD = *I;
2378 if (PVD->hasAttr<NonNullAttr>() ||
2379 isNonNullType(S.Context, PVD->getType())) {
2380 if (NonNullArgs.empty())
2381 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002382
Douglas Gregorb4866e82015-06-19 18:13:19 +00002383 NonNullArgs.set(ParamIndex);
2384 }
2385 }
2386 } else {
2387 // If we have a non-function, non-method declaration but no
2388 // function prototype, try to dig out the function prototype.
2389 if (!Proto) {
2390 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2391 QualType type = VD->getType().getNonReferenceType();
2392 if (auto pointerType = type->getAs<PointerType>())
2393 type = pointerType->getPointeeType();
2394 else if (auto blockType = type->getAs<BlockPointerType>())
2395 type = blockType->getPointeeType();
2396 // FIXME: data member pointers?
2397
2398 // Dig out the function prototype, if there is one.
2399 Proto = type->getAs<FunctionProtoType>();
2400 }
2401 }
2402
2403 // Fill in non-null argument information from the nullability
2404 // information on the parameter types (if we have them).
2405 if (Proto) {
2406 unsigned Index = 0;
2407 for (auto paramType : Proto->getParamTypes()) {
2408 if (isNonNullType(S.Context, paramType)) {
2409 if (NonNullArgs.empty())
2410 NonNullArgs.resize(Args.size());
2411
2412 NonNullArgs.set(Index);
2413 }
2414
2415 ++Index;
2416 }
2417 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002418 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002419
Douglas Gregorb4866e82015-06-19 18:13:19 +00002420 // Check for non-null arguments.
2421 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2422 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002423 if (NonNullArgs[ArgIndex])
2424 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002425 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002426}
2427
Richard Smith55ce3522012-06-25 20:30:08 +00002428/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00002429/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2430/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002431void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00002432 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2433 bool IsMemberFunction, SourceLocation Loc,
2434 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002435 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002436 if (CurContext->isDependentContext())
2437 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002438
Ted Kremenekb8176da2010-09-09 04:33:05 +00002439 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002440 llvm::SmallBitVector CheckedVarArgs;
2441 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002442 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002443 // Only create vector if there are format attributes.
2444 CheckedVarArgs.resize(Args.size());
2445
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002446 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002447 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002448 }
Richard Smithd7293d72013-08-05 18:49:43 +00002449 }
Richard Smith55ce3522012-06-25 20:30:08 +00002450
2451 // Refuse POD arguments that weren't caught by the format string
2452 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00002453 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2454 if (CallType != VariadicDoesNotApply &&
2455 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002456 unsigned NumParams = Proto ? Proto->getNumParams()
2457 : FDecl && isa<FunctionDecl>(FDecl)
2458 ? cast<FunctionDecl>(FDecl)->getNumParams()
2459 : FDecl && isa<ObjCMethodDecl>(FDecl)
2460 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2461 : 0;
2462
Alp Toker9cacbab2014-01-20 20:26:09 +00002463 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002464 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002465 if (const Expr *Arg = Args[ArgIdx]) {
2466 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2467 checkVariadicArgument(Arg, CallType);
2468 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002469 }
Richard Smithd7293d72013-08-05 18:49:43 +00002470 }
Mike Stump11289f42009-09-09 15:08:12 +00002471
Douglas Gregorb4866e82015-06-19 18:13:19 +00002472 if (FDecl || Proto) {
2473 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002474
Richard Trieu41bc0992013-06-22 00:20:41 +00002475 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002476 if (FDecl) {
2477 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2478 CheckArgumentWithTypeTag(I, Args.data());
2479 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002480 }
George Burgess IVce6284b2017-01-28 02:19:40 +00002481
2482 if (FD)
2483 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00002484}
2485
2486/// CheckConstructorCall - Check a constructor call for correctness and safety
2487/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002488void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2489 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002490 const FunctionProtoType *Proto,
2491 SourceLocation Loc) {
2492 VariadicCallType CallType =
2493 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00002494 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2495 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002496}
2497
2498/// CheckFunctionCall - Check a direct function call for various correctness
2499/// and safety properties not strictly enforced by the C type system.
2500bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2501 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002502 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2503 isa<CXXMethodDecl>(FDecl);
2504 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2505 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002506 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2507 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002508 Expr** Args = TheCall->getArgs();
2509 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00002510
2511 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00002512 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002513 // If this is a call to a member operator, hide the first argument
2514 // from checkCall.
2515 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00002516 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00002517 ++Args;
2518 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00002519 } else if (IsMemberFunction)
2520 ImplicitThis =
2521 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2522
2523 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002524 IsMemberFunction, TheCall->getRParenLoc(),
2525 TheCall->getCallee()->getSourceRange(), CallType);
2526
2527 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2528 // None of the checks below are needed for functions that don't have
2529 // simple names (e.g., C++ conversion functions).
2530 if (!FnInfo)
2531 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002532
Richard Trieua7f30b12016-12-06 01:42:28 +00002533 CheckAbsoluteValueFunction(TheCall, FDecl);
2534 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00002535
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002536 if (getLangOpts().ObjC1)
2537 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002538
Anna Zaks22122702012-01-17 00:37:07 +00002539 unsigned CMId = FDecl->getMemoryFunctionKind();
2540 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002541 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002542
Anna Zaks201d4892012-01-13 21:52:01 +00002543 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002544 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002545 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002546 else if (CMId == Builtin::BIstrncat)
2547 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002548 else
Anna Zaks22122702012-01-17 00:37:07 +00002549 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002550
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002551 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002552}
2553
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002554bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002555 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002556 VariadicCallType CallType =
2557 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002558
George Burgess IVce6284b2017-01-28 02:19:40 +00002559 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2560 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002561 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002562
2563 return false;
2564}
2565
Richard Trieu664c4c62013-06-20 21:03:13 +00002566bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2567 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002568 QualType Ty;
2569 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002570 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002571 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002572 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002573 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002574 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002575
Douglas Gregorb4866e82015-06-19 18:13:19 +00002576 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2577 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002578 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002579
Richard Trieu664c4c62013-06-20 21:03:13 +00002580 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002581 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002582 CallType = VariadicDoesNotApply;
2583 } else if (Ty->isBlockPointerType()) {
2584 CallType = VariadicBlock;
2585 } else { // Ty->isFunctionPointerType()
2586 CallType = VariadicFunction;
2587 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002588
George Burgess IVce6284b2017-01-28 02:19:40 +00002589 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002590 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2591 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002592 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002593
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002594 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002595}
2596
Richard Trieu41bc0992013-06-22 00:20:41 +00002597/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2598/// such as function pointers returned from functions.
2599bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002600 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002601 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00002602 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002603 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002604 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002605 TheCall->getCallee()->getSourceRange(), CallType);
2606
2607 return false;
2608}
2609
Tim Northovere94a34c2014-03-11 10:49:14 +00002610static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002611 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002612 return false;
2613
JF Bastiendda2cb12016-04-18 18:01:49 +00002614 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002615 switch (Op) {
2616 case AtomicExpr::AO__c11_atomic_init:
2617 llvm_unreachable("There is no ordering argument for an init");
2618
2619 case AtomicExpr::AO__c11_atomic_load:
2620 case AtomicExpr::AO__atomic_load_n:
2621 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002622 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2623 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002624
2625 case AtomicExpr::AO__c11_atomic_store:
2626 case AtomicExpr::AO__atomic_store:
2627 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002628 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2629 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2630 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002631
2632 default:
2633 return true;
2634 }
2635}
2636
Richard Smithfeea8832012-04-12 05:08:17 +00002637ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2638 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002639 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2640 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002641
Richard Smithfeea8832012-04-12 05:08:17 +00002642 // All these operations take one of the following forms:
2643 enum {
2644 // C __c11_atomic_init(A *, C)
2645 Init,
2646 // C __c11_atomic_load(A *, int)
2647 Load,
2648 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002649 LoadCopy,
2650 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002651 Copy,
2652 // C __c11_atomic_add(A *, M, int)
2653 Arithmetic,
2654 // C __atomic_exchange_n(A *, CP, int)
2655 Xchg,
2656 // void __atomic_exchange(A *, C *, CP, int)
2657 GNUXchg,
2658 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2659 C11CmpXchg,
2660 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2661 GNUCmpXchg
2662 } Form = Init;
Eric Fiselier8d662442016-03-30 23:39:56 +00002663 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2664 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002665 // where:
2666 // C is an appropriate type,
2667 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2668 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2669 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2670 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002671
Gabor Horvath98bd0982015-03-16 09:59:54 +00002672 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2673 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2674 AtomicExpr::AO__atomic_load,
2675 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00002676 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2677 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2678 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2679 Op == AtomicExpr::AO__atomic_store_n ||
2680 Op == AtomicExpr::AO__atomic_exchange_n ||
2681 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2682 bool IsAddSub = false;
2683
2684 switch (Op) {
2685 case AtomicExpr::AO__c11_atomic_init:
2686 Form = Init;
2687 break;
2688
2689 case AtomicExpr::AO__c11_atomic_load:
2690 case AtomicExpr::AO__atomic_load_n:
2691 Form = Load;
2692 break;
2693
Richard Smithfeea8832012-04-12 05:08:17 +00002694 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002695 Form = LoadCopy;
2696 break;
2697
2698 case AtomicExpr::AO__c11_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002699 case AtomicExpr::AO__atomic_store:
2700 case AtomicExpr::AO__atomic_store_n:
2701 Form = Copy;
2702 break;
2703
2704 case AtomicExpr::AO__c11_atomic_fetch_add:
2705 case AtomicExpr::AO__c11_atomic_fetch_sub:
2706 case AtomicExpr::AO__atomic_fetch_add:
2707 case AtomicExpr::AO__atomic_fetch_sub:
2708 case AtomicExpr::AO__atomic_add_fetch:
2709 case AtomicExpr::AO__atomic_sub_fetch:
2710 IsAddSub = true;
2711 // Fall through.
2712 case AtomicExpr::AO__c11_atomic_fetch_and:
2713 case AtomicExpr::AO__c11_atomic_fetch_or:
2714 case AtomicExpr::AO__c11_atomic_fetch_xor:
2715 case AtomicExpr::AO__atomic_fetch_and:
2716 case AtomicExpr::AO__atomic_fetch_or:
2717 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00002718 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00002719 case AtomicExpr::AO__atomic_and_fetch:
2720 case AtomicExpr::AO__atomic_or_fetch:
2721 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00002722 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00002723 Form = Arithmetic;
2724 break;
2725
2726 case AtomicExpr::AO__c11_atomic_exchange:
2727 case AtomicExpr::AO__atomic_exchange_n:
2728 Form = Xchg;
2729 break;
2730
2731 case AtomicExpr::AO__atomic_exchange:
2732 Form = GNUXchg;
2733 break;
2734
2735 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2736 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2737 Form = C11CmpXchg;
2738 break;
2739
2740 case AtomicExpr::AO__atomic_compare_exchange:
2741 case AtomicExpr::AO__atomic_compare_exchange_n:
2742 Form = GNUCmpXchg;
2743 break;
2744 }
2745
2746 // Check we have the right number of arguments.
2747 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002748 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002749 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002750 << TheCall->getCallee()->getSourceRange();
2751 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00002752 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2753 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002754 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002755 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002756 << TheCall->getCallee()->getSourceRange();
2757 return ExprError();
2758 }
2759
Richard Smithfeea8832012-04-12 05:08:17 +00002760 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002761 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00002762 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2763 if (ConvertedPtr.isInvalid())
2764 return ExprError();
2765
2766 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002767 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2768 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00002769 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002770 << Ptr->getType() << Ptr->getSourceRange();
2771 return ExprError();
2772 }
2773
Richard Smithfeea8832012-04-12 05:08:17 +00002774 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2775 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2776 QualType ValType = AtomTy; // 'C'
2777 if (IsC11) {
2778 if (!AtomTy->isAtomicType()) {
2779 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2780 << Ptr->getType() << Ptr->getSourceRange();
2781 return ExprError();
2782 }
Richard Smithe00921a2012-09-15 06:09:58 +00002783 if (AtomTy.isConstQualified()) {
2784 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2785 << Ptr->getType() << Ptr->getSourceRange();
2786 return ExprError();
2787 }
Richard Smithfeea8832012-04-12 05:08:17 +00002788 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00002789 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002790 if (ValType.isConstQualified()) {
2791 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2792 << Ptr->getType() << Ptr->getSourceRange();
2793 return ExprError();
2794 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002795 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002796
Richard Smithfeea8832012-04-12 05:08:17 +00002797 // For an arithmetic operation, the implied arithmetic must be well-formed.
2798 if (Form == Arithmetic) {
2799 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2800 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2801 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2802 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2803 return ExprError();
2804 }
2805 if (!IsAddSub && !ValType->isIntegerType()) {
2806 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2807 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2808 return ExprError();
2809 }
David Majnemere85cff82015-01-28 05:48:06 +00002810 if (IsC11 && ValType->isPointerType() &&
2811 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2812 diag::err_incomplete_type)) {
2813 return ExprError();
2814 }
Richard Smithfeea8832012-04-12 05:08:17 +00002815 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2816 // For __atomic_*_n operations, the value type must be a scalar integral or
2817 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002818 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00002819 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2820 return ExprError();
2821 }
2822
Eli Friedmanaa769812013-09-11 03:49:34 +00002823 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2824 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00002825 // For GNU atomics, require a trivially-copyable type. This is not part of
2826 // the GNU atomics specification, but we enforce it for sanity.
2827 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002828 << Ptr->getType() << Ptr->getSourceRange();
2829 return ExprError();
2830 }
2831
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002832 switch (ValType.getObjCLifetime()) {
2833 case Qualifiers::OCL_None:
2834 case Qualifiers::OCL_ExplicitNone:
2835 // okay
2836 break;
2837
2838 case Qualifiers::OCL_Weak:
2839 case Qualifiers::OCL_Strong:
2840 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002841 // FIXME: Can this happen? By this point, ValType should be known
2842 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002843 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2844 << ValType << Ptr->getSourceRange();
2845 return ExprError();
2846 }
2847
David Majnemerc6eb6502015-06-03 00:26:35 +00002848 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2849 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00002850 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00002851 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00002852 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002853 QualType ResultType = ValType;
Eric Fiselier8d662442016-03-30 23:39:56 +00002854 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002855 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002856 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002857 ResultType = Context.BoolTy;
2858
Richard Smithfeea8832012-04-12 05:08:17 +00002859 // The type of a parameter passed 'by value'. In the GNU atomics, such
2860 // arguments are actually passed as pointers.
2861 QualType ByValType = ValType; // 'CP'
2862 if (!IsC11 && !IsN)
2863 ByValType = Ptr->getType();
2864
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002865 // The first argument --- the pointer --- has a fixed type; we
2866 // deduce the types of the rest of the arguments accordingly. Walk
2867 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002868 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002869 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002870 if (i < NumVals[Form] + 1) {
2871 switch (i) {
2872 case 1:
2873 // The second argument is the non-atomic operand. For arithmetic, this
2874 // is always passed by value, and for a compare_exchange it is always
2875 // passed by address. For the rest, GNU uses by-address and C11 uses
2876 // by-value.
2877 assert(Form != Load);
2878 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2879 Ty = ValType;
2880 else if (Form == Copy || Form == Xchg)
2881 Ty = ByValType;
2882 else if (Form == Arithmetic)
2883 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002884 else {
2885 Expr *ValArg = TheCall->getArg(i);
Alex Lorenz67522152016-11-23 16:57:03 +00002886 // Treat this argument as _Nonnull as we want to show a warning if
2887 // NULL is passed into it.
2888 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002889 unsigned AS = 0;
2890 // Keep address space of non-atomic pointer type.
2891 if (const PointerType *PtrTy =
2892 ValArg->getType()->getAs<PointerType>()) {
2893 AS = PtrTy->getPointeeType().getAddressSpace();
2894 }
2895 Ty = Context.getPointerType(
2896 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2897 }
Richard Smithfeea8832012-04-12 05:08:17 +00002898 break;
2899 case 2:
2900 // The third argument to compare_exchange / GNU exchange is a
2901 // (pointer to a) desired value.
2902 Ty = ByValType;
2903 break;
2904 case 3:
2905 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2906 Ty = Context.BoolTy;
2907 break;
2908 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002909 } else {
2910 // The order(s) are always converted to int.
2911 Ty = Context.IntTy;
2912 }
Richard Smithfeea8832012-04-12 05:08:17 +00002913
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002914 InitializedEntity Entity =
2915 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00002916 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002917 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2918 if (Arg.isInvalid())
2919 return true;
2920 TheCall->setArg(i, Arg.get());
2921 }
2922
Richard Smithfeea8832012-04-12 05:08:17 +00002923 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002924 SmallVector<Expr*, 5> SubExprs;
2925 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00002926 switch (Form) {
2927 case Init:
2928 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00002929 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002930 break;
2931 case Load:
2932 SubExprs.push_back(TheCall->getArg(1)); // Order
2933 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00002934 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00002935 case Copy:
2936 case Arithmetic:
2937 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002938 SubExprs.push_back(TheCall->getArg(2)); // Order
2939 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002940 break;
2941 case GNUXchg:
2942 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2943 SubExprs.push_back(TheCall->getArg(3)); // Order
2944 SubExprs.push_back(TheCall->getArg(1)); // Val1
2945 SubExprs.push_back(TheCall->getArg(2)); // Val2
2946 break;
2947 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002948 SubExprs.push_back(TheCall->getArg(3)); // Order
2949 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002950 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00002951 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00002952 break;
2953 case GNUCmpXchg:
2954 SubExprs.push_back(TheCall->getArg(4)); // Order
2955 SubExprs.push_back(TheCall->getArg(1)); // Val1
2956 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2957 SubExprs.push_back(TheCall->getArg(2)); // Val2
2958 SubExprs.push_back(TheCall->getArg(3)); // Weak
2959 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002960 }
Tim Northovere94a34c2014-03-11 10:49:14 +00002961
2962 if (SubExprs.size() >= 2 && Form != Init) {
2963 llvm::APSInt Result(32);
2964 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2965 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00002966 Diag(SubExprs[1]->getLocStart(),
2967 diag::warn_atomic_op_has_invalid_memory_order)
2968 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00002969 }
2970
Fariborz Jahanian615de762013-05-28 17:37:39 +00002971 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2972 SubExprs, ResultType, Op,
2973 TheCall->getRParenLoc());
2974
2975 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2976 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2977 Context.AtomicUsesUnsupportedLibcall(AE))
2978 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2979 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002980
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002981 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002982}
2983
John McCall29ad95b2011-08-27 01:09:30 +00002984/// checkBuiltinArgument - Given a call to a builtin function, perform
2985/// normal type-checking on the given argument, updating the call in
2986/// place. This is useful when a builtin function requires custom
2987/// type-checking for some of its arguments but not necessarily all of
2988/// them.
2989///
2990/// Returns true on error.
2991static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2992 FunctionDecl *Fn = E->getDirectCallee();
2993 assert(Fn && "builtin call without direct callee!");
2994
2995 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2996 InitializedEntity Entity =
2997 InitializedEntity::InitializeParameter(S.Context, Param);
2998
2999 ExprResult Arg = E->getArg(0);
3000 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3001 if (Arg.isInvalid())
3002 return true;
3003
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003004 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003005 return false;
3006}
3007
Chris Lattnerdc046542009-05-08 06:58:22 +00003008/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3009/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3010/// type of its first argument. The main ActOnCallExpr routines have already
3011/// promoted the types of arguments because all of these calls are prototyped as
3012/// void(...).
3013///
3014/// This function goes through and does final semantic checking for these
3015/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003016ExprResult
3017Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003018 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003019 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3020 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3021
3022 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003023 if (TheCall->getNumArgs() < 1) {
3024 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3025 << 0 << 1 << TheCall->getNumArgs()
3026 << TheCall->getCallee()->getSourceRange();
3027 return ExprError();
3028 }
Mike Stump11289f42009-09-09 15:08:12 +00003029
Chris Lattnerdc046542009-05-08 06:58:22 +00003030 // Inspect the first argument of the atomic builtin. This should always be
3031 // a pointer type, whose element is an integral scalar or pointer type.
3032 // Because it is a pointer type, we don't have to worry about any implicit
3033 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003034 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003035 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003036 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3037 if (FirstArgResult.isInvalid())
3038 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003039 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003040 TheCall->setArg(0, FirstArg);
3041
John McCall31168b02011-06-15 23:02:42 +00003042 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3043 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003044 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3045 << FirstArg->getType() << FirstArg->getSourceRange();
3046 return ExprError();
3047 }
Mike Stump11289f42009-09-09 15:08:12 +00003048
John McCall31168b02011-06-15 23:02:42 +00003049 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003050 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003051 !ValType->isBlockPointerType()) {
3052 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3053 << FirstArg->getType() << FirstArg->getSourceRange();
3054 return ExprError();
3055 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003056
John McCall31168b02011-06-15 23:02:42 +00003057 switch (ValType.getObjCLifetime()) {
3058 case Qualifiers::OCL_None:
3059 case Qualifiers::OCL_ExplicitNone:
3060 // okay
3061 break;
3062
3063 case Qualifiers::OCL_Weak:
3064 case Qualifiers::OCL_Strong:
3065 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003066 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003067 << ValType << FirstArg->getSourceRange();
3068 return ExprError();
3069 }
3070
John McCallb50451a2011-10-05 07:41:44 +00003071 // Strip any qualifiers off ValType.
3072 ValType = ValType.getUnqualifiedType();
3073
Chandler Carruth3973af72010-07-18 20:54:12 +00003074 // The majority of builtins return a value, but a few have special return
3075 // types, so allow them to override appropriately below.
3076 QualType ResultType = ValType;
3077
Chris Lattnerdc046542009-05-08 06:58:22 +00003078 // We need to figure out which concrete builtin this maps onto. For example,
3079 // __sync_fetch_and_add with a 2 byte object turns into
3080 // __sync_fetch_and_add_2.
3081#define BUILTIN_ROW(x) \
3082 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3083 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003084
Chris Lattnerdc046542009-05-08 06:58:22 +00003085 static const unsigned BuiltinIndices[][5] = {
3086 BUILTIN_ROW(__sync_fetch_and_add),
3087 BUILTIN_ROW(__sync_fetch_and_sub),
3088 BUILTIN_ROW(__sync_fetch_and_or),
3089 BUILTIN_ROW(__sync_fetch_and_and),
3090 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003091 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003092
Chris Lattnerdc046542009-05-08 06:58:22 +00003093 BUILTIN_ROW(__sync_add_and_fetch),
3094 BUILTIN_ROW(__sync_sub_and_fetch),
3095 BUILTIN_ROW(__sync_and_and_fetch),
3096 BUILTIN_ROW(__sync_or_and_fetch),
3097 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003098 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003099
Chris Lattnerdc046542009-05-08 06:58:22 +00003100 BUILTIN_ROW(__sync_val_compare_and_swap),
3101 BUILTIN_ROW(__sync_bool_compare_and_swap),
3102 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003103 BUILTIN_ROW(__sync_lock_release),
3104 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003105 };
Mike Stump11289f42009-09-09 15:08:12 +00003106#undef BUILTIN_ROW
3107
Chris Lattnerdc046542009-05-08 06:58:22 +00003108 // Determine the index of the size.
3109 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003110 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003111 case 1: SizeIndex = 0; break;
3112 case 2: SizeIndex = 1; break;
3113 case 4: SizeIndex = 2; break;
3114 case 8: SizeIndex = 3; break;
3115 case 16: SizeIndex = 4; break;
3116 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003117 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3118 << FirstArg->getType() << FirstArg->getSourceRange();
3119 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003120 }
Mike Stump11289f42009-09-09 15:08:12 +00003121
Chris Lattnerdc046542009-05-08 06:58:22 +00003122 // Each of these builtins has one pointer argument, followed by some number of
3123 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3124 // that we ignore. Find out which row of BuiltinIndices to read from as well
3125 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003126 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003127 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003128 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003129 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003130 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003131 case Builtin::BI__sync_fetch_and_add:
3132 case Builtin::BI__sync_fetch_and_add_1:
3133 case Builtin::BI__sync_fetch_and_add_2:
3134 case Builtin::BI__sync_fetch_and_add_4:
3135 case Builtin::BI__sync_fetch_and_add_8:
3136 case Builtin::BI__sync_fetch_and_add_16:
3137 BuiltinIndex = 0;
3138 break;
3139
3140 case Builtin::BI__sync_fetch_and_sub:
3141 case Builtin::BI__sync_fetch_and_sub_1:
3142 case Builtin::BI__sync_fetch_and_sub_2:
3143 case Builtin::BI__sync_fetch_and_sub_4:
3144 case Builtin::BI__sync_fetch_and_sub_8:
3145 case Builtin::BI__sync_fetch_and_sub_16:
3146 BuiltinIndex = 1;
3147 break;
3148
3149 case Builtin::BI__sync_fetch_and_or:
3150 case Builtin::BI__sync_fetch_and_or_1:
3151 case Builtin::BI__sync_fetch_and_or_2:
3152 case Builtin::BI__sync_fetch_and_or_4:
3153 case Builtin::BI__sync_fetch_and_or_8:
3154 case Builtin::BI__sync_fetch_and_or_16:
3155 BuiltinIndex = 2;
3156 break;
3157
3158 case Builtin::BI__sync_fetch_and_and:
3159 case Builtin::BI__sync_fetch_and_and_1:
3160 case Builtin::BI__sync_fetch_and_and_2:
3161 case Builtin::BI__sync_fetch_and_and_4:
3162 case Builtin::BI__sync_fetch_and_and_8:
3163 case Builtin::BI__sync_fetch_and_and_16:
3164 BuiltinIndex = 3;
3165 break;
Mike Stump11289f42009-09-09 15:08:12 +00003166
Douglas Gregor73722482011-11-28 16:30:08 +00003167 case Builtin::BI__sync_fetch_and_xor:
3168 case Builtin::BI__sync_fetch_and_xor_1:
3169 case Builtin::BI__sync_fetch_and_xor_2:
3170 case Builtin::BI__sync_fetch_and_xor_4:
3171 case Builtin::BI__sync_fetch_and_xor_8:
3172 case Builtin::BI__sync_fetch_and_xor_16:
3173 BuiltinIndex = 4;
3174 break;
3175
Hal Finkeld2208b52014-10-02 20:53:50 +00003176 case Builtin::BI__sync_fetch_and_nand:
3177 case Builtin::BI__sync_fetch_and_nand_1:
3178 case Builtin::BI__sync_fetch_and_nand_2:
3179 case Builtin::BI__sync_fetch_and_nand_4:
3180 case Builtin::BI__sync_fetch_and_nand_8:
3181 case Builtin::BI__sync_fetch_and_nand_16:
3182 BuiltinIndex = 5;
3183 WarnAboutSemanticsChange = true;
3184 break;
3185
Douglas Gregor73722482011-11-28 16:30:08 +00003186 case Builtin::BI__sync_add_and_fetch:
3187 case Builtin::BI__sync_add_and_fetch_1:
3188 case Builtin::BI__sync_add_and_fetch_2:
3189 case Builtin::BI__sync_add_and_fetch_4:
3190 case Builtin::BI__sync_add_and_fetch_8:
3191 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003192 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003193 break;
3194
3195 case Builtin::BI__sync_sub_and_fetch:
3196 case Builtin::BI__sync_sub_and_fetch_1:
3197 case Builtin::BI__sync_sub_and_fetch_2:
3198 case Builtin::BI__sync_sub_and_fetch_4:
3199 case Builtin::BI__sync_sub_and_fetch_8:
3200 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003201 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003202 break;
3203
3204 case Builtin::BI__sync_and_and_fetch:
3205 case Builtin::BI__sync_and_and_fetch_1:
3206 case Builtin::BI__sync_and_and_fetch_2:
3207 case Builtin::BI__sync_and_and_fetch_4:
3208 case Builtin::BI__sync_and_and_fetch_8:
3209 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003210 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003211 break;
3212
3213 case Builtin::BI__sync_or_and_fetch:
3214 case Builtin::BI__sync_or_and_fetch_1:
3215 case Builtin::BI__sync_or_and_fetch_2:
3216 case Builtin::BI__sync_or_and_fetch_4:
3217 case Builtin::BI__sync_or_and_fetch_8:
3218 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003219 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003220 break;
3221
3222 case Builtin::BI__sync_xor_and_fetch:
3223 case Builtin::BI__sync_xor_and_fetch_1:
3224 case Builtin::BI__sync_xor_and_fetch_2:
3225 case Builtin::BI__sync_xor_and_fetch_4:
3226 case Builtin::BI__sync_xor_and_fetch_8:
3227 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003228 BuiltinIndex = 10;
3229 break;
3230
3231 case Builtin::BI__sync_nand_and_fetch:
3232 case Builtin::BI__sync_nand_and_fetch_1:
3233 case Builtin::BI__sync_nand_and_fetch_2:
3234 case Builtin::BI__sync_nand_and_fetch_4:
3235 case Builtin::BI__sync_nand_and_fetch_8:
3236 case Builtin::BI__sync_nand_and_fetch_16:
3237 BuiltinIndex = 11;
3238 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003239 break;
Mike Stump11289f42009-09-09 15:08:12 +00003240
Chris Lattnerdc046542009-05-08 06:58:22 +00003241 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003242 case Builtin::BI__sync_val_compare_and_swap_1:
3243 case Builtin::BI__sync_val_compare_and_swap_2:
3244 case Builtin::BI__sync_val_compare_and_swap_4:
3245 case Builtin::BI__sync_val_compare_and_swap_8:
3246 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003247 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003248 NumFixed = 2;
3249 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003250
Chris Lattnerdc046542009-05-08 06:58:22 +00003251 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003252 case Builtin::BI__sync_bool_compare_and_swap_1:
3253 case Builtin::BI__sync_bool_compare_and_swap_2:
3254 case Builtin::BI__sync_bool_compare_and_swap_4:
3255 case Builtin::BI__sync_bool_compare_and_swap_8:
3256 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003257 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003258 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003259 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003260 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003261
3262 case Builtin::BI__sync_lock_test_and_set:
3263 case Builtin::BI__sync_lock_test_and_set_1:
3264 case Builtin::BI__sync_lock_test_and_set_2:
3265 case Builtin::BI__sync_lock_test_and_set_4:
3266 case Builtin::BI__sync_lock_test_and_set_8:
3267 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003268 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003269 break;
3270
Chris Lattnerdc046542009-05-08 06:58:22 +00003271 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003272 case Builtin::BI__sync_lock_release_1:
3273 case Builtin::BI__sync_lock_release_2:
3274 case Builtin::BI__sync_lock_release_4:
3275 case Builtin::BI__sync_lock_release_8:
3276 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003277 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003278 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003279 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003280 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003281
3282 case Builtin::BI__sync_swap:
3283 case Builtin::BI__sync_swap_1:
3284 case Builtin::BI__sync_swap_2:
3285 case Builtin::BI__sync_swap_4:
3286 case Builtin::BI__sync_swap_8:
3287 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003288 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003289 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003290 }
Mike Stump11289f42009-09-09 15:08:12 +00003291
Chris Lattnerdc046542009-05-08 06:58:22 +00003292 // Now that we know how many fixed arguments we expect, first check that we
3293 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003294 if (TheCall->getNumArgs() < 1+NumFixed) {
3295 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3296 << 0 << 1+NumFixed << TheCall->getNumArgs()
3297 << TheCall->getCallee()->getSourceRange();
3298 return ExprError();
3299 }
Mike Stump11289f42009-09-09 15:08:12 +00003300
Hal Finkeld2208b52014-10-02 20:53:50 +00003301 if (WarnAboutSemanticsChange) {
3302 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3303 << TheCall->getCallee()->getSourceRange();
3304 }
3305
Chris Lattner5b9241b2009-05-08 15:36:58 +00003306 // Get the decl for the concrete builtin from this, we can tell what the
3307 // concrete integer type we should convert to is.
3308 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003309 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003310 FunctionDecl *NewBuiltinDecl;
3311 if (NewBuiltinID == BuiltinID)
3312 NewBuiltinDecl = FDecl;
3313 else {
3314 // Perform builtin lookup to avoid redeclaring it.
3315 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3316 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3317 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3318 assert(Res.getFoundDecl());
3319 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003320 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003321 return ExprError();
3322 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003323
John McCallcf142162010-08-07 06:22:56 +00003324 // The first argument --- the pointer --- has a fixed type; we
3325 // deduce the types of the rest of the arguments accordingly. Walk
3326 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003327 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003328 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003329
Chris Lattnerdc046542009-05-08 06:58:22 +00003330 // GCC does an implicit conversion to the pointer or integer ValType. This
3331 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003332 // Initialize the argument.
3333 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3334 ValType, /*consume*/ false);
3335 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003336 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003337 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003338
Chris Lattnerdc046542009-05-08 06:58:22 +00003339 // Okay, we have something that *can* be converted to the right type. Check
3340 // to see if there is a potentially weird extension going on here. This can
3341 // happen when you do an atomic operation on something like an char* and
3342 // pass in 42. The 42 gets converted to char. This is even more strange
3343 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003344 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003345 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003346 }
Mike Stump11289f42009-09-09 15:08:12 +00003347
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003348 ASTContext& Context = this->getASTContext();
3349
3350 // Create a new DeclRefExpr to refer to the new decl.
3351 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3352 Context,
3353 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003354 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003355 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003356 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003357 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003358 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003359 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003360
Chris Lattnerdc046542009-05-08 06:58:22 +00003361 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003362 // FIXME: This loses syntactic information.
3363 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3364 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3365 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003366 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003367
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003368 // Change the result type of the call to match the original value type. This
3369 // is arbitrary, but the codegen for these builtins ins design to handle it
3370 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003371 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003372
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003373 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003374}
3375
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003376/// SemaBuiltinNontemporalOverloaded - We have a call to
3377/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3378/// overloaded function based on the pointer type of its last argument.
3379///
3380/// This function goes through and does final semantic checking for these
3381/// builtins.
3382ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3383 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3384 DeclRefExpr *DRE =
3385 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3386 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3387 unsigned BuiltinID = FDecl->getBuiltinID();
3388 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3389 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3390 "Unexpected nontemporal load/store builtin!");
3391 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3392 unsigned numArgs = isStore ? 2 : 1;
3393
3394 // Ensure that we have the proper number of arguments.
3395 if (checkArgCount(*this, TheCall, numArgs))
3396 return ExprError();
3397
3398 // Inspect the last argument of the nontemporal builtin. This should always
3399 // be a pointer type, from which we imply the type of the memory access.
3400 // Because it is a pointer type, we don't have to worry about any implicit
3401 // casts here.
3402 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3403 ExprResult PointerArgResult =
3404 DefaultFunctionArrayLvalueConversion(PointerArg);
3405
3406 if (PointerArgResult.isInvalid())
3407 return ExprError();
3408 PointerArg = PointerArgResult.get();
3409 TheCall->setArg(numArgs - 1, PointerArg);
3410
3411 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3412 if (!pointerType) {
3413 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3414 << PointerArg->getType() << PointerArg->getSourceRange();
3415 return ExprError();
3416 }
3417
3418 QualType ValType = pointerType->getPointeeType();
3419
3420 // Strip any qualifiers off ValType.
3421 ValType = ValType.getUnqualifiedType();
3422 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3423 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3424 !ValType->isVectorType()) {
3425 Diag(DRE->getLocStart(),
3426 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3427 << PointerArg->getType() << PointerArg->getSourceRange();
3428 return ExprError();
3429 }
3430
3431 if (!isStore) {
3432 TheCall->setType(ValType);
3433 return TheCallResult;
3434 }
3435
3436 ExprResult ValArg = TheCall->getArg(0);
3437 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3438 Context, ValType, /*consume*/ false);
3439 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3440 if (ValArg.isInvalid())
3441 return ExprError();
3442
3443 TheCall->setArg(0, ValArg.get());
3444 TheCall->setType(Context.VoidTy);
3445 return TheCallResult;
3446}
3447
Chris Lattner6436fb62009-02-18 06:01:06 +00003448/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003449/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003450/// Note: It might also make sense to do the UTF-16 conversion here (would
3451/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003452bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003453 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003454 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3455
Douglas Gregorfb65e592011-07-27 05:40:30 +00003456 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003457 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3458 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003459 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003460 }
Mike Stump11289f42009-09-09 15:08:12 +00003461
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003462 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003463 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003464 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00003465 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3466 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3467 llvm::UTF16 *ToPtr = &ToBuf[0];
3468
3469 llvm::ConversionResult Result =
3470 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3471 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003472 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00003473 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003474 Diag(Arg->getLocStart(),
3475 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3476 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003477 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003478}
3479
Mehdi Amini06d367c2016-10-24 20:39:34 +00003480/// CheckObjCString - Checks that the format string argument to the os_log()
3481/// and os_trace() functions is correct, and converts it to const char *.
3482ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3483 Arg = Arg->IgnoreParenCasts();
3484 auto *Literal = dyn_cast<StringLiteral>(Arg);
3485 if (!Literal) {
3486 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3487 Literal = ObjcLiteral->getString();
3488 }
3489 }
3490
3491 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3492 return ExprError(
3493 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3494 << Arg->getSourceRange());
3495 }
3496
3497 ExprResult Result(Literal);
3498 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3499 InitializedEntity Entity =
3500 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3501 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3502 return Result;
3503}
3504
Charles Davisc7d5c942015-09-17 20:55:33 +00003505/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3506/// for validity. Emit an error and return true on failure; return false
3507/// on success.
3508bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003509 Expr *Fn = TheCall->getCallee();
3510 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003511 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003512 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003513 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3514 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003515 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003516 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003517 return true;
3518 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003519
3520 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003521 return Diag(TheCall->getLocEnd(),
3522 diag::err_typecheck_call_too_few_args_at_least)
3523 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003524 }
3525
John McCall29ad95b2011-08-27 01:09:30 +00003526 // Type-check the first argument normally.
3527 if (checkBuiltinArgument(*this, TheCall, 0))
3528 return true;
3529
Chris Lattnere202e6a2007-12-20 00:05:45 +00003530 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00003531 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00003532 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00003533 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00003534 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00003535 else if (FunctionDecl *FD = getCurFunctionDecl())
3536 isVariadic = FD->isVariadic();
3537 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00003538 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00003539
Chris Lattnere202e6a2007-12-20 00:05:45 +00003540 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003541 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3542 return true;
3543 }
Mike Stump11289f42009-09-09 15:08:12 +00003544
Chris Lattner43be2e62007-12-19 23:59:04 +00003545 // Verify that the second argument to the builtin is the last argument of the
3546 // current function or method.
3547 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003548 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003549
Nico Weber9eea7642013-05-24 23:31:57 +00003550 // These are valid if SecondArgIsLastNamedArgument is false after the next
3551 // block.
3552 QualType Type;
3553 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003554 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003555
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003556 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3557 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003558 // FIXME: This isn't correct for methods (results in bogus warning).
3559 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003560 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00003561 if (CurBlock)
David Majnemera3debed2016-06-24 05:33:44 +00003562 LastArg = CurBlock->TheDecl->parameters().back();
Steve Naroff439a3e42009-04-15 19:33:47 +00003563 else if (FunctionDecl *FD = getCurFunctionDecl())
David Majnemera3debed2016-06-24 05:33:44 +00003564 LastArg = FD->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003565 else
David Majnemera3debed2016-06-24 05:33:44 +00003566 LastArg = getCurMethodDecl()->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003567 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00003568
3569 Type = PV->getType();
3570 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003571 IsCRegister =
3572 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003573 }
3574 }
Mike Stump11289f42009-09-09 15:08:12 +00003575
Chris Lattner43be2e62007-12-19 23:59:04 +00003576 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003577 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003578 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003579 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00003580 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3581 // Promotable integers are UB, but enumerations need a bit of
3582 // extra checking to see what their promotable type actually is.
3583 if (!Type->isPromotableIntegerType())
3584 return false;
3585 if (!Type->isEnumeralType())
3586 return true;
3587 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3588 return !(ED &&
3589 Context.typesAreCompatible(ED->getPromotionType(), Type));
3590 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00003591 unsigned Reason = 0;
3592 if (Type->isReferenceType()) Reason = 1;
3593 else if (IsCRegister) Reason = 2;
3594 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003595 Diag(ParamLoc, diag::note_parameter_type) << Type;
3596 }
3597
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003598 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003599 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003600}
Chris Lattner43be2e62007-12-19 23:59:04 +00003601
Charles Davisc7d5c942015-09-17 20:55:33 +00003602/// Check the arguments to '__builtin_va_start' for validity, and that
3603/// it was called from a function of the native ABI.
3604/// Emit an error and return true on failure; return false on success.
3605bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3606 // On x86-64 Unix, don't allow this in Win64 ABI functions.
3607 // On x64 Windows, don't allow this in System V ABI functions.
3608 // (Yes, that means there's no corresponding way to support variadic
3609 // System V ABI functions on Windows.)
3610 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3611 unsigned OS = Context.getTargetInfo().getTriple().getOS();
3612 clang::CallingConv CC = CC_C;
3613 if (const FunctionDecl *FD = getCurFunctionDecl())
3614 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3615 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3616 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3617 return Diag(TheCall->getCallee()->getLocStart(),
3618 diag::err_va_start_used_in_wrong_abi_function)
3619 << (OS != llvm::Triple::Win32);
3620 }
3621 return SemaBuiltinVAStartImpl(TheCall);
3622}
3623
3624/// Check the arguments to '__builtin_ms_va_start' for validity, and that
3625/// it was called from a Win64 ABI function.
3626/// Emit an error and return true on failure; return false on success.
3627bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3628 // This only makes sense for x86-64.
3629 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3630 Expr *Callee = TheCall->getCallee();
3631 if (TT.getArch() != llvm::Triple::x86_64)
3632 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3633 // Don't allow this in System V ABI functions.
3634 clang::CallingConv CC = CC_C;
3635 if (const FunctionDecl *FD = getCurFunctionDecl())
3636 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3637 if (CC == CC_X86_64SysV ||
3638 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3639 return Diag(Callee->getLocStart(),
3640 diag::err_ms_va_start_used_in_sysv_function);
3641 return SemaBuiltinVAStartImpl(TheCall);
3642}
3643
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003644bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3645 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3646 // const char *named_addr);
3647
3648 Expr *Func = Call->getCallee();
3649
3650 if (Call->getNumArgs() < 3)
3651 return Diag(Call->getLocEnd(),
3652 diag::err_typecheck_call_too_few_args_at_least)
3653 << 0 /*function call*/ << 3 << Call->getNumArgs();
3654
3655 // Determine whether the current function is variadic or not.
3656 bool IsVariadic;
3657 if (BlockScopeInfo *CurBlock = getCurBlock())
3658 IsVariadic = CurBlock->TheDecl->isVariadic();
3659 else if (FunctionDecl *FD = getCurFunctionDecl())
3660 IsVariadic = FD->isVariadic();
3661 else if (ObjCMethodDecl *MD = getCurMethodDecl())
3662 IsVariadic = MD->isVariadic();
3663 else
3664 llvm_unreachable("unexpected statement type");
3665
3666 if (!IsVariadic) {
3667 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3668 return true;
3669 }
3670
3671 // Type-check the first argument normally.
3672 if (checkBuiltinArgument(*this, Call, 0))
3673 return true;
3674
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003675 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003676 unsigned ArgNo;
3677 QualType Type;
3678 } ArgumentTypes[] = {
3679 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3680 { 2, Context.getSizeType() },
3681 };
3682
3683 for (const auto &AT : ArgumentTypes) {
3684 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3685 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3686 continue;
3687 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3688 << Arg->getType() << AT.Type << 1 /* different class */
3689 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3690 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3691 }
3692
3693 return false;
3694}
3695
Chris Lattner2da14fb2007-12-20 00:26:33 +00003696/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3697/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003698bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3699 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003700 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003701 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003702 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003703 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003704 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003705 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003706 << SourceRange(TheCall->getArg(2)->getLocStart(),
3707 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003708
John Wiegley01296292011-04-08 18:41:53 +00003709 ExprResult OrigArg0 = TheCall->getArg(0);
3710 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003711
Chris Lattner2da14fb2007-12-20 00:26:33 +00003712 // Do standard promotions between the two arguments, returning their common
3713 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003714 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003715 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3716 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003717
3718 // Make sure any conversions are pushed back into the call; this is
3719 // type safe since unordered compare builtins are declared as "_Bool
3720 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003721 TheCall->setArg(0, OrigArg0.get());
3722 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003723
John Wiegley01296292011-04-08 18:41:53 +00003724 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003725 return false;
3726
Chris Lattner2da14fb2007-12-20 00:26:33 +00003727 // If the common type isn't a real floating type, then the arguments were
3728 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003729 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00003730 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003731 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00003732 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3733 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003734
Chris Lattner2da14fb2007-12-20 00:26:33 +00003735 return false;
3736}
3737
Benjamin Kramer634fc102010-02-15 22:42:31 +00003738/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3739/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00003740/// to check everything. We expect the last argument to be a floating point
3741/// value.
3742bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3743 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00003744 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003745 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00003746 if (TheCall->getNumArgs() > NumArgs)
3747 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003748 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003749 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00003750 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003751 (*(TheCall->arg_end()-1))->getLocEnd());
3752
Benjamin Kramer64aae502010-02-16 10:07:31 +00003753 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00003754
Eli Friedman7e4faac2009-08-31 20:06:00 +00003755 if (OrigArg->isTypeDependent())
3756 return false;
3757
Chris Lattner68784ef2010-05-06 05:50:07 +00003758 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00003759 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00003760 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003761 diag::err_typecheck_call_invalid_unary_fp)
3762 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003763
Neil Hickey88c0fac2016-12-13 16:22:50 +00003764 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00003765 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00003766 // Only remove standard FloatCasts, leaving other casts inplace
3767 if (Cast->getCastKind() == CK_FloatingCast) {
3768 Expr *CastArg = Cast->getSubExpr();
3769 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3770 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
3771 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
3772 "promotion from float to either float or double is the only expected cast here");
3773 Cast->setSubExpr(nullptr);
3774 TheCall->setArg(NumArgs-1, CastArg);
3775 }
Chris Lattner68784ef2010-05-06 05:50:07 +00003776 }
3777 }
3778
Eli Friedman7e4faac2009-08-31 20:06:00 +00003779 return false;
3780}
3781
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003782/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3783// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00003784ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00003785 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003786 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00003787 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00003788 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3789 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003790
Nate Begemana0110022010-06-08 00:16:34 +00003791 // Determine which of the following types of shufflevector we're checking:
3792 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00003793 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00003794 QualType resType = TheCall->getArg(0)->getType();
3795 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00003796
Douglas Gregorc25f7662009-05-19 22:10:17 +00003797 if (!TheCall->getArg(0)->isTypeDependent() &&
3798 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00003799 QualType LHSType = TheCall->getArg(0)->getType();
3800 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00003801
Craig Topperbaca3892013-07-29 06:47:04 +00003802 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3803 return ExprError(Diag(TheCall->getLocStart(),
3804 diag::err_shufflevector_non_vector)
3805 << SourceRange(TheCall->getArg(0)->getLocStart(),
3806 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003807
Nate Begemana0110022010-06-08 00:16:34 +00003808 numElements = LHSType->getAs<VectorType>()->getNumElements();
3809 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00003810
Nate Begemana0110022010-06-08 00:16:34 +00003811 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3812 // with mask. If so, verify that RHS is an integer vector type with the
3813 // same number of elts as lhs.
3814 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00003815 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00003816 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00003817 return ExprError(Diag(TheCall->getLocStart(),
3818 diag::err_shufflevector_incompatible_vector)
3819 << SourceRange(TheCall->getArg(1)->getLocStart(),
3820 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003821 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00003822 return ExprError(Diag(TheCall->getLocStart(),
3823 diag::err_shufflevector_incompatible_vector)
3824 << SourceRange(TheCall->getArg(0)->getLocStart(),
3825 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00003826 } else if (numElements != numResElements) {
3827 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00003828 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003829 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003830 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003831 }
3832
3833 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00003834 if (TheCall->getArg(i)->isTypeDependent() ||
3835 TheCall->getArg(i)->isValueDependent())
3836 continue;
3837
Nate Begemana0110022010-06-08 00:16:34 +00003838 llvm::APSInt Result(32);
3839 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3840 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003841 diag::err_shufflevector_nonconstant_argument)
3842 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003843
Craig Topper50ad5b72013-08-03 17:40:38 +00003844 // Allow -1 which will be translated to undef in the IR.
3845 if (Result.isSigned() && Result.isAllOnesValue())
3846 continue;
3847
Chris Lattner7ab824e2008-08-10 02:05:13 +00003848 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003849 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003850 diag::err_shufflevector_argument_too_large)
3851 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003852 }
3853
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003854 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003855
Chris Lattner7ab824e2008-08-10 02:05:13 +00003856 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003857 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00003858 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003859 }
3860
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003861 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3862 TheCall->getCallee()->getLocStart(),
3863 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003864}
Chris Lattner43be2e62007-12-19 23:59:04 +00003865
Hal Finkelc4d7c822013-09-18 03:29:45 +00003866/// SemaConvertVectorExpr - Handle __builtin_convertvector
3867ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3868 SourceLocation BuiltinLoc,
3869 SourceLocation RParenLoc) {
3870 ExprValueKind VK = VK_RValue;
3871 ExprObjectKind OK = OK_Ordinary;
3872 QualType DstTy = TInfo->getType();
3873 QualType SrcTy = E->getType();
3874
3875 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3876 return ExprError(Diag(BuiltinLoc,
3877 diag::err_convertvector_non_vector)
3878 << E->getSourceRange());
3879 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3880 return ExprError(Diag(BuiltinLoc,
3881 diag::err_convertvector_non_vector_type));
3882
3883 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3884 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3885 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3886 if (SrcElts != DstElts)
3887 return ExprError(Diag(BuiltinLoc,
3888 diag::err_convertvector_incompatible_vector)
3889 << E->getSourceRange());
3890 }
3891
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003892 return new (Context)
3893 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003894}
3895
Daniel Dunbarb7257262008-07-21 22:59:13 +00003896/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3897// This is declared to take (const void*, ...) and can take two
3898// optional constant int args.
3899bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003900 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003901
Chris Lattner3b054132008-11-19 05:08:23 +00003902 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003903 return Diag(TheCall->getLocEnd(),
3904 diag::err_typecheck_call_too_many_args_at_most)
3905 << 0 /*function call*/ << 3 << NumArgs
3906 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003907
3908 // Argument 0 is checked for us and the remaining arguments must be
3909 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003910 for (unsigned i = 1; i != NumArgs; ++i)
3911 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003912 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003913
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003914 return false;
3915}
3916
Hal Finkelf0417332014-07-17 14:25:55 +00003917/// SemaBuiltinAssume - Handle __assume (MS Extension).
3918// __assume does not evaluate its arguments, and should warn if its argument
3919// has side effects.
3920bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3921 Expr *Arg = TheCall->getArg(0);
3922 if (Arg->isInstantiationDependent()) return false;
3923
3924 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003925 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003926 << Arg->getSourceRange()
3927 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3928
3929 return false;
3930}
3931
David Majnemer86b1bfa2016-10-31 18:07:57 +00003932/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00003933/// as (size_t, size_t) where the second size_t must be a power of 2 greater
3934/// than 8.
3935bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
3936 // The alignment must be a constant integer.
3937 Expr *Arg = TheCall->getArg(1);
3938
3939 // We can't check the value of a dependent argument.
3940 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00003941 if (const auto *UE =
3942 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
3943 if (UE->getKind() == UETT_AlignOf)
3944 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
3945 << Arg->getSourceRange();
3946
David Majnemer51169932016-10-31 05:37:48 +00003947 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
3948
3949 if (!Result.isPowerOf2())
3950 return Diag(TheCall->getLocStart(),
3951 diag::err_alignment_not_power_of_two)
3952 << Arg->getSourceRange();
3953
3954 if (Result < Context.getCharWidth())
3955 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
3956 << (unsigned)Context.getCharWidth()
3957 << Arg->getSourceRange();
3958
3959 if (Result > INT32_MAX)
3960 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
3961 << INT32_MAX
3962 << Arg->getSourceRange();
3963 }
3964
3965 return false;
3966}
3967
3968/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00003969/// as (const void*, size_t, ...) and can take one optional constant int arg.
3970bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3971 unsigned NumArgs = TheCall->getNumArgs();
3972
3973 if (NumArgs > 3)
3974 return Diag(TheCall->getLocEnd(),
3975 diag::err_typecheck_call_too_many_args_at_most)
3976 << 0 /*function call*/ << 3 << NumArgs
3977 << TheCall->getSourceRange();
3978
3979 // The alignment must be a constant integer.
3980 Expr *Arg = TheCall->getArg(1);
3981
3982 // We can't check the value of a dependent argument.
3983 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3984 llvm::APSInt Result;
3985 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3986 return true;
3987
3988 if (!Result.isPowerOf2())
3989 return Diag(TheCall->getLocStart(),
3990 diag::err_alignment_not_power_of_two)
3991 << Arg->getSourceRange();
3992 }
3993
3994 if (NumArgs > 2) {
3995 ExprResult Arg(TheCall->getArg(2));
3996 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3997 Context.getSizeType(), false);
3998 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3999 if (Arg.isInvalid()) return true;
4000 TheCall->setArg(2, Arg.get());
4001 }
Hal Finkelf0417332014-07-17 14:25:55 +00004002
4003 return false;
4004}
4005
Mehdi Amini06d367c2016-10-24 20:39:34 +00004006bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4007 unsigned BuiltinID =
4008 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4009 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4010
4011 unsigned NumArgs = TheCall->getNumArgs();
4012 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4013 if (NumArgs < NumRequiredArgs) {
4014 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4015 << 0 /* function call */ << NumRequiredArgs << NumArgs
4016 << TheCall->getSourceRange();
4017 }
4018 if (NumArgs >= NumRequiredArgs + 0x100) {
4019 return Diag(TheCall->getLocEnd(),
4020 diag::err_typecheck_call_too_many_args_at_most)
4021 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4022 << TheCall->getSourceRange();
4023 }
4024 unsigned i = 0;
4025
4026 // For formatting call, check buffer arg.
4027 if (!IsSizeCall) {
4028 ExprResult Arg(TheCall->getArg(i));
4029 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4030 Context, Context.VoidPtrTy, false);
4031 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4032 if (Arg.isInvalid())
4033 return true;
4034 TheCall->setArg(i, Arg.get());
4035 i++;
4036 }
4037
4038 // Check string literal arg.
4039 unsigned FormatIdx = i;
4040 {
4041 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4042 if (Arg.isInvalid())
4043 return true;
4044 TheCall->setArg(i, Arg.get());
4045 i++;
4046 }
4047
4048 // Make sure variadic args are scalar.
4049 unsigned FirstDataArg = i;
4050 while (i < NumArgs) {
4051 ExprResult Arg = DefaultVariadicArgumentPromotion(
4052 TheCall->getArg(i), VariadicFunction, nullptr);
4053 if (Arg.isInvalid())
4054 return true;
4055 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4056 if (ArgSize.getQuantity() >= 0x100) {
4057 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4058 << i << (int)ArgSize.getQuantity() << 0xff
4059 << TheCall->getSourceRange();
4060 }
4061 TheCall->setArg(i, Arg.get());
4062 i++;
4063 }
4064
4065 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4066 // call to avoid duplicate diagnostics.
4067 if (!IsSizeCall) {
4068 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4069 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4070 bool Success = CheckFormatArguments(
4071 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4072 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4073 CheckedVarArgs);
4074 if (!Success)
4075 return true;
4076 }
4077
4078 if (IsSizeCall) {
4079 TheCall->setType(Context.getSizeType());
4080 } else {
4081 TheCall->setType(Context.VoidPtrTy);
4082 }
4083 return false;
4084}
4085
Eric Christopher8d0c6212010-04-17 02:26:23 +00004086/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4087/// TheCall is a constant expression.
4088bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4089 llvm::APSInt &Result) {
4090 Expr *Arg = TheCall->getArg(ArgNum);
4091 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4092 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4093
4094 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4095
4096 if (!Arg->isIntegerConstantExpr(Result, Context))
4097 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004098 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004099
Chris Lattnerd545ad12009-09-23 06:06:36 +00004100 return false;
4101}
4102
Richard Sandiford28940af2014-04-16 08:47:51 +00004103/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4104/// TheCall is a constant expression in the range [Low, High].
4105bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4106 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004107 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004108
4109 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004110 Expr *Arg = TheCall->getArg(ArgNum);
4111 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004112 return false;
4113
Eric Christopher8d0c6212010-04-17 02:26:23 +00004114 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004115 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004116 return true;
4117
Richard Sandiford28940af2014-04-16 08:47:51 +00004118 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004119 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004120 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004121
4122 return false;
4123}
4124
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004125/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4126/// TheCall is a constant expression is a multiple of Num..
4127bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4128 unsigned Num) {
4129 llvm::APSInt Result;
4130
4131 // We can't check the value of a dependent argument.
4132 Expr *Arg = TheCall->getArg(ArgNum);
4133 if (Arg->isTypeDependent() || Arg->isValueDependent())
4134 return false;
4135
4136 // Check constant-ness first.
4137 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4138 return true;
4139
4140 if (Result.getSExtValue() % Num != 0)
4141 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4142 << Num << Arg->getSourceRange();
4143
4144 return false;
4145}
4146
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004147/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4148/// TheCall is an ARM/AArch64 special register string literal.
4149bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4150 int ArgNum, unsigned ExpectedFieldNum,
4151 bool AllowName) {
4152 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4153 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4154 BuiltinID == ARM::BI__builtin_arm_rsr ||
4155 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4156 BuiltinID == ARM::BI__builtin_arm_wsr ||
4157 BuiltinID == ARM::BI__builtin_arm_wsrp;
4158 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4159 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4160 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4161 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4162 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4163 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4164 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4165
4166 // We can't check the value of a dependent argument.
4167 Expr *Arg = TheCall->getArg(ArgNum);
4168 if (Arg->isTypeDependent() || Arg->isValueDependent())
4169 return false;
4170
4171 // Check if the argument is a string literal.
4172 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4173 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4174 << Arg->getSourceRange();
4175
4176 // Check the type of special register given.
4177 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4178 SmallVector<StringRef, 6> Fields;
4179 Reg.split(Fields, ":");
4180
4181 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4182 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4183 << Arg->getSourceRange();
4184
4185 // If the string is the name of a register then we cannot check that it is
4186 // valid here but if the string is of one the forms described in ACLE then we
4187 // can check that the supplied fields are integers and within the valid
4188 // ranges.
4189 if (Fields.size() > 1) {
4190 bool FiveFields = Fields.size() == 5;
4191
4192 bool ValidString = true;
4193 if (IsARMBuiltin) {
4194 ValidString &= Fields[0].startswith_lower("cp") ||
4195 Fields[0].startswith_lower("p");
4196 if (ValidString)
4197 Fields[0] =
4198 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4199
4200 ValidString &= Fields[2].startswith_lower("c");
4201 if (ValidString)
4202 Fields[2] = Fields[2].drop_front(1);
4203
4204 if (FiveFields) {
4205 ValidString &= Fields[3].startswith_lower("c");
4206 if (ValidString)
4207 Fields[3] = Fields[3].drop_front(1);
4208 }
4209 }
4210
4211 SmallVector<int, 5> Ranges;
4212 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00004213 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004214 else
4215 Ranges.append({15, 7, 15});
4216
4217 for (unsigned i=0; i<Fields.size(); ++i) {
4218 int IntField;
4219 ValidString &= !Fields[i].getAsInteger(10, IntField);
4220 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4221 }
4222
4223 if (!ValidString)
4224 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4225 << Arg->getSourceRange();
4226
4227 } else if (IsAArch64Builtin && Fields.size() == 1) {
4228 // If the register name is one of those that appear in the condition below
4229 // and the special register builtin being used is one of the write builtins,
4230 // then we require that the argument provided for writing to the register
4231 // is an integer constant expression. This is because it will be lowered to
4232 // an MSR (immediate) instruction, so we need to know the immediate at
4233 // compile time.
4234 if (TheCall->getNumArgs() != 2)
4235 return false;
4236
4237 std::string RegLower = Reg.lower();
4238 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4239 RegLower != "pan" && RegLower != "uao")
4240 return false;
4241
4242 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4243 }
4244
4245 return false;
4246}
4247
Eli Friedmanc97d0142009-05-03 06:04:26 +00004248/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004249/// This checks that the target supports __builtin_longjmp and
4250/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004251bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004252 if (!Context.getTargetInfo().hasSjLjLowering())
4253 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4254 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4255
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004256 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004257 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004258
Eric Christopher8d0c6212010-04-17 02:26:23 +00004259 // TODO: This is less than ideal. Overload this to take a value.
4260 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4261 return true;
4262
4263 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004264 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4265 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4266
4267 return false;
4268}
4269
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004270/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4271/// This checks that the target supports __builtin_setjmp.
4272bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4273 if (!Context.getTargetInfo().hasSjLjLowering())
4274 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4275 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4276 return false;
4277}
4278
Richard Smithd7293d72013-08-05 18:49:43 +00004279namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004280class UncoveredArgHandler {
4281 enum { Unknown = -1, AllCovered = -2 };
4282 signed FirstUncoveredArg;
4283 SmallVector<const Expr *, 4> DiagnosticExprs;
4284
4285public:
4286 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4287
4288 bool hasUncoveredArg() const {
4289 return (FirstUncoveredArg >= 0);
4290 }
4291
4292 unsigned getUncoveredArg() const {
4293 assert(hasUncoveredArg() && "no uncovered argument");
4294 return FirstUncoveredArg;
4295 }
4296
4297 void setAllCovered() {
4298 // A string has been found with all arguments covered, so clear out
4299 // the diagnostics.
4300 DiagnosticExprs.clear();
4301 FirstUncoveredArg = AllCovered;
4302 }
4303
4304 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4305 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4306
4307 // Don't update if a previous string covers all arguments.
4308 if (FirstUncoveredArg == AllCovered)
4309 return;
4310
4311 // UncoveredArgHandler tracks the highest uncovered argument index
4312 // and with it all the strings that match this index.
4313 if (NewFirstUncoveredArg == FirstUncoveredArg)
4314 DiagnosticExprs.push_back(StrExpr);
4315 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4316 DiagnosticExprs.clear();
4317 DiagnosticExprs.push_back(StrExpr);
4318 FirstUncoveredArg = NewFirstUncoveredArg;
4319 }
4320 }
4321
4322 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4323};
4324
Richard Smithd7293d72013-08-05 18:49:43 +00004325enum StringLiteralCheckType {
4326 SLCT_NotALiteral,
4327 SLCT_UncheckedLiteral,
4328 SLCT_CheckedLiteral
4329};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004330} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00004331
Stephen Hines648c3692016-09-16 01:07:04 +00004332static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4333 BinaryOperatorKind BinOpKind,
4334 bool AddendIsRight) {
4335 unsigned BitWidth = Offset.getBitWidth();
4336 unsigned AddendBitWidth = Addend.getBitWidth();
4337 // There might be negative interim results.
4338 if (Addend.isUnsigned()) {
4339 Addend = Addend.zext(++AddendBitWidth);
4340 Addend.setIsSigned(true);
4341 }
4342 // Adjust the bit width of the APSInts.
4343 if (AddendBitWidth > BitWidth) {
4344 Offset = Offset.sext(AddendBitWidth);
4345 BitWidth = AddendBitWidth;
4346 } else if (BitWidth > AddendBitWidth) {
4347 Addend = Addend.sext(BitWidth);
4348 }
4349
4350 bool Ov = false;
4351 llvm::APSInt ResOffset = Offset;
4352 if (BinOpKind == BO_Add)
4353 ResOffset = Offset.sadd_ov(Addend, Ov);
4354 else {
4355 assert(AddendIsRight && BinOpKind == BO_Sub &&
4356 "operator must be add or sub with addend on the right");
4357 ResOffset = Offset.ssub_ov(Addend, Ov);
4358 }
4359
4360 // We add an offset to a pointer here so we should support an offset as big as
4361 // possible.
4362 if (Ov) {
4363 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00004364 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00004365 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4366 return;
4367 }
4368
4369 Offset = ResOffset;
4370}
4371
4372namespace {
4373// This is a wrapper class around StringLiteral to support offsetted string
4374// literals as format strings. It takes the offset into account when returning
4375// the string and its length or the source locations to display notes correctly.
4376class FormatStringLiteral {
4377 const StringLiteral *FExpr;
4378 int64_t Offset;
4379
4380 public:
4381 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4382 : FExpr(fexpr), Offset(Offset) {}
4383
4384 StringRef getString() const {
4385 return FExpr->getString().drop_front(Offset);
4386 }
4387
4388 unsigned getByteLength() const {
4389 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4390 }
4391 unsigned getLength() const { return FExpr->getLength() - Offset; }
4392 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4393
4394 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4395
4396 QualType getType() const { return FExpr->getType(); }
4397
4398 bool isAscii() const { return FExpr->isAscii(); }
4399 bool isWide() const { return FExpr->isWide(); }
4400 bool isUTF8() const { return FExpr->isUTF8(); }
4401 bool isUTF16() const { return FExpr->isUTF16(); }
4402 bool isUTF32() const { return FExpr->isUTF32(); }
4403 bool isPascal() const { return FExpr->isPascal(); }
4404
4405 SourceLocation getLocationOfByte(
4406 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4407 const TargetInfo &Target, unsigned *StartToken = nullptr,
4408 unsigned *StartTokenByteOffset = nullptr) const {
4409 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4410 StartToken, StartTokenByteOffset);
4411 }
4412
4413 SourceLocation getLocStart() const LLVM_READONLY {
4414 return FExpr->getLocStart().getLocWithOffset(Offset);
4415 }
4416 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4417};
4418} // end anonymous namespace
4419
4420static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004421 const Expr *OrigFormatExpr,
4422 ArrayRef<const Expr *> Args,
4423 bool HasVAListArg, unsigned format_idx,
4424 unsigned firstDataArg,
4425 Sema::FormatStringType Type,
4426 bool inFunctionCall,
4427 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004428 llvm::SmallBitVector &CheckedVarArgs,
4429 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004430
Richard Smith55ce3522012-06-25 20:30:08 +00004431// Determine if an expression is a string literal or constant string.
4432// If this function returns false on the arguments to a function expecting a
4433// format string, we will usually need to emit a warning.
4434// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00004435static StringLiteralCheckType
4436checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4437 bool HasVAListArg, unsigned format_idx,
4438 unsigned firstDataArg, Sema::FormatStringType Type,
4439 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004440 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004441 UncoveredArgHandler &UncoveredArg,
4442 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00004443 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00004444 assert(Offset.isSigned() && "invalid offset");
4445
Douglas Gregorc25f7662009-05-19 22:10:17 +00004446 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00004447 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004448
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004449 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00004450
Richard Smithd7293d72013-08-05 18:49:43 +00004451 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00004452 // Technically -Wformat-nonliteral does not warn about this case.
4453 // The behavior of printf and friends in this case is implementation
4454 // dependent. Ideally if the format string cannot be null then
4455 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00004456 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00004457
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004458 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00004459 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004460 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00004461 // The expression is a literal if both sub-expressions were, and it was
4462 // completely checked only if both sub-expressions were checked.
4463 const AbstractConditionalOperator *C =
4464 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004465
4466 // Determine whether it is necessary to check both sub-expressions, for
4467 // example, because the condition expression is a constant that can be
4468 // evaluated at compile time.
4469 bool CheckLeft = true, CheckRight = true;
4470
4471 bool Cond;
4472 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4473 if (Cond)
4474 CheckRight = false;
4475 else
4476 CheckLeft = false;
4477 }
4478
Stephen Hines648c3692016-09-16 01:07:04 +00004479 // We need to maintain the offsets for the right and the left hand side
4480 // separately to check if every possible indexed expression is a valid
4481 // string literal. They might have different offsets for different string
4482 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004483 StringLiteralCheckType Left;
4484 if (!CheckLeft)
4485 Left = SLCT_UncheckedLiteral;
4486 else {
4487 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4488 HasVAListArg, format_idx, firstDataArg,
4489 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004490 CheckedVarArgs, UncoveredArg, Offset);
4491 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004492 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004493 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004494 }
4495
Richard Smith55ce3522012-06-25 20:30:08 +00004496 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004497 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004498 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004499 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004500 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004501
4502 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004503 }
4504
4505 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00004506 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4507 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004508 }
4509
John McCallc07a0c72011-02-17 10:25:35 +00004510 case Stmt::OpaqueValueExprClass:
4511 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4512 E = src;
4513 goto tryAgain;
4514 }
Richard Smith55ce3522012-06-25 20:30:08 +00004515 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004516
Ted Kremeneka8890832011-02-24 23:03:04 +00004517 case Stmt::PredefinedExprClass:
4518 // While __func__, etc., are technically not string literals, they
4519 // cannot contain format specifiers and thus are not a security
4520 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004521 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004522
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004523 case Stmt::DeclRefExprClass: {
4524 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004525
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004526 // As an exception, do not flag errors for variables binding to
4527 // const string literals.
4528 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4529 bool isConstant = false;
4530 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004531
Richard Smithd7293d72013-08-05 18:49:43 +00004532 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4533 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004534 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004535 isConstant = T.isConstant(S.Context) &&
4536 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004537 } else if (T->isObjCObjectPointerType()) {
4538 // In ObjC, there is usually no "const ObjectPointer" type,
4539 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004540 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004541 }
Mike Stump11289f42009-09-09 15:08:12 +00004542
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004543 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004544 if (const Expr *Init = VD->getAnyInitializer()) {
4545 // Look through initializers like const char c[] = { "foo" }
4546 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4547 if (InitList->isStringLiteralInit())
4548 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4549 }
Richard Smithd7293d72013-08-05 18:49:43 +00004550 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004551 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004552 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004553 /*InFunctionCall*/ false, CheckedVarArgs,
4554 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004555 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004556 }
Mike Stump11289f42009-09-09 15:08:12 +00004557
Anders Carlssonb012ca92009-06-28 19:55:58 +00004558 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4559 // special check to see if the format string is a function parameter
4560 // of the function calling the printf function. If the function
4561 // has an attribute indicating it is a printf-like function, then we
4562 // should suppress warnings concerning non-literals being used in a call
4563 // to a vprintf function. For example:
4564 //
4565 // void
4566 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4567 // va_list ap;
4568 // va_start(ap, fmt);
4569 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4570 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00004571 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004572 if (HasVAListArg) {
4573 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4574 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4575 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004576 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004577 // adjust for implicit parameter
4578 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4579 if (MD->isInstance())
4580 ++PVIndex;
4581 // We also check if the formats are compatible.
4582 // We can't pass a 'scanf' string to a 'printf' function.
4583 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00004584 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00004585 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004586 }
4587 }
4588 }
4589 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004590 }
Mike Stump11289f42009-09-09 15:08:12 +00004591
Richard Smith55ce3522012-06-25 20:30:08 +00004592 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004593 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004594
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004595 case Stmt::CallExprClass:
4596 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004597 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004598 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4599 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4600 unsigned ArgIndex = FA->getFormatIdx();
4601 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4602 if (MD->isInstance())
4603 --ArgIndex;
4604 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00004605
Richard Smithd7293d72013-08-05 18:49:43 +00004606 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004607 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00004608 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004609 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004610 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4611 unsigned BuiltinID = FD->getBuiltinID();
4612 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4613 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4614 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00004615 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004616 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004617 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004618 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004619 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004620 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004621 }
4622 }
Mike Stump11289f42009-09-09 15:08:12 +00004623
Richard Smith55ce3522012-06-25 20:30:08 +00004624 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004625 }
Alex Lorenzd9007142016-10-24 09:42:34 +00004626 case Stmt::ObjCMessageExprClass: {
4627 const auto *ME = cast<ObjCMessageExpr>(E);
4628 if (const auto *ND = ME->getMethodDecl()) {
4629 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4630 unsigned ArgIndex = FA->getFormatIdx();
4631 const Expr *Arg = ME->getArg(ArgIndex - 1);
4632 return checkFormatStringExpr(
4633 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4634 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4635 }
4636 }
4637
4638 return SLCT_NotALiteral;
4639 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004640 case Stmt::ObjCStringLiteralClass:
4641 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00004642 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004643
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004644 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004645 StrE = ObjCFExpr->getString();
4646 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004647 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004648
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004649 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00004650 if (Offset.isNegative() || Offset > StrE->getLength()) {
4651 // TODO: It would be better to have an explicit warning for out of
4652 // bounds literals.
4653 return SLCT_NotALiteral;
4654 }
4655 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4656 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004657 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004658 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00004659 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004660 }
Mike Stump11289f42009-09-09 15:08:12 +00004661
Richard Smith55ce3522012-06-25 20:30:08 +00004662 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004663 }
Stephen Hines648c3692016-09-16 01:07:04 +00004664 case Stmt::BinaryOperatorClass: {
4665 llvm::APSInt LResult;
4666 llvm::APSInt RResult;
4667
4668 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4669
4670 // A string literal + an int offset is still a string literal.
4671 if (BinOp->isAdditiveOp()) {
4672 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4673 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4674
4675 if (LIsInt != RIsInt) {
4676 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4677
4678 if (LIsInt) {
4679 if (BinOpKind == BO_Add) {
4680 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4681 E = BinOp->getRHS();
4682 goto tryAgain;
4683 }
4684 } else {
4685 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4686 E = BinOp->getLHS();
4687 goto tryAgain;
4688 }
4689 }
Stephen Hines648c3692016-09-16 01:07:04 +00004690 }
George Burgess IVd273aab2016-09-22 00:00:26 +00004691
4692 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00004693 }
4694 case Stmt::UnaryOperatorClass: {
4695 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4696 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4697 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4698 llvm::APSInt IndexResult;
4699 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4700 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4701 E = ASE->getBase();
4702 goto tryAgain;
4703 }
4704 }
4705
4706 return SLCT_NotALiteral;
4707 }
Mike Stump11289f42009-09-09 15:08:12 +00004708
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004709 default:
Richard Smith55ce3522012-06-25 20:30:08 +00004710 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004711 }
4712}
4713
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004714Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00004715 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00004716 .Case("scanf", FST_Scanf)
4717 .Cases("printf", "printf0", FST_Printf)
4718 .Cases("NSString", "CFString", FST_NSString)
4719 .Case("strftime", FST_Strftime)
4720 .Case("strfmon", FST_Strfmon)
4721 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4722 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4723 .Case("os_trace", FST_OSLog)
4724 .Case("os_log", FST_OSLog)
4725 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004726}
4727
Jordan Rose3e0ec582012-07-19 18:10:23 +00004728/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00004729/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00004730/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004731bool Sema::CheckFormatArguments(const FormatAttr *Format,
4732 ArrayRef<const Expr *> Args,
4733 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004734 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004735 SourceLocation Loc, SourceRange Range,
4736 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00004737 FormatStringInfo FSI;
4738 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004739 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00004740 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00004741 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00004742 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004743}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00004744
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004745bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004746 bool HasVAListArg, unsigned format_idx,
4747 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004748 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004749 SourceLocation Loc, SourceRange Range,
4750 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004751 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004752 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004753 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00004754 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004755 }
Mike Stump11289f42009-09-09 15:08:12 +00004756
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004757 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004758
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004759 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00004760 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004761 // Dynamically generated format strings are difficult to
4762 // automatically vet at compile time. Requiring that format strings
4763 // are string literals: (1) permits the checking of format strings by
4764 // the compiler and thereby (2) can practically remove the source of
4765 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00004766
Mike Stump11289f42009-09-09 15:08:12 +00004767 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00004768 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00004769 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00004770 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004771 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00004772 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00004773 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4774 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004775 /*IsFunctionCall*/ true, CheckedVarArgs,
4776 UncoveredArg,
4777 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004778
4779 // Generate a diagnostic where an uncovered argument is detected.
4780 if (UncoveredArg.hasUncoveredArg()) {
4781 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4782 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4783 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4784 }
4785
Richard Smith55ce3522012-06-25 20:30:08 +00004786 if (CT != SLCT_NotALiteral)
4787 // Literal format string found, check done!
4788 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00004789
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004790 // Strftime is particular as it always uses a single 'time' argument,
4791 // so it is safe to pass a non-literal string.
4792 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00004793 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004794
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004795 // Do not emit diag when the string param is a macro expansion and the
4796 // format is either NSString or CFString. This is a hack to prevent
4797 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4798 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004799 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4800 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00004801 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004802
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004803 // If there are no arguments specified, warn with -Wformat-security, otherwise
4804 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004805 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00004806 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4807 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004808 switch (Type) {
4809 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004810 break;
4811 case FST_Kprintf:
4812 case FST_FreeBSDKPrintf:
4813 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00004814 Diag(FormatLoc, diag::note_format_security_fixit)
4815 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004816 break;
4817 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00004818 Diag(FormatLoc, diag::note_format_security_fixit)
4819 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004820 break;
4821 }
4822 } else {
4823 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004824 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004825 }
Richard Smith55ce3522012-06-25 20:30:08 +00004826 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004827}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004828
Ted Kremenekab278de2010-01-28 23:39:18 +00004829namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00004830class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4831protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00004832 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00004833 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00004834 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00004835 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00004836 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00004837 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00004838 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00004839 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004840 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00004841 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00004842 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00004843 bool usesPositionalArgs;
4844 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004845 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00004846 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00004847 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004848 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004849
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004850public:
Stephen Hines648c3692016-09-16 01:07:04 +00004851 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00004852 const Expr *origFormatExpr,
4853 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004854 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00004855 ArrayRef<const Expr *> Args, unsigned formatIdx,
4856 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004857 llvm::SmallBitVector &CheckedVarArgs,
4858 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00004859 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
4860 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
4861 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
4862 usesPositionalArgs(false), atFirstArg(true),
4863 inFunctionCall(inFunctionCall), CallType(callType),
4864 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00004865 CoveredArgs.resize(numDataArgs);
4866 CoveredArgs.reset();
4867 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004868
Ted Kremenek019d2242010-01-29 01:50:07 +00004869 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004870
Ted Kremenek02087932010-07-16 02:11:22 +00004871 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004872 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004873
Jordan Rose92303592012-09-08 04:00:03 +00004874 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004875 const analyze_format_string::FormatSpecifier &FS,
4876 const analyze_format_string::ConversionSpecifier &CS,
4877 const char *startSpecifier, unsigned specifierLen,
4878 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00004879
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004880 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004881 const analyze_format_string::FormatSpecifier &FS,
4882 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004883
4884 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004885 const analyze_format_string::ConversionSpecifier &CS,
4886 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004887
Craig Toppere14c0f82014-03-12 04:55:44 +00004888 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004889
Craig Toppere14c0f82014-03-12 04:55:44 +00004890 void HandleInvalidPosition(const char *startSpecifier,
4891 unsigned specifierLen,
4892 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004893
Craig Toppere14c0f82014-03-12 04:55:44 +00004894 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004895
Craig Toppere14c0f82014-03-12 04:55:44 +00004896 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004897
Richard Trieu03cf7b72011-10-28 00:41:25 +00004898 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00004899 static void
4900 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4901 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4902 bool IsStringLocation, Range StringRange,
4903 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004904
Ted Kremenek02087932010-07-16 02:11:22 +00004905protected:
Ted Kremenekce815422010-07-19 21:25:57 +00004906 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4907 const char *startSpec,
4908 unsigned specifierLen,
4909 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004910
4911 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4912 const char *startSpec,
4913 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00004914
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004915 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00004916 CharSourceRange getSpecifierRange(const char *startSpecifier,
4917 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00004918 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004919
Ted Kremenek5739de72010-01-29 01:06:55 +00004920 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004921
4922 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4923 const analyze_format_string::ConversionSpecifier &CS,
4924 const char *startSpecifier, unsigned specifierLen,
4925 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004926
4927 template <typename Range>
4928 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4929 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004930 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00004931};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004932} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004933
Ted Kremenek02087932010-07-16 02:11:22 +00004934SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00004935 return OrigFormatExpr->getSourceRange();
4936}
4937
Ted Kremenek02087932010-07-16 02:11:22 +00004938CharSourceRange CheckFormatHandler::
4939getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00004940 SourceLocation Start = getLocationOfByte(startSpecifier);
4941 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
4942
4943 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004944 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00004945
4946 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004947}
4948
Ted Kremenek02087932010-07-16 02:11:22 +00004949SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00004950 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
4951 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00004952}
4953
Ted Kremenek02087932010-07-16 02:11:22 +00004954void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4955 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00004956 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4957 getLocationOfByte(startSpecifier),
4958 /*IsStringLocation*/true,
4959 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00004960}
4961
Jordan Rose92303592012-09-08 04:00:03 +00004962void CheckFormatHandler::HandleInvalidLengthModifier(
4963 const analyze_format_string::FormatSpecifier &FS,
4964 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00004965 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00004966 using namespace analyze_format_string;
4967
4968 const LengthModifier &LM = FS.getLengthModifier();
4969 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4970
4971 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004972 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00004973 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004974 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004975 getLocationOfByte(LM.getStart()),
4976 /*IsStringLocation*/true,
4977 getSpecifierRange(startSpecifier, specifierLen));
4978
4979 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4980 << FixedLM->toString()
4981 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4982
4983 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004984 FixItHint Hint;
4985 if (DiagID == diag::warn_format_nonsensical_length)
4986 Hint = FixItHint::CreateRemoval(LMRange);
4987
4988 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004989 getLocationOfByte(LM.getStart()),
4990 /*IsStringLocation*/true,
4991 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00004992 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00004993 }
4994}
4995
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004996void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00004997 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004998 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004999 using namespace analyze_format_string;
5000
5001 const LengthModifier &LM = FS.getLengthModifier();
5002 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5003
5004 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005005 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005006 if (FixedLM) {
5007 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5008 << LM.toString() << 0,
5009 getLocationOfByte(LM.getStart()),
5010 /*IsStringLocation*/true,
5011 getSpecifierRange(startSpecifier, specifierLen));
5012
5013 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5014 << FixedLM->toString()
5015 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5016
5017 } else {
5018 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5019 << LM.toString() << 0,
5020 getLocationOfByte(LM.getStart()),
5021 /*IsStringLocation*/true,
5022 getSpecifierRange(startSpecifier, specifierLen));
5023 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005024}
5025
5026void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5027 const analyze_format_string::ConversionSpecifier &CS,
5028 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005029 using namespace analyze_format_string;
5030
5031 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005032 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005033 if (FixedCS) {
5034 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5035 << CS.toString() << /*conversion specifier*/1,
5036 getLocationOfByte(CS.getStart()),
5037 /*IsStringLocation*/true,
5038 getSpecifierRange(startSpecifier, specifierLen));
5039
5040 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5041 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5042 << FixedCS->toString()
5043 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5044 } else {
5045 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5046 << CS.toString() << /*conversion specifier*/1,
5047 getLocationOfByte(CS.getStart()),
5048 /*IsStringLocation*/true,
5049 getSpecifierRange(startSpecifier, specifierLen));
5050 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005051}
5052
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005053void CheckFormatHandler::HandlePosition(const char *startPos,
5054 unsigned posLen) {
5055 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5056 getLocationOfByte(startPos),
5057 /*IsStringLocation*/true,
5058 getSpecifierRange(startPos, posLen));
5059}
5060
Ted Kremenekd1668192010-02-27 01:41:03 +00005061void
Ted Kremenek02087932010-07-16 02:11:22 +00005062CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5063 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005064 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5065 << (unsigned) p,
5066 getLocationOfByte(startPos), /*IsStringLocation*/true,
5067 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005068}
5069
Ted Kremenek02087932010-07-16 02:11:22 +00005070void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005071 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005072 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5073 getLocationOfByte(startPos),
5074 /*IsStringLocation*/true,
5075 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005076}
5077
Ted Kremenek02087932010-07-16 02:11:22 +00005078void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005079 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005080 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005081 EmitFormatDiagnostic(
5082 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5083 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5084 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005085 }
Ted Kremenek02087932010-07-16 02:11:22 +00005086}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005087
Jordan Rose58bbe422012-07-19 18:10:08 +00005088// Note that this may return NULL if there was an error parsing or building
5089// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005090const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005091 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005092}
5093
5094void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005095 // Does the number of data arguments exceed the number of
5096 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005097 if (!HasVAListArg) {
5098 // Find any arguments that weren't covered.
5099 CoveredArgs.flip();
5100 signed notCoveredArg = CoveredArgs.find_first();
5101 if (notCoveredArg >= 0) {
5102 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005103 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5104 } else {
5105 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005106 }
5107 }
5108}
5109
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005110void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5111 const Expr *ArgExpr) {
5112 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5113 "Invalid state");
5114
5115 if (!ArgExpr)
5116 return;
5117
5118 SourceLocation Loc = ArgExpr->getLocStart();
5119
5120 if (S.getSourceManager().isInSystemMacro(Loc))
5121 return;
5122
5123 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5124 for (auto E : DiagnosticExprs)
5125 PDiag << E->getSourceRange();
5126
5127 CheckFormatHandler::EmitFormatDiagnostic(
5128 S, IsFunctionCall, DiagnosticExprs[0],
5129 PDiag, Loc, /*IsStringLocation*/false,
5130 DiagnosticExprs[0]->getSourceRange());
5131}
5132
Ted Kremenekce815422010-07-19 21:25:57 +00005133bool
5134CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5135 SourceLocation Loc,
5136 const char *startSpec,
5137 unsigned specifierLen,
5138 const char *csStart,
5139 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005140 bool keepGoing = true;
5141 if (argIndex < NumDataArgs) {
5142 // Consider the argument coverered, even though the specifier doesn't
5143 // make sense.
5144 CoveredArgs.set(argIndex);
5145 }
5146 else {
5147 // If argIndex exceeds the number of data arguments we
5148 // don't issue a warning because that is just a cascade of warnings (and
5149 // they may have intended '%%' anyway). We don't want to continue processing
5150 // the format string after this point, however, as we will like just get
5151 // gibberish when trying to match arguments.
5152 keepGoing = false;
5153 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005154
5155 StringRef Specifier(csStart, csLen);
5156
5157 // If the specifier in non-printable, it could be the first byte of a UTF-8
5158 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5159 // hex value.
5160 std::string CodePointStr;
5161 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005162 llvm::UTF32 CodePoint;
5163 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5164 const llvm::UTF8 *E =
5165 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5166 llvm::ConversionResult Result =
5167 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005168
Justin Lebar90910552016-09-30 00:38:45 +00005169 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005170 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005171 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005172 }
5173
5174 llvm::raw_string_ostream OS(CodePointStr);
5175 if (CodePoint < 256)
5176 OS << "\\x" << llvm::format("%02x", CodePoint);
5177 else if (CodePoint <= 0xFFFF)
5178 OS << "\\u" << llvm::format("%04x", CodePoint);
5179 else
5180 OS << "\\U" << llvm::format("%08x", CodePoint);
5181 OS.flush();
5182 Specifier = CodePointStr;
5183 }
5184
5185 EmitFormatDiagnostic(
5186 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5187 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5188
Ted Kremenekce815422010-07-19 21:25:57 +00005189 return keepGoing;
5190}
5191
Richard Trieu03cf7b72011-10-28 00:41:25 +00005192void
5193CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5194 const char *startSpec,
5195 unsigned specifierLen) {
5196 EmitFormatDiagnostic(
5197 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5198 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5199}
5200
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005201bool
5202CheckFormatHandler::CheckNumArgs(
5203 const analyze_format_string::FormatSpecifier &FS,
5204 const analyze_format_string::ConversionSpecifier &CS,
5205 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5206
5207 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005208 PartialDiagnostic PDiag = FS.usesPositionalArg()
5209 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5210 << (argIndex+1) << NumDataArgs)
5211 : S.PDiag(diag::warn_printf_insufficient_data_args);
5212 EmitFormatDiagnostic(
5213 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5214 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005215
5216 // Since more arguments than conversion tokens are given, by extension
5217 // all arguments are covered, so mark this as so.
5218 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005219 return false;
5220 }
5221 return true;
5222}
5223
Richard Trieu03cf7b72011-10-28 00:41:25 +00005224template<typename Range>
5225void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5226 SourceLocation Loc,
5227 bool IsStringLocation,
5228 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005229 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005230 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005231 Loc, IsStringLocation, StringRange, FixIt);
5232}
5233
5234/// \brief If the format string is not within the funcion call, emit a note
5235/// so that the function call and string are in diagnostic messages.
5236///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005237/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005238/// call and only one diagnostic message will be produced. Otherwise, an
5239/// extra note will be emitted pointing to location of the format string.
5240///
5241/// \param ArgumentExpr the expression that is passed as the format string
5242/// argument in the function call. Used for getting locations when two
5243/// diagnostics are emitted.
5244///
5245/// \param PDiag the callee should already have provided any strings for the
5246/// diagnostic message. This function only adds locations and fixits
5247/// to diagnostics.
5248///
5249/// \param Loc primary location for diagnostic. If two diagnostics are
5250/// required, one will be at Loc and a new SourceLocation will be created for
5251/// the other one.
5252///
5253/// \param IsStringLocation if true, Loc points to the format string should be
5254/// used for the note. Otherwise, Loc points to the argument list and will
5255/// be used with PDiag.
5256///
5257/// \param StringRange some or all of the string to highlight. This is
5258/// templated so it can accept either a CharSourceRange or a SourceRange.
5259///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005260/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005261template <typename Range>
5262void CheckFormatHandler::EmitFormatDiagnostic(
5263 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5264 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5265 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005266 if (InFunctionCall) {
5267 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5268 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005269 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00005270 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005271 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5272 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00005273
5274 const Sema::SemaDiagnosticBuilder &Note =
5275 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5276 diag::note_format_string_defined);
5277
5278 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005279 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005280 }
5281}
5282
Ted Kremenek02087932010-07-16 02:11:22 +00005283//===--- CHECK: Printf format string checking ------------------------------===//
5284
5285namespace {
5286class CheckPrintfHandler : public CheckFormatHandler {
5287public:
Stephen Hines648c3692016-09-16 01:07:04 +00005288 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005289 const Expr *origFormatExpr,
5290 const Sema::FormatStringType type, unsigned firstDataArg,
5291 unsigned numDataArgs, bool isObjC, const char *beg,
5292 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005293 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005294 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005295 llvm::SmallBitVector &CheckedVarArgs,
5296 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005297 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5298 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5299 inFunctionCall, CallType, CheckedVarArgs,
5300 UncoveredArg) {}
5301
5302 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5303
5304 /// Returns true if '%@' specifiers are allowed in the format string.
5305 bool allowsObjCArg() const {
5306 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5307 FSType == Sema::FST_OSTrace;
5308 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00005309
Ted Kremenek02087932010-07-16 02:11:22 +00005310 bool HandleInvalidPrintfConversionSpecifier(
5311 const analyze_printf::PrintfSpecifier &FS,
5312 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005313 unsigned specifierLen) override;
5314
Ted Kremenek02087932010-07-16 02:11:22 +00005315 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5316 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005317 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005318 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5319 const char *StartSpecifier,
5320 unsigned SpecifierLen,
5321 const Expr *E);
5322
Ted Kremenek02087932010-07-16 02:11:22 +00005323 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5324 const char *startSpecifier, unsigned specifierLen);
5325 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5326 const analyze_printf::OptionalAmount &Amt,
5327 unsigned type,
5328 const char *startSpecifier, unsigned specifierLen);
5329 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5330 const analyze_printf::OptionalFlag &flag,
5331 const char *startSpecifier, unsigned specifierLen);
5332 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5333 const analyze_printf::OptionalFlag &ignoredFlag,
5334 const analyze_printf::OptionalFlag &flag,
5335 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005336 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00005337 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00005338
5339 void HandleEmptyObjCModifierFlag(const char *startFlag,
5340 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005341
Ted Kremenek2b417712015-07-02 05:39:16 +00005342 void HandleInvalidObjCModifierFlag(const char *startFlag,
5343 unsigned flagLen) override;
5344
5345 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5346 const char *flagsEnd,
5347 const char *conversionPosition)
5348 override;
5349};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005350} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00005351
5352bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5353 const analyze_printf::PrintfSpecifier &FS,
5354 const char *startSpecifier,
5355 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005356 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005357 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005358
Ted Kremenekce815422010-07-19 21:25:57 +00005359 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5360 getLocationOfByte(CS.getStart()),
5361 startSpecifier, specifierLen,
5362 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00005363}
5364
Ted Kremenek02087932010-07-16 02:11:22 +00005365bool CheckPrintfHandler::HandleAmount(
5366 const analyze_format_string::OptionalAmount &Amt,
5367 unsigned k, const char *startSpecifier,
5368 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005369 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005370 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00005371 unsigned argIndex = Amt.getArgIndex();
5372 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005373 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5374 << k,
5375 getLocationOfByte(Amt.getStart()),
5376 /*IsStringLocation*/true,
5377 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005378 // Don't do any more checking. We will just emit
5379 // spurious errors.
5380 return false;
5381 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005382
Ted Kremenek5739de72010-01-29 01:06:55 +00005383 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00005384 // Although not in conformance with C99, we also allow the argument to be
5385 // an 'unsigned int' as that is a reasonably safe case. GCC also
5386 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00005387 CoveredArgs.set(argIndex);
5388 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005389 if (!Arg)
5390 return false;
5391
Ted Kremenek5739de72010-01-29 01:06:55 +00005392 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005393
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005394 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5395 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005396
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005397 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005398 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005399 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00005400 << T << Arg->getSourceRange(),
5401 getLocationOfByte(Amt.getStart()),
5402 /*IsStringLocation*/true,
5403 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005404 // Don't do any more checking. We will just emit
5405 // spurious errors.
5406 return false;
5407 }
5408 }
5409 }
5410 return true;
5411}
Ted Kremenek5739de72010-01-29 01:06:55 +00005412
Tom Careb49ec692010-06-17 19:00:27 +00005413void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00005414 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005415 const analyze_printf::OptionalAmount &Amt,
5416 unsigned type,
5417 const char *startSpecifier,
5418 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005419 const analyze_printf::PrintfConversionSpecifier &CS =
5420 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00005421
Richard Trieu03cf7b72011-10-28 00:41:25 +00005422 FixItHint fixit =
5423 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5424 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5425 Amt.getConstantLength()))
5426 : FixItHint();
5427
5428 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5429 << type << CS.toString(),
5430 getLocationOfByte(Amt.getStart()),
5431 /*IsStringLocation*/true,
5432 getSpecifierRange(startSpecifier, specifierLen),
5433 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00005434}
5435
Ted Kremenek02087932010-07-16 02:11:22 +00005436void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005437 const analyze_printf::OptionalFlag &flag,
5438 const char *startSpecifier,
5439 unsigned specifierLen) {
5440 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005441 const analyze_printf::PrintfConversionSpecifier &CS =
5442 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00005443 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5444 << flag.toString() << CS.toString(),
5445 getLocationOfByte(flag.getPosition()),
5446 /*IsStringLocation*/true,
5447 getSpecifierRange(startSpecifier, specifierLen),
5448 FixItHint::CreateRemoval(
5449 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005450}
5451
5452void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00005453 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005454 const analyze_printf::OptionalFlag &ignoredFlag,
5455 const analyze_printf::OptionalFlag &flag,
5456 const char *startSpecifier,
5457 unsigned specifierLen) {
5458 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005459 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5460 << ignoredFlag.toString() << flag.toString(),
5461 getLocationOfByte(ignoredFlag.getPosition()),
5462 /*IsStringLocation*/true,
5463 getSpecifierRange(startSpecifier, specifierLen),
5464 FixItHint::CreateRemoval(
5465 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005466}
5467
Ted Kremenek2b417712015-07-02 05:39:16 +00005468// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5469// bool IsStringLocation, Range StringRange,
5470// ArrayRef<FixItHint> Fixit = None);
5471
5472void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5473 unsigned flagLen) {
5474 // Warn about an empty flag.
5475 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5476 getLocationOfByte(startFlag),
5477 /*IsStringLocation*/true,
5478 getSpecifierRange(startFlag, flagLen));
5479}
5480
5481void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5482 unsigned flagLen) {
5483 // Warn about an invalid flag.
5484 auto Range = getSpecifierRange(startFlag, flagLen);
5485 StringRef flag(startFlag, flagLen);
5486 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5487 getLocationOfByte(startFlag),
5488 /*IsStringLocation*/true,
5489 Range, FixItHint::CreateRemoval(Range));
5490}
5491
5492void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5493 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5494 // Warn about using '[...]' without a '@' conversion.
5495 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5496 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5497 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5498 getLocationOfByte(conversionPosition),
5499 /*IsStringLocation*/true,
5500 Range, FixItHint::CreateRemoval(Range));
5501}
5502
Richard Smith55ce3522012-06-25 20:30:08 +00005503// Determines if the specified is a C++ class or struct containing
5504// a member with the specified name and kind (e.g. a CXXMethodDecl named
5505// "c_str()").
5506template<typename MemberKind>
5507static llvm::SmallPtrSet<MemberKind*, 1>
5508CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5509 const RecordType *RT = Ty->getAs<RecordType>();
5510 llvm::SmallPtrSet<MemberKind*, 1> Results;
5511
5512 if (!RT)
5513 return Results;
5514 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005515 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005516 return Results;
5517
Alp Tokerb6cc5922014-05-03 03:45:55 +00005518 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005519 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005520 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005521
5522 // We just need to include all members of the right kind turned up by the
5523 // filter, at this point.
5524 if (S.LookupQualifiedName(R, RT->getDecl()))
5525 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5526 NamedDecl *decl = (*I)->getUnderlyingDecl();
5527 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5528 Results.insert(FK);
5529 }
5530 return Results;
5531}
5532
Richard Smith2868a732014-02-28 01:36:39 +00005533/// Check if we could call '.c_str()' on an object.
5534///
5535/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5536/// allow the call, or if it would be ambiguous).
5537bool Sema::hasCStrMethod(const Expr *E) {
5538 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5539 MethodSet Results =
5540 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5541 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5542 MI != ME; ++MI)
5543 if ((*MI)->getMinRequiredArguments() == 0)
5544 return true;
5545 return false;
5546}
5547
Richard Smith55ce3522012-06-25 20:30:08 +00005548// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005549// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00005550// Returns true when a c_str() conversion method is found.
5551bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00005552 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00005553 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5554
5555 MethodSet Results =
5556 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5557
5558 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5559 MI != ME; ++MI) {
5560 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00005561 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00005562 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00005563 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00005564 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00005565 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5566 << "c_str()"
5567 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5568 return true;
5569 }
5570 }
5571
5572 return false;
5573}
5574
Ted Kremenekab278de2010-01-28 23:39:18 +00005575bool
Ted Kremenek02087932010-07-16 02:11:22 +00005576CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00005577 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00005578 const char *startSpecifier,
5579 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005580 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00005581 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005582 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00005583
Ted Kremenek6cd69422010-07-19 22:01:06 +00005584 if (FS.consumesDataArgument()) {
5585 if (atFirstArg) {
5586 atFirstArg = false;
5587 usesPositionalArgs = FS.usesPositionalArg();
5588 }
5589 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005590 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5591 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005592 return false;
5593 }
Ted Kremenek5739de72010-01-29 01:06:55 +00005594 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005595
Ted Kremenekd1668192010-02-27 01:41:03 +00005596 // First check if the field width, precision, and conversion specifier
5597 // have matching data arguments.
5598 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5599 startSpecifier, specifierLen)) {
5600 return false;
5601 }
5602
5603 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5604 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005605 return false;
5606 }
5607
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005608 if (!CS.consumesDataArgument()) {
5609 // FIXME: Technically specifying a precision or field width here
5610 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00005611 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005612 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005613
Ted Kremenek4a49d982010-02-26 19:18:41 +00005614 // Consume the argument.
5615 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00005616 if (argIndex < NumDataArgs) {
5617 // The check to see if the argIndex is valid will come later.
5618 // We set the bit here because we may exit early from this
5619 // function if we encounter some other error.
5620 CoveredArgs.set(argIndex);
5621 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00005622
Dimitry Andric6b5ed342015-02-19 22:32:33 +00005623 // FreeBSD kernel extensions.
5624 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5625 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5626 // We need at least two arguments.
5627 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5628 return false;
5629
5630 // Claim the second argument.
5631 CoveredArgs.set(argIndex + 1);
5632
5633 // Type check the first argument (int for %b, pointer for %D)
5634 const Expr *Ex = getDataArg(argIndex);
5635 const analyze_printf::ArgType &AT =
5636 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5637 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5638 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5639 EmitFormatDiagnostic(
5640 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5641 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5642 << false << Ex->getSourceRange(),
5643 Ex->getLocStart(), /*IsStringLocation*/false,
5644 getSpecifierRange(startSpecifier, specifierLen));
5645
5646 // Type check the second argument (char * for both %b and %D)
5647 Ex = getDataArg(argIndex + 1);
5648 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5649 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5650 EmitFormatDiagnostic(
5651 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5652 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5653 << false << Ex->getSourceRange(),
5654 Ex->getLocStart(), /*IsStringLocation*/false,
5655 getSpecifierRange(startSpecifier, specifierLen));
5656
5657 return true;
5658 }
5659
Ted Kremenek4a49d982010-02-26 19:18:41 +00005660 // Check for using an Objective-C specific conversion specifier
5661 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00005662 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00005663 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5664 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00005665 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005666
Mehdi Amini06d367c2016-10-24 20:39:34 +00005667 // %P can only be used with os_log.
5668 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
5669 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5670 specifierLen);
5671 }
5672
5673 // %n is not allowed with os_log.
5674 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
5675 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
5676 getLocationOfByte(CS.getStart()),
5677 /*IsStringLocation*/ false,
5678 getSpecifierRange(startSpecifier, specifierLen));
5679
5680 return true;
5681 }
5682
5683 // Only scalars are allowed for os_trace.
5684 if (FSType == Sema::FST_OSTrace &&
5685 (CS.getKind() == ConversionSpecifier::PArg ||
5686 CS.getKind() == ConversionSpecifier::sArg ||
5687 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
5688 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5689 specifierLen);
5690 }
5691
5692 // Check for use of public/private annotation outside of os_log().
5693 if (FSType != Sema::FST_OSLog) {
5694 if (FS.isPublic().isSet()) {
5695 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5696 << "public",
5697 getLocationOfByte(FS.isPublic().getPosition()),
5698 /*IsStringLocation*/ false,
5699 getSpecifierRange(startSpecifier, specifierLen));
5700 }
5701 if (FS.isPrivate().isSet()) {
5702 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5703 << "private",
5704 getLocationOfByte(FS.isPrivate().getPosition()),
5705 /*IsStringLocation*/ false,
5706 getSpecifierRange(startSpecifier, specifierLen));
5707 }
5708 }
5709
Tom Careb49ec692010-06-17 19:00:27 +00005710 // Check for invalid use of field width
5711 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00005712 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00005713 startSpecifier, specifierLen);
5714 }
5715
5716 // Check for invalid use of precision
5717 if (!FS.hasValidPrecision()) {
5718 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5719 startSpecifier, specifierLen);
5720 }
5721
Mehdi Amini06d367c2016-10-24 20:39:34 +00005722 // Precision is mandatory for %P specifier.
5723 if (CS.getKind() == ConversionSpecifier::PArg &&
5724 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
5725 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
5726 getLocationOfByte(startSpecifier),
5727 /*IsStringLocation*/ false,
5728 getSpecifierRange(startSpecifier, specifierLen));
5729 }
5730
Tom Careb49ec692010-06-17 19:00:27 +00005731 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00005732 if (!FS.hasValidThousandsGroupingPrefix())
5733 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005734 if (!FS.hasValidLeadingZeros())
5735 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5736 if (!FS.hasValidPlusPrefix())
5737 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00005738 if (!FS.hasValidSpacePrefix())
5739 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005740 if (!FS.hasValidAlternativeForm())
5741 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5742 if (!FS.hasValidLeftJustified())
5743 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5744
5745 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00005746 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5747 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5748 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005749 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5750 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5751 startSpecifier, specifierLen);
5752
5753 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005754 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005755 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5756 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005757 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005758 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005759 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005760 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5761 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00005762
Jordan Rose92303592012-09-08 04:00:03 +00005763 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5764 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5765
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005766 // The remaining checks depend on the data arguments.
5767 if (HasVAListArg)
5768 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005769
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005770 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005771 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005772
Jordan Rose58bbe422012-07-19 18:10:08 +00005773 const Expr *Arg = getDataArg(argIndex);
5774 if (!Arg)
5775 return true;
5776
5777 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00005778}
5779
Jordan Roseaee34382012-09-05 22:56:26 +00005780static bool requiresParensToAddCast(const Expr *E) {
5781 // FIXME: We should have a general way to reason about operator
5782 // precedence and whether parens are actually needed here.
5783 // Take care of a few common cases where they aren't.
5784 const Expr *Inside = E->IgnoreImpCasts();
5785 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5786 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5787
5788 switch (Inside->getStmtClass()) {
5789 case Stmt::ArraySubscriptExprClass:
5790 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005791 case Stmt::CharacterLiteralClass:
5792 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005793 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005794 case Stmt::FloatingLiteralClass:
5795 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005796 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005797 case Stmt::ObjCArrayLiteralClass:
5798 case Stmt::ObjCBoolLiteralExprClass:
5799 case Stmt::ObjCBoxedExprClass:
5800 case Stmt::ObjCDictionaryLiteralClass:
5801 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005802 case Stmt::ObjCIvarRefExprClass:
5803 case Stmt::ObjCMessageExprClass:
5804 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005805 case Stmt::ObjCStringLiteralClass:
5806 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005807 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005808 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005809 case Stmt::UnaryOperatorClass:
5810 return false;
5811 default:
5812 return true;
5813 }
5814}
5815
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005816static std::pair<QualType, StringRef>
5817shouldNotPrintDirectly(const ASTContext &Context,
5818 QualType IntendedTy,
5819 const Expr *E) {
5820 // Use a 'while' to peel off layers of typedefs.
5821 QualType TyTy = IntendedTy;
5822 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5823 StringRef Name = UserTy->getDecl()->getName();
5824 QualType CastTy = llvm::StringSwitch<QualType>(Name)
5825 .Case("NSInteger", Context.LongTy)
5826 .Case("NSUInteger", Context.UnsignedLongTy)
5827 .Case("SInt32", Context.IntTy)
5828 .Case("UInt32", Context.UnsignedIntTy)
5829 .Default(QualType());
5830
5831 if (!CastTy.isNull())
5832 return std::make_pair(CastTy, Name);
5833
5834 TyTy = UserTy->desugar();
5835 }
5836
5837 // Strip parens if necessary.
5838 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5839 return shouldNotPrintDirectly(Context,
5840 PE->getSubExpr()->getType(),
5841 PE->getSubExpr());
5842
5843 // If this is a conditional expression, then its result type is constructed
5844 // via usual arithmetic conversions and thus there might be no necessary
5845 // typedef sugar there. Recurse to operands to check for NSInteger &
5846 // Co. usage condition.
5847 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5848 QualType TrueTy, FalseTy;
5849 StringRef TrueName, FalseName;
5850
5851 std::tie(TrueTy, TrueName) =
5852 shouldNotPrintDirectly(Context,
5853 CO->getTrueExpr()->getType(),
5854 CO->getTrueExpr());
5855 std::tie(FalseTy, FalseName) =
5856 shouldNotPrintDirectly(Context,
5857 CO->getFalseExpr()->getType(),
5858 CO->getFalseExpr());
5859
5860 if (TrueTy == FalseTy)
5861 return std::make_pair(TrueTy, TrueName);
5862 else if (TrueTy.isNull())
5863 return std::make_pair(FalseTy, FalseName);
5864 else if (FalseTy.isNull())
5865 return std::make_pair(TrueTy, TrueName);
5866 }
5867
5868 return std::make_pair(QualType(), StringRef());
5869}
5870
Richard Smith55ce3522012-06-25 20:30:08 +00005871bool
5872CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5873 const char *StartSpecifier,
5874 unsigned SpecifierLen,
5875 const Expr *E) {
5876 using namespace analyze_format_string;
5877 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005878 // Now type check the data expression that matches the
5879 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00005880 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00005881 if (!AT.isValid())
5882 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00005883
Jordan Rose598ec092012-12-05 18:44:40 +00005884 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00005885 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5886 ExprTy = TET->getUnderlyingExpr()->getType();
5887 }
5888
Seth Cantrellb4802962015-03-04 03:12:10 +00005889 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5890
5891 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00005892 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005893 }
Jordan Rose98709982012-06-04 22:48:57 +00005894
Jordan Rose22b74712012-09-05 22:56:19 +00005895 // Look through argument promotions for our error message's reported type.
5896 // This includes the integral and floating promotions, but excludes array
5897 // and function pointer decay; seeing that an argument intended to be a
5898 // string has type 'char [6]' is probably more confusing than 'char *'.
5899 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5900 if (ICE->getCastKind() == CK_IntegralCast ||
5901 ICE->getCastKind() == CK_FloatingCast) {
5902 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00005903 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00005904
5905 // Check if we didn't match because of an implicit cast from a 'char'
5906 // or 'short' to an 'int'. This is done because printf is a varargs
5907 // function.
5908 if (ICE->getType() == S.Context.IntTy ||
5909 ICE->getType() == S.Context.UnsignedIntTy) {
5910 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00005911 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00005912 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00005913 }
Jordan Rose98709982012-06-04 22:48:57 +00005914 }
Jordan Rose598ec092012-12-05 18:44:40 +00005915 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5916 // Special case for 'a', which has type 'int' in C.
5917 // Note, however, that we do /not/ want to treat multibyte constants like
5918 // 'MooV' as characters! This form is deprecated but still exists.
5919 if (ExprTy == S.Context.IntTy)
5920 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5921 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00005922 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005923
Jordan Rosebc53ed12014-05-31 04:12:14 +00005924 // Look through enums to their underlying type.
5925 bool IsEnum = false;
5926 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5927 ExprTy = EnumTy->getDecl()->getIntegerType();
5928 IsEnum = true;
5929 }
5930
Jordan Rose0e5badd2012-12-05 18:44:49 +00005931 // %C in an Objective-C context prints a unichar, not a wchar_t.
5932 // If the argument is an integer of some kind, believe the %C and suggest
5933 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00005934 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005935 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00005936 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5937 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5938 !ExprTy->isCharType()) {
5939 // 'unichar' is defined as a typedef of unsigned short, but we should
5940 // prefer using the typedef if it is visible.
5941 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00005942
5943 // While we are here, check if the value is an IntegerLiteral that happens
5944 // to be within the valid range.
5945 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5946 const llvm::APInt &V = IL->getValue();
5947 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5948 return true;
5949 }
5950
Jordan Rose0e5badd2012-12-05 18:44:49 +00005951 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5952 Sema::LookupOrdinaryName);
5953 if (S.LookupName(Result, S.getCurScope())) {
5954 NamedDecl *ND = Result.getFoundDecl();
5955 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5956 if (TD->getUnderlyingType() == IntendedTy)
5957 IntendedTy = S.Context.getTypedefType(TD);
5958 }
5959 }
5960 }
5961
5962 // Special-case some of Darwin's platform-independence types by suggesting
5963 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005964 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00005965 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005966 QualType CastTy;
5967 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5968 if (!CastTy.isNull()) {
5969 IntendedTy = CastTy;
5970 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00005971 }
5972 }
5973
Jordan Rose22b74712012-09-05 22:56:19 +00005974 // We may be able to offer a FixItHint if it is a supported type.
5975 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005976 bool success =
5977 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005978
Jordan Rose22b74712012-09-05 22:56:19 +00005979 if (success) {
5980 // Get the fix string from the fixed format specifier
5981 SmallString<16> buf;
5982 llvm::raw_svector_ostream os(buf);
5983 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005984
Jordan Roseaee34382012-09-05 22:56:26 +00005985 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5986
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005987 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00005988 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5989 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5990 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5991 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00005992 // In this case, the specifier is wrong and should be changed to match
5993 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00005994 EmitFormatDiagnostic(S.PDiag(diag)
5995 << AT.getRepresentativeTypeName(S.Context)
5996 << IntendedTy << IsEnum << E->getSourceRange(),
5997 E->getLocStart(),
5998 /*IsStringLocation*/ false, SpecRange,
5999 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006000 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006001 // The canonical type for formatting this value is different from the
6002 // actual type of the expression. (This occurs, for example, with Darwin's
6003 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6004 // should be printed as 'long' for 64-bit compatibility.)
6005 // Rather than emitting a normal format/argument mismatch, we want to
6006 // add a cast to the recommended type (and correct the format string
6007 // if necessary).
6008 SmallString<16> CastBuf;
6009 llvm::raw_svector_ostream CastFix(CastBuf);
6010 CastFix << "(";
6011 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6012 CastFix << ")";
6013
6014 SmallVector<FixItHint,4> Hints;
6015 if (!AT.matchesType(S.Context, IntendedTy))
6016 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6017
6018 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6019 // If there's already a cast present, just replace it.
6020 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6021 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6022
6023 } else if (!requiresParensToAddCast(E)) {
6024 // If the expression has high enough precedence,
6025 // just write the C-style cast.
6026 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6027 CastFix.str()));
6028 } else {
6029 // Otherwise, add parens around the expression as well as the cast.
6030 CastFix << "(";
6031 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6032 CastFix.str()));
6033
Alp Tokerb6cc5922014-05-03 03:45:55 +00006034 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006035 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6036 }
6037
Jordan Rose0e5badd2012-12-05 18:44:49 +00006038 if (ShouldNotPrintDirectly) {
6039 // The expression has a type that should not be printed directly.
6040 // We extract the name from the typedef because we don't want to show
6041 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006042 StringRef Name;
6043 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6044 Name = TypedefTy->getDecl()->getName();
6045 else
6046 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006047 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006048 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006049 << E->getSourceRange(),
6050 E->getLocStart(), /*IsStringLocation=*/false,
6051 SpecRange, Hints);
6052 } else {
6053 // In this case, the expression could be printed using a different
6054 // specifier, but we've decided that the specifier is probably correct
6055 // and we should cast instead. Just use the normal warning message.
6056 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006057 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6058 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006059 << E->getSourceRange(),
6060 E->getLocStart(), /*IsStringLocation*/false,
6061 SpecRange, Hints);
6062 }
Jordan Roseaee34382012-09-05 22:56:26 +00006063 }
Jordan Rose22b74712012-09-05 22:56:19 +00006064 } else {
6065 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6066 SpecifierLen);
6067 // Since the warning for passing non-POD types to variadic functions
6068 // was deferred until now, we emit a warning for non-POD
6069 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006070 switch (S.isValidVarArgType(ExprTy)) {
6071 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006072 case Sema::VAK_ValidInCXX11: {
6073 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6074 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6075 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6076 }
Richard Smithd7293d72013-08-05 18:49:43 +00006077
Seth Cantrellb4802962015-03-04 03:12:10 +00006078 EmitFormatDiagnostic(
6079 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6080 << IsEnum << CSR << E->getSourceRange(),
6081 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6082 break;
6083 }
Richard Smithd7293d72013-08-05 18:49:43 +00006084 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006085 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006086 EmitFormatDiagnostic(
6087 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006088 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006089 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006090 << CallType
6091 << AT.getRepresentativeTypeName(S.Context)
6092 << CSR
6093 << E->getSourceRange(),
6094 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006095 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006096 break;
6097
6098 case Sema::VAK_Invalid:
6099 if (ExprTy->isObjCObjectType())
6100 EmitFormatDiagnostic(
6101 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6102 << S.getLangOpts().CPlusPlus11
6103 << ExprTy
6104 << CallType
6105 << AT.getRepresentativeTypeName(S.Context)
6106 << CSR
6107 << E->getSourceRange(),
6108 E->getLocStart(), /*IsStringLocation*/false, CSR);
6109 else
6110 // FIXME: If this is an initializer list, suggest removing the braces
6111 // or inserting a cast to the target type.
6112 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6113 << isa<InitListExpr>(E) << ExprTy << CallType
6114 << AT.getRepresentativeTypeName(S.Context)
6115 << E->getSourceRange();
6116 break;
6117 }
6118
6119 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6120 "format string specifier index out of range");
6121 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006122 }
6123
Ted Kremenekab278de2010-01-28 23:39:18 +00006124 return true;
6125}
6126
Ted Kremenek02087932010-07-16 02:11:22 +00006127//===--- CHECK: Scanf format string checking ------------------------------===//
6128
6129namespace {
6130class CheckScanfHandler : public CheckFormatHandler {
6131public:
Stephen Hines648c3692016-09-16 01:07:04 +00006132 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006133 const Expr *origFormatExpr, Sema::FormatStringType type,
6134 unsigned firstDataArg, unsigned numDataArgs,
6135 const char *beg, bool hasVAListArg,
6136 ArrayRef<const Expr *> Args, unsigned formatIdx,
6137 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006138 llvm::SmallBitVector &CheckedVarArgs,
6139 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006140 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6141 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6142 inFunctionCall, CallType, CheckedVarArgs,
6143 UncoveredArg) {}
6144
Ted Kremenek02087932010-07-16 02:11:22 +00006145 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6146 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006147 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006148
6149 bool HandleInvalidScanfConversionSpecifier(
6150 const analyze_scanf::ScanfSpecifier &FS,
6151 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006152 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006153
Craig Toppere14c0f82014-03-12 04:55:44 +00006154 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006155};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006156} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006157
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006158void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6159 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006160 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6161 getLocationOfByte(end), /*IsStringLocation*/true,
6162 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006163}
6164
Ted Kremenekce815422010-07-19 21:25:57 +00006165bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6166 const analyze_scanf::ScanfSpecifier &FS,
6167 const char *startSpecifier,
6168 unsigned specifierLen) {
6169
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006170 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006171 FS.getConversionSpecifier();
6172
6173 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6174 getLocationOfByte(CS.getStart()),
6175 startSpecifier, specifierLen,
6176 CS.getStart(), CS.getLength());
6177}
6178
Ted Kremenek02087932010-07-16 02:11:22 +00006179bool CheckScanfHandler::HandleScanfSpecifier(
6180 const analyze_scanf::ScanfSpecifier &FS,
6181 const char *startSpecifier,
6182 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006183 using namespace analyze_scanf;
6184 using namespace analyze_format_string;
6185
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006186 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006187
Ted Kremenek6cd69422010-07-19 22:01:06 +00006188 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6189 // be used to decide if we are using positional arguments consistently.
6190 if (FS.consumesDataArgument()) {
6191 if (atFirstArg) {
6192 atFirstArg = false;
6193 usesPositionalArgs = FS.usesPositionalArg();
6194 }
6195 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006196 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6197 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006198 return false;
6199 }
Ted Kremenek02087932010-07-16 02:11:22 +00006200 }
6201
6202 // Check if the field with is non-zero.
6203 const OptionalAmount &Amt = FS.getFieldWidth();
6204 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6205 if (Amt.getConstantAmount() == 0) {
6206 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6207 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006208 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6209 getLocationOfByte(Amt.getStart()),
6210 /*IsStringLocation*/true, R,
6211 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006212 }
6213 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006214
Ted Kremenek02087932010-07-16 02:11:22 +00006215 if (!FS.consumesDataArgument()) {
6216 // FIXME: Technically specifying a precision or field width here
6217 // makes no sense. Worth issuing a warning at some point.
6218 return true;
6219 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006220
Ted Kremenek02087932010-07-16 02:11:22 +00006221 // Consume the argument.
6222 unsigned argIndex = FS.getArgIndex();
6223 if (argIndex < NumDataArgs) {
6224 // The check to see if the argIndex is valid will come later.
6225 // We set the bit here because we may exit early from this
6226 // function if we encounter some other error.
6227 CoveredArgs.set(argIndex);
6228 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006229
Ted Kremenek4407ea42010-07-20 20:04:47 +00006230 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006231 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006232 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6233 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006234 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006235 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006236 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006237 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6238 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006239
Jordan Rose92303592012-09-08 04:00:03 +00006240 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6241 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6242
Ted Kremenek02087932010-07-16 02:11:22 +00006243 // The remaining checks depend on the data arguments.
6244 if (HasVAListArg)
6245 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006246
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006247 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006248 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006249
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006250 // Check that the argument type matches the format specifier.
6251 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006252 if (!Ex)
6253 return true;
6254
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006255 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006256
6257 if (!AT.isValid()) {
6258 return true;
6259 }
6260
Seth Cantrellb4802962015-03-04 03:12:10 +00006261 analyze_format_string::ArgType::MatchKind match =
6262 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006263 if (match == analyze_format_string::ArgType::Match) {
6264 return true;
6265 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006266
Seth Cantrell79340072015-03-04 05:58:08 +00006267 ScanfSpecifier fixedFS = FS;
6268 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6269 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006270
Seth Cantrell79340072015-03-04 05:58:08 +00006271 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6272 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6273 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6274 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006275
Seth Cantrell79340072015-03-04 05:58:08 +00006276 if (success) {
6277 // Get the fix string from the fixed format specifier.
6278 SmallString<128> buf;
6279 llvm::raw_svector_ostream os(buf);
6280 fixedFS.toString(os);
6281
6282 EmitFormatDiagnostic(
6283 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6284 << Ex->getType() << false << Ex->getSourceRange(),
6285 Ex->getLocStart(),
6286 /*IsStringLocation*/ false,
6287 getSpecifierRange(startSpecifier, specifierLen),
6288 FixItHint::CreateReplacement(
6289 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6290 } else {
6291 EmitFormatDiagnostic(S.PDiag(diag)
6292 << AT.getRepresentativeTypeName(S.Context)
6293 << Ex->getType() << false << Ex->getSourceRange(),
6294 Ex->getLocStart(),
6295 /*IsStringLocation*/ false,
6296 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006297 }
6298
Ted Kremenek02087932010-07-16 02:11:22 +00006299 return true;
6300}
6301
Stephen Hines648c3692016-09-16 01:07:04 +00006302static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006303 const Expr *OrigFormatExpr,
6304 ArrayRef<const Expr *> Args,
6305 bool HasVAListArg, unsigned format_idx,
6306 unsigned firstDataArg,
6307 Sema::FormatStringType Type,
6308 bool inFunctionCall,
6309 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006310 llvm::SmallBitVector &CheckedVarArgs,
6311 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00006312 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00006313 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006314 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006315 S, inFunctionCall, Args[format_idx],
6316 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006317 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006318 return;
6319 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006320
Ted Kremenekab278de2010-01-28 23:39:18 +00006321 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006322 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00006323 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006324 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006325 const ConstantArrayType *T =
6326 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006327 assert(T && "String literal not of constant array type!");
6328 size_t TypeSize = T->getSize().getZExtValue();
6329 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006330 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006331
6332 // Emit a warning if the string literal is truncated and does not contain an
6333 // embedded null character.
6334 if (TypeSize <= StrRef.size() &&
6335 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6336 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006337 S, inFunctionCall, Args[format_idx],
6338 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006339 FExpr->getLocStart(),
6340 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6341 return;
6342 }
6343
Ted Kremenekab278de2010-01-28 23:39:18 +00006344 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006345 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006346 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006347 S, inFunctionCall, Args[format_idx],
6348 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006349 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006350 return;
6351 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006352
6353 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00006354 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6355 Type == Sema::FST_OSTrace) {
6356 CheckPrintfHandler H(
6357 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6358 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6359 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6360 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006361
Hans Wennborg23926bd2011-12-15 10:25:47 +00006362 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006363 S.getLangOpts(),
6364 S.Context.getTargetInfo(),
6365 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006366 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006367 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00006368 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6369 numDataArgs, Str, HasVAListArg, Args, format_idx,
6370 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006371
Hans Wennborg23926bd2011-12-15 10:25:47 +00006372 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006373 S.getLangOpts(),
6374 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006375 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006376 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006377}
6378
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006379bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6380 // Str - The format string. NOTE: this is NOT null-terminated!
6381 StringRef StrRef = FExpr->getString();
6382 const char *Str = StrRef.data();
6383 // Account for cases where the string literal is truncated in a declaration.
6384 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6385 assert(T && "String literal not of constant array type!");
6386 size_t TypeSize = T->getSize().getZExtValue();
6387 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6388 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6389 getLangOpts(),
6390 Context.getTargetInfo());
6391}
6392
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006393//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6394
6395// Returns the related absolute value function that is larger, of 0 if one
6396// does not exist.
6397static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6398 switch (AbsFunction) {
6399 default:
6400 return 0;
6401
6402 case Builtin::BI__builtin_abs:
6403 return Builtin::BI__builtin_labs;
6404 case Builtin::BI__builtin_labs:
6405 return Builtin::BI__builtin_llabs;
6406 case Builtin::BI__builtin_llabs:
6407 return 0;
6408
6409 case Builtin::BI__builtin_fabsf:
6410 return Builtin::BI__builtin_fabs;
6411 case Builtin::BI__builtin_fabs:
6412 return Builtin::BI__builtin_fabsl;
6413 case Builtin::BI__builtin_fabsl:
6414 return 0;
6415
6416 case Builtin::BI__builtin_cabsf:
6417 return Builtin::BI__builtin_cabs;
6418 case Builtin::BI__builtin_cabs:
6419 return Builtin::BI__builtin_cabsl;
6420 case Builtin::BI__builtin_cabsl:
6421 return 0;
6422
6423 case Builtin::BIabs:
6424 return Builtin::BIlabs;
6425 case Builtin::BIlabs:
6426 return Builtin::BIllabs;
6427 case Builtin::BIllabs:
6428 return 0;
6429
6430 case Builtin::BIfabsf:
6431 return Builtin::BIfabs;
6432 case Builtin::BIfabs:
6433 return Builtin::BIfabsl;
6434 case Builtin::BIfabsl:
6435 return 0;
6436
6437 case Builtin::BIcabsf:
6438 return Builtin::BIcabs;
6439 case Builtin::BIcabs:
6440 return Builtin::BIcabsl;
6441 case Builtin::BIcabsl:
6442 return 0;
6443 }
6444}
6445
6446// Returns the argument type of the absolute value function.
6447static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6448 unsigned AbsType) {
6449 if (AbsType == 0)
6450 return QualType();
6451
6452 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6453 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6454 if (Error != ASTContext::GE_None)
6455 return QualType();
6456
6457 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6458 if (!FT)
6459 return QualType();
6460
6461 if (FT->getNumParams() != 1)
6462 return QualType();
6463
6464 return FT->getParamType(0);
6465}
6466
6467// Returns the best absolute value function, or zero, based on type and
6468// current absolute value function.
6469static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6470 unsigned AbsFunctionKind) {
6471 unsigned BestKind = 0;
6472 uint64_t ArgSize = Context.getTypeSize(ArgType);
6473 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6474 Kind = getLargerAbsoluteValueFunction(Kind)) {
6475 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6476 if (Context.getTypeSize(ParamType) >= ArgSize) {
6477 if (BestKind == 0)
6478 BestKind = Kind;
6479 else if (Context.hasSameType(ParamType, ArgType)) {
6480 BestKind = Kind;
6481 break;
6482 }
6483 }
6484 }
6485 return BestKind;
6486}
6487
6488enum AbsoluteValueKind {
6489 AVK_Integer,
6490 AVK_Floating,
6491 AVK_Complex
6492};
6493
6494static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6495 if (T->isIntegralOrEnumerationType())
6496 return AVK_Integer;
6497 if (T->isRealFloatingType())
6498 return AVK_Floating;
6499 if (T->isAnyComplexType())
6500 return AVK_Complex;
6501
6502 llvm_unreachable("Type not integer, floating, or complex");
6503}
6504
6505// Changes the absolute value function to a different type. Preserves whether
6506// the function is a builtin.
6507static unsigned changeAbsFunction(unsigned AbsKind,
6508 AbsoluteValueKind ValueKind) {
6509 switch (ValueKind) {
6510 case AVK_Integer:
6511 switch (AbsKind) {
6512 default:
6513 return 0;
6514 case Builtin::BI__builtin_fabsf:
6515 case Builtin::BI__builtin_fabs:
6516 case Builtin::BI__builtin_fabsl:
6517 case Builtin::BI__builtin_cabsf:
6518 case Builtin::BI__builtin_cabs:
6519 case Builtin::BI__builtin_cabsl:
6520 return Builtin::BI__builtin_abs;
6521 case Builtin::BIfabsf:
6522 case Builtin::BIfabs:
6523 case Builtin::BIfabsl:
6524 case Builtin::BIcabsf:
6525 case Builtin::BIcabs:
6526 case Builtin::BIcabsl:
6527 return Builtin::BIabs;
6528 }
6529 case AVK_Floating:
6530 switch (AbsKind) {
6531 default:
6532 return 0;
6533 case Builtin::BI__builtin_abs:
6534 case Builtin::BI__builtin_labs:
6535 case Builtin::BI__builtin_llabs:
6536 case Builtin::BI__builtin_cabsf:
6537 case Builtin::BI__builtin_cabs:
6538 case Builtin::BI__builtin_cabsl:
6539 return Builtin::BI__builtin_fabsf;
6540 case Builtin::BIabs:
6541 case Builtin::BIlabs:
6542 case Builtin::BIllabs:
6543 case Builtin::BIcabsf:
6544 case Builtin::BIcabs:
6545 case Builtin::BIcabsl:
6546 return Builtin::BIfabsf;
6547 }
6548 case AVK_Complex:
6549 switch (AbsKind) {
6550 default:
6551 return 0;
6552 case Builtin::BI__builtin_abs:
6553 case Builtin::BI__builtin_labs:
6554 case Builtin::BI__builtin_llabs:
6555 case Builtin::BI__builtin_fabsf:
6556 case Builtin::BI__builtin_fabs:
6557 case Builtin::BI__builtin_fabsl:
6558 return Builtin::BI__builtin_cabsf;
6559 case Builtin::BIabs:
6560 case Builtin::BIlabs:
6561 case Builtin::BIllabs:
6562 case Builtin::BIfabsf:
6563 case Builtin::BIfabs:
6564 case Builtin::BIfabsl:
6565 return Builtin::BIcabsf;
6566 }
6567 }
6568 llvm_unreachable("Unable to convert function");
6569}
6570
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006571static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006572 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6573 if (!FnInfo)
6574 return 0;
6575
6576 switch (FDecl->getBuiltinID()) {
6577 default:
6578 return 0;
6579 case Builtin::BI__builtin_abs:
6580 case Builtin::BI__builtin_fabs:
6581 case Builtin::BI__builtin_fabsf:
6582 case Builtin::BI__builtin_fabsl:
6583 case Builtin::BI__builtin_labs:
6584 case Builtin::BI__builtin_llabs:
6585 case Builtin::BI__builtin_cabs:
6586 case Builtin::BI__builtin_cabsf:
6587 case Builtin::BI__builtin_cabsl:
6588 case Builtin::BIabs:
6589 case Builtin::BIlabs:
6590 case Builtin::BIllabs:
6591 case Builtin::BIfabs:
6592 case Builtin::BIfabsf:
6593 case Builtin::BIfabsl:
6594 case Builtin::BIcabs:
6595 case Builtin::BIcabsf:
6596 case Builtin::BIcabsl:
6597 return FDecl->getBuiltinID();
6598 }
6599 llvm_unreachable("Unknown Builtin type");
6600}
6601
6602// If the replacement is valid, emit a note with replacement function.
6603// Additionally, suggest including the proper header if not already included.
6604static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00006605 unsigned AbsKind, QualType ArgType) {
6606 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006607 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00006608 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006609 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6610 FunctionName = "std::abs";
6611 if (ArgType->isIntegralOrEnumerationType()) {
6612 HeaderName = "cstdlib";
6613 } else if (ArgType->isRealFloatingType()) {
6614 HeaderName = "cmath";
6615 } else {
6616 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006617 }
Richard Trieubeffb832014-04-15 23:47:53 +00006618
6619 // Lookup all std::abs
6620 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00006621 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00006622 R.suppressDiagnostics();
6623 S.LookupQualifiedName(R, Std);
6624
6625 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006626 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006627 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6628 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6629 } else {
6630 FDecl = dyn_cast<FunctionDecl>(I);
6631 }
6632 if (!FDecl)
6633 continue;
6634
6635 // Found std::abs(), check that they are the right ones.
6636 if (FDecl->getNumParams() != 1)
6637 continue;
6638
6639 // Check that the parameter type can handle the argument.
6640 QualType ParamType = FDecl->getParamDecl(0)->getType();
6641 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6642 S.Context.getTypeSize(ArgType) <=
6643 S.Context.getTypeSize(ParamType)) {
6644 // Found a function, don't need the header hint.
6645 EmitHeaderHint = false;
6646 break;
6647 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006648 }
Richard Trieubeffb832014-04-15 23:47:53 +00006649 }
6650 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00006651 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00006652 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6653
6654 if (HeaderName) {
6655 DeclarationName DN(&S.Context.Idents.get(FunctionName));
6656 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6657 R.suppressDiagnostics();
6658 S.LookupName(R, S.getCurScope());
6659
6660 if (R.isSingleResult()) {
6661 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6662 if (FD && FD->getBuiltinID() == AbsKind) {
6663 EmitHeaderHint = false;
6664 } else {
6665 return;
6666 }
6667 } else if (!R.empty()) {
6668 return;
6669 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006670 }
6671 }
6672
6673 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00006674 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006675
Richard Trieubeffb832014-04-15 23:47:53 +00006676 if (!HeaderName)
6677 return;
6678
6679 if (!EmitHeaderHint)
6680 return;
6681
Alp Toker5d96e0a2014-07-11 20:53:51 +00006682 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6683 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00006684}
6685
Richard Trieua7f30b12016-12-06 01:42:28 +00006686template <std::size_t StrLen>
6687static bool IsStdFunction(const FunctionDecl *FDecl,
6688 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00006689 if (!FDecl)
6690 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00006691 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00006692 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00006693 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00006694 return false;
6695
6696 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006697}
6698
6699// Warn when using the wrong abs() function.
6700void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00006701 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006702 if (Call->getNumArgs() != 1)
6703 return;
6704
6705 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00006706 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00006707 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006708 return;
6709
6710 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6711 QualType ParamType = Call->getArg(0)->getType();
6712
Alp Toker5d96e0a2014-07-11 20:53:51 +00006713 // Unsigned types cannot be negative. Suggest removing the absolute value
6714 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006715 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00006716 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00006717 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006718 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6719 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00006720 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006721 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6722 return;
6723 }
6724
David Majnemer7f77eb92015-11-15 03:04:34 +00006725 // Taking the absolute value of a pointer is very suspicious, they probably
6726 // wanted to index into an array, dereference a pointer, call a function, etc.
6727 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6728 unsigned DiagType = 0;
6729 if (ArgType->isFunctionType())
6730 DiagType = 1;
6731 else if (ArgType->isArrayType())
6732 DiagType = 2;
6733
6734 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6735 return;
6736 }
6737
Richard Trieubeffb832014-04-15 23:47:53 +00006738 // std::abs has overloads which prevent most of the absolute value problems
6739 // from occurring.
6740 if (IsStdAbs)
6741 return;
6742
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006743 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6744 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6745
6746 // The argument and parameter are the same kind. Check if they are the right
6747 // size.
6748 if (ArgValueKind == ParamValueKind) {
6749 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6750 return;
6751
6752 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6753 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6754 << FDecl << ArgType << ParamType;
6755
6756 if (NewAbsKind == 0)
6757 return;
6758
6759 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006760 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006761 return;
6762 }
6763
6764 // ArgValueKind != ParamValueKind
6765 // The wrong type of absolute value function was used. Attempt to find the
6766 // proper one.
6767 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6768 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6769 if (NewAbsKind == 0)
6770 return;
6771
6772 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6773 << FDecl << ParamValueKind << ArgValueKind;
6774
6775 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006776 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006777}
6778
Richard Trieu67c00712016-12-05 23:41:46 +00006779//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00006780void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
6781 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00006782 if (!Call || !FDecl) return;
6783
6784 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00006785 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00006786 if (Call->getExprLoc().isMacroID()) return;
6787
6788 // Only care about the one template argument, two function parameter std::max
6789 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00006790 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00006791 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
6792 if (!ArgList) return;
6793 if (ArgList->size() != 1) return;
6794
6795 // Check that template type argument is unsigned integer.
6796 const auto& TA = ArgList->get(0);
6797 if (TA.getKind() != TemplateArgument::Type) return;
6798 QualType ArgType = TA.getAsType();
6799 if (!ArgType->isUnsignedIntegerType()) return;
6800
6801 // See if either argument is a literal zero.
6802 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
6803 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
6804 if (!MTE) return false;
6805 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
6806 if (!Num) return false;
6807 if (Num->getValue() != 0) return false;
6808 return true;
6809 };
6810
6811 const Expr *FirstArg = Call->getArg(0);
6812 const Expr *SecondArg = Call->getArg(1);
6813 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
6814 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
6815
6816 // Only warn when exactly one argument is zero.
6817 if (IsFirstArgZero == IsSecondArgZero) return;
6818
6819 SourceRange FirstRange = FirstArg->getSourceRange();
6820 SourceRange SecondRange = SecondArg->getSourceRange();
6821
6822 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
6823
6824 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
6825 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
6826
6827 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
6828 SourceRange RemovalRange;
6829 if (IsFirstArgZero) {
6830 RemovalRange = SourceRange(FirstRange.getBegin(),
6831 SecondRange.getBegin().getLocWithOffset(-1));
6832 } else {
6833 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
6834 SecondRange.getEnd());
6835 }
6836
6837 Diag(Call->getExprLoc(), diag::note_remove_max_call)
6838 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
6839 << FixItHint::CreateRemoval(RemovalRange);
6840}
6841
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006842//===--- CHECK: Standard memory functions ---------------------------------===//
6843
Nico Weber0e6daef2013-12-26 23:38:39 +00006844/// \brief Takes the expression passed to the size_t parameter of functions
6845/// such as memcmp, strncat, etc and warns if it's a comparison.
6846///
6847/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6848static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6849 IdentifierInfo *FnName,
6850 SourceLocation FnLoc,
6851 SourceLocation RParenLoc) {
6852 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6853 if (!Size)
6854 return false;
6855
6856 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6857 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6858 return false;
6859
Nico Weber0e6daef2013-12-26 23:38:39 +00006860 SourceRange SizeRange = Size->getSourceRange();
6861 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6862 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00006863 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006864 << FnName << FixItHint::CreateInsertion(
6865 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00006866 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00006867 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00006868 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00006869 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6870 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00006871
6872 return true;
6873}
6874
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006875/// \brief Determine whether the given type is or contains a dynamic class type
6876/// (e.g., whether it has a vtable).
6877static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6878 bool &IsContained) {
6879 // Look through array types while ignoring qualifiers.
6880 const Type *Ty = T->getBaseElementTypeUnsafe();
6881 IsContained = false;
6882
6883 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6884 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00006885 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006886 return nullptr;
6887
6888 if (RD->isDynamicClass())
6889 return RD;
6890
6891 // Check all the fields. If any bases were dynamic, the class is dynamic.
6892 // It's impossible for a class to transitively contain itself by value, so
6893 // infinite recursion is impossible.
6894 for (auto *FD : RD->fields()) {
6895 bool SubContained;
6896 if (const CXXRecordDecl *ContainedRD =
6897 getContainedDynamicClass(FD->getType(), SubContained)) {
6898 IsContained = true;
6899 return ContainedRD;
6900 }
6901 }
6902
6903 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00006904}
6905
Chandler Carruth889ed862011-06-21 23:04:20 +00006906/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006907/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00006908static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00006909 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006910 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6911 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6912 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006913
Craig Topperc3ec1492014-05-26 06:22:03 +00006914 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006915}
6916
Chandler Carruth889ed862011-06-21 23:04:20 +00006917/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00006918static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006919 if (const UnaryExprOrTypeTraitExpr *SizeOf =
6920 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6921 if (SizeOf->getKind() == clang::UETT_SizeOf)
6922 return SizeOf->getTypeOfArgument();
6923
6924 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00006925}
6926
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006927/// \brief Check for dangerous or invalid arguments to memset().
6928///
Chandler Carruthac687262011-06-03 06:23:57 +00006929/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006930/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6931/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006932///
6933/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006934void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00006935 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006936 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00006937 assert(BId != 0);
6938
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006939 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00006940 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006941 unsigned ExpectedNumArgs =
6942 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00006943 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006944 return;
6945
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006946 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00006947 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006948 unsigned LenArg =
6949 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00006950 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006951
Nico Weber0e6daef2013-12-26 23:38:39 +00006952 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6953 Call->getLocStart(), Call->getRParenLoc()))
6954 return;
6955
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006956 // We have special checking when the length is a sizeof expression.
6957 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6958 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6959 llvm::FoldingSetNodeID SizeOfArgID;
6960
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00006961 // Although widely used, 'bzero' is not a standard function. Be more strict
6962 // with the argument types before allowing diagnostics and only allow the
6963 // form bzero(ptr, sizeof(...)).
6964 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6965 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
6966 return;
6967
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006968 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6969 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006970 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006971
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006972 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00006973 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006974 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00006975 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00006976
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006977 // Never warn about void type pointers. This can be used to suppress
6978 // false positives.
6979 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006980 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006981
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006982 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6983 // actually comparing the expressions for equality. Because computing the
6984 // expression IDs can be expensive, we only do this if the diagnostic is
6985 // enabled.
6986 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006987 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6988 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006989 // We only compute IDs for expressions if the warning is enabled, and
6990 // cache the sizeof arg's ID.
6991 if (SizeOfArgID == llvm::FoldingSetNodeID())
6992 SizeOfArg->Profile(SizeOfArgID, Context, true);
6993 llvm::FoldingSetNodeID DestID;
6994 Dest->Profile(DestID, Context, true);
6995 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00006996 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6997 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006998 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00006999 StringRef ReadableName = FnName->getName();
7000
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007001 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007002 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007003 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007004 if (!PointeeTy->isIncompleteType() &&
7005 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007006 ActionIdx = 2; // If the pointee's size is sizeof(char),
7007 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007008
7009 // If the function is defined as a builtin macro, do not show macro
7010 // expansion.
7011 SourceLocation SL = SizeOfArg->getExprLoc();
7012 SourceRange DSR = Dest->getSourceRange();
7013 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007014 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007015
7016 if (SM.isMacroArgExpansion(SL)) {
7017 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7018 SL = SM.getSpellingLoc(SL);
7019 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7020 SM.getSpellingLoc(DSR.getEnd()));
7021 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7022 SM.getSpellingLoc(SSR.getEnd()));
7023 }
7024
Anna Zaksd08d9152012-05-30 23:14:52 +00007025 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007026 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007027 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007028 << PointeeTy
7029 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007030 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007031 << SSR);
7032 DiagRuntimeBehavior(SL, SizeOfArg,
7033 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7034 << ActionIdx
7035 << SSR);
7036
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007037 break;
7038 }
7039 }
7040
7041 // Also check for cases where the sizeof argument is the exact same
7042 // type as the memory argument, and where it points to a user-defined
7043 // record type.
7044 if (SizeOfArgTy != QualType()) {
7045 if (PointeeTy->isRecordType() &&
7046 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7047 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7048 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7049 << FnName << SizeOfArgTy << ArgIdx
7050 << PointeeTy << Dest->getSourceRange()
7051 << LenExpr->getSourceRange());
7052 break;
7053 }
Nico Weberc5e73862011-06-14 16:14:58 +00007054 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00007055 } else if (DestTy->isArrayType()) {
7056 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00007057 }
Nico Weberc5e73862011-06-14 16:14:58 +00007058
Nico Weberc44b35e2015-03-21 17:37:46 +00007059 if (PointeeTy == QualType())
7060 continue;
Anna Zaks22122702012-01-17 00:37:07 +00007061
Nico Weberc44b35e2015-03-21 17:37:46 +00007062 // Always complain about dynamic classes.
7063 bool IsContained;
7064 if (const CXXRecordDecl *ContainedRD =
7065 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00007066
Nico Weberc44b35e2015-03-21 17:37:46 +00007067 unsigned OperationType = 0;
7068 // "overwritten" if we're warning about the destination for any call
7069 // but memcmp; otherwise a verb appropriate to the call.
7070 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7071 if (BId == Builtin::BImemcpy)
7072 OperationType = 1;
7073 else if(BId == Builtin::BImemmove)
7074 OperationType = 2;
7075 else if (BId == Builtin::BImemcmp)
7076 OperationType = 3;
7077 }
7078
John McCall31168b02011-06-15 23:02:42 +00007079 DiagRuntimeBehavior(
7080 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007081 PDiag(diag::warn_dyn_class_memaccess)
7082 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7083 << FnName << IsContained << ContainedRD << OperationType
7084 << Call->getCallee()->getSourceRange());
7085 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7086 BId != Builtin::BImemset)
7087 DiagRuntimeBehavior(
7088 Dest->getExprLoc(), Dest,
7089 PDiag(diag::warn_arc_object_memaccess)
7090 << ArgIdx << FnName << PointeeTy
7091 << Call->getCallee()->getSourceRange());
7092 else
7093 continue;
7094
7095 DiagRuntimeBehavior(
7096 Dest->getExprLoc(), Dest,
7097 PDiag(diag::note_bad_memaccess_silence)
7098 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7099 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007100 }
7101}
7102
Ted Kremenek6865f772011-08-18 20:55:45 +00007103// A little helper routine: ignore addition and subtraction of integer literals.
7104// This intentionally does not ignore all integer constant expressions because
7105// we don't want to remove sizeof().
7106static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7107 Ex = Ex->IgnoreParenCasts();
7108
7109 for (;;) {
7110 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7111 if (!BO || !BO->isAdditiveOp())
7112 break;
7113
7114 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7115 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7116
7117 if (isa<IntegerLiteral>(RHS))
7118 Ex = LHS;
7119 else if (isa<IntegerLiteral>(LHS))
7120 Ex = RHS;
7121 else
7122 break;
7123 }
7124
7125 return Ex;
7126}
7127
Anna Zaks13b08572012-08-08 21:42:23 +00007128static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7129 ASTContext &Context) {
7130 // Only handle constant-sized or VLAs, but not flexible members.
7131 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7132 // Only issue the FIXIT for arrays of size > 1.
7133 if (CAT->getSize().getSExtValue() <= 1)
7134 return false;
7135 } else if (!Ty->isVariableArrayType()) {
7136 return false;
7137 }
7138 return true;
7139}
7140
Ted Kremenek6865f772011-08-18 20:55:45 +00007141// Warn if the user has made the 'size' argument to strlcpy or strlcat
7142// be the size of the source, instead of the destination.
7143void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7144 IdentifierInfo *FnName) {
7145
7146 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007147 unsigned NumArgs = Call->getNumArgs();
7148 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007149 return;
7150
7151 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7152 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007153 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007154
7155 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7156 Call->getLocStart(), Call->getRParenLoc()))
7157 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00007158
7159 // Look for 'strlcpy(dst, x, sizeof(x))'
7160 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7161 CompareWithSrc = Ex;
7162 else {
7163 // Look for 'strlcpy(dst, x, strlen(x))'
7164 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00007165 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7166 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00007167 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7168 }
7169 }
7170
7171 if (!CompareWithSrc)
7172 return;
7173
7174 // Determine if the argument to sizeof/strlen is equal to the source
7175 // argument. In principle there's all kinds of things you could do
7176 // here, for instance creating an == expression and evaluating it with
7177 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7178 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7179 if (!SrcArgDRE)
7180 return;
7181
7182 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7183 if (!CompareWithSrcDRE ||
7184 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7185 return;
7186
7187 const Expr *OriginalSizeArg = Call->getArg(2);
7188 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7189 << OriginalSizeArg->getSourceRange() << FnName;
7190
7191 // Output a FIXIT hint if the destination is an array (rather than a
7192 // pointer to an array). This could be enhanced to handle some
7193 // pointers if we know the actual size, like if DstArg is 'array+2'
7194 // we could say 'sizeof(array)-2'.
7195 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00007196 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00007197 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007198
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007199 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007200 llvm::raw_svector_ostream OS(sizeString);
7201 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007202 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00007203 OS << ")";
7204
7205 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7206 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7207 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00007208}
7209
Anna Zaks314cd092012-02-01 19:08:57 +00007210/// Check if two expressions refer to the same declaration.
7211static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7212 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7213 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7214 return D1->getDecl() == D2->getDecl();
7215 return false;
7216}
7217
7218static const Expr *getStrlenExprArg(const Expr *E) {
7219 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7220 const FunctionDecl *FD = CE->getDirectCallee();
7221 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00007222 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007223 return CE->getArg(0)->IgnoreParenCasts();
7224 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007225 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007226}
7227
7228// Warn on anti-patterns as the 'size' argument to strncat.
7229// The correct size argument should look like following:
7230// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7231void Sema::CheckStrncatArguments(const CallExpr *CE,
7232 IdentifierInfo *FnName) {
7233 // Don't crash if the user has the wrong number of arguments.
7234 if (CE->getNumArgs() < 3)
7235 return;
7236 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7237 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7238 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7239
Nico Weber0e6daef2013-12-26 23:38:39 +00007240 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7241 CE->getRParenLoc()))
7242 return;
7243
Anna Zaks314cd092012-02-01 19:08:57 +00007244 // Identify common expressions, which are wrongly used as the size argument
7245 // to strncat and may lead to buffer overflows.
7246 unsigned PatternType = 0;
7247 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7248 // - sizeof(dst)
7249 if (referToTheSameDecl(SizeOfArg, DstArg))
7250 PatternType = 1;
7251 // - sizeof(src)
7252 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7253 PatternType = 2;
7254 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7255 if (BE->getOpcode() == BO_Sub) {
7256 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7257 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7258 // - sizeof(dst) - strlen(dst)
7259 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7260 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7261 PatternType = 1;
7262 // - sizeof(src) - (anything)
7263 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7264 PatternType = 2;
7265 }
7266 }
7267
7268 if (PatternType == 0)
7269 return;
7270
Anna Zaks5069aa32012-02-03 01:27:37 +00007271 // Generate the diagnostic.
7272 SourceLocation SL = LenArg->getLocStart();
7273 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007274 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00007275
7276 // If the function is defined as a builtin macro, do not show macro expansion.
7277 if (SM.isMacroArgExpansion(SL)) {
7278 SL = SM.getSpellingLoc(SL);
7279 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7280 SM.getSpellingLoc(SR.getEnd()));
7281 }
7282
Anna Zaks13b08572012-08-08 21:42:23 +00007283 // Check if the destination is an array (rather than a pointer to an array).
7284 QualType DstTy = DstArg->getType();
7285 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7286 Context);
7287 if (!isKnownSizeArray) {
7288 if (PatternType == 1)
7289 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7290 else
7291 Diag(SL, diag::warn_strncat_src_size) << SR;
7292 return;
7293 }
7294
Anna Zaks314cd092012-02-01 19:08:57 +00007295 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00007296 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007297 else
Anna Zaks5069aa32012-02-03 01:27:37 +00007298 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007299
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007300 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00007301 llvm::raw_svector_ostream OS(sizeString);
7302 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007303 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007304 OS << ") - ";
7305 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007306 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007307 OS << ") - 1";
7308
Anna Zaks5069aa32012-02-03 01:27:37 +00007309 Diag(SL, diag::note_strncat_wrong_size)
7310 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00007311}
7312
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007313//===--- CHECK: Return Address of Stack Variable --------------------------===//
7314
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007315static const Expr *EvalVal(const Expr *E,
7316 SmallVectorImpl<const DeclRefExpr *> &refVars,
7317 const Decl *ParentDecl);
7318static const Expr *EvalAddr(const Expr *E,
7319 SmallVectorImpl<const DeclRefExpr *> &refVars,
7320 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007321
7322/// CheckReturnStackAddr - Check if a return statement returns the address
7323/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007324static void
7325CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7326 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00007327
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007328 const Expr *stackE = nullptr;
7329 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007330
7331 // Perform checking for returned stack addresses, local blocks,
7332 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00007333 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007334 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007335 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00007336 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007337 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007338 }
7339
Craig Topperc3ec1492014-05-26 06:22:03 +00007340 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007341 return; // Nothing suspicious was found.
7342
Richard Trieu81b6c562016-08-05 23:24:47 +00007343 // Parameters are initalized in the calling scope, so taking the address
7344 // of a parameter reference doesn't need a warning.
7345 for (auto *DRE : refVars)
7346 if (isa<ParmVarDecl>(DRE->getDecl()))
7347 return;
7348
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007349 SourceLocation diagLoc;
7350 SourceRange diagRange;
7351 if (refVars.empty()) {
7352 diagLoc = stackE->getLocStart();
7353 diagRange = stackE->getSourceRange();
7354 } else {
7355 // We followed through a reference variable. 'stackE' contains the
7356 // problematic expression but we will warn at the return statement pointing
7357 // at the reference variable. We will later display the "trail" of
7358 // reference variables using notes.
7359 diagLoc = refVars[0]->getLocStart();
7360 diagRange = refVars[0]->getSourceRange();
7361 }
7362
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007363 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7364 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00007365 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007366 << DR->getDecl()->getDeclName() << diagRange;
7367 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007368 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007369 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007370 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007371 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00007372 // If there is an LValue->RValue conversion, then the value of the
7373 // reference type is used, not the reference.
7374 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7375 if (ICE->getCastKind() == CK_LValueToRValue) {
7376 return;
7377 }
7378 }
Craig Topperda7b27f2015-11-17 05:40:09 +00007379 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7380 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007381 }
7382
7383 // Display the "trail" of reference variables that we followed until we
7384 // found the problematic expression using notes.
7385 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007386 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007387 // If this var binds to another reference var, show the range of the next
7388 // var, otherwise the var binds to the problematic expression, in which case
7389 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007390 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7391 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007392 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7393 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007394 }
7395}
7396
7397/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7398/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007399/// to a location on the stack, a local block, an address of a label, or a
7400/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007401/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007402/// encounter a subexpression that (1) clearly does not lead to one of the
7403/// above problematic expressions (2) is something we cannot determine leads to
7404/// a problematic expression based on such local checking.
7405///
7406/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7407/// the expression that they point to. Such variables are added to the
7408/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007409///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007410/// EvalAddr processes expressions that are pointers that are used as
7411/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007412/// At the base case of the recursion is a check for the above problematic
7413/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007414///
7415/// This implementation handles:
7416///
7417/// * pointer-to-pointer casts
7418/// * implicit conversions from array references to pointers
7419/// * taking the address of fields
7420/// * arbitrary interplay between "&" and "*" operators
7421/// * pointer arithmetic from an address of a stack variable
7422/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007423static const Expr *EvalAddr(const Expr *E,
7424 SmallVectorImpl<const DeclRefExpr *> &refVars,
7425 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007426 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00007427 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007428
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007429 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00007430 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00007431 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007432 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00007433 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00007434
Peter Collingbourne91147592011-04-15 00:35:48 +00007435 E = E->IgnoreParens();
7436
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007437 // Our "symbolic interpreter" is just a dispatch off the currently
7438 // viewed AST node. We then recursively traverse the AST by calling
7439 // EvalAddr and EvalVal appropriately.
7440 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007441 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007442 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007443
Richard Smith40f08eb2014-01-30 22:05:38 +00007444 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00007445 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00007446 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00007447
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007448 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007449 // If this is a reference variable, follow through to the expression that
7450 // it points to.
7451 if (V->hasLocalStorage() &&
7452 V->getType()->isReferenceType() && V->hasInit()) {
7453 // Add the reference variable to the "trail".
7454 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007455 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007456 }
7457
Craig Topperc3ec1492014-05-26 06:22:03 +00007458 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007459 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007460
Chris Lattner934edb22007-12-28 05:31:15 +00007461 case Stmt::UnaryOperatorClass: {
7462 // The only unary operator that make sense to handle here
7463 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007464 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007465
John McCalle3027922010-08-25 11:45:40 +00007466 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007467 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007468 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007469 }
Mike Stump11289f42009-09-09 15:08:12 +00007470
Chris Lattner934edb22007-12-28 05:31:15 +00007471 case Stmt::BinaryOperatorClass: {
7472 // Handle pointer arithmetic. All other binary operators are not valid
7473 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007474 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00007475 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00007476
John McCalle3027922010-08-25 11:45:40 +00007477 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00007478 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007479
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007480 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00007481
7482 // Determine which argument is the real pointer base. It could be
7483 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007484 if (!Base->getType()->isPointerType())
7485 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00007486
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007487 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007488 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007489 }
Steve Naroff2752a172008-09-10 19:17:48 +00007490
Chris Lattner934edb22007-12-28 05:31:15 +00007491 // For conditional operators we need to see if either the LHS or RHS are
7492 // valid DeclRefExpr*s. If one of them is valid, we return it.
7493 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007494 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007495
Chris Lattner934edb22007-12-28 05:31:15 +00007496 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007497 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007498 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007499 // In C++, we can have a throw-expression, which has 'void' type.
7500 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007501 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007502 return LHS;
7503 }
Chris Lattner934edb22007-12-28 05:31:15 +00007504
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007505 // In C++, we can have a throw-expression, which has 'void' type.
7506 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00007507 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007508
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007509 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007510 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007511
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007512 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00007513 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007514 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00007515 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007516
7517 case Stmt::AddrLabelExprClass:
7518 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00007519
John McCall28fc7092011-11-10 05:35:25 +00007520 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007521 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7522 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00007523
Ted Kremenekc3b4c522008-08-07 00:49:01 +00007524 // For casts, we need to handle conversions from arrays to
7525 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00007526 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00007527 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007528 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00007529 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00007530 case Stmt::CXXStaticCastExprClass:
7531 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00007532 case Stmt::CXXConstCastExprClass:
7533 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007534 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00007535 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00007536 case CK_LValueToRValue:
7537 case CK_NoOp:
7538 case CK_BaseToDerived:
7539 case CK_DerivedToBase:
7540 case CK_UncheckedDerivedToBase:
7541 case CK_Dynamic:
7542 case CK_CPointerToObjCPointerCast:
7543 case CK_BlockPointerToObjCPointerCast:
7544 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007545 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007546
7547 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007548 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007549
Richard Trieudadefde2014-07-02 04:39:38 +00007550 case CK_BitCast:
7551 if (SubExpr->getType()->isAnyPointerType() ||
7552 SubExpr->getType()->isBlockPointerType() ||
7553 SubExpr->getType()->isObjCQualifiedIdType())
7554 return EvalAddr(SubExpr, refVars, ParentDecl);
7555 else
7556 return nullptr;
7557
Eli Friedman8195ad72012-02-23 23:04:32 +00007558 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007559 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00007560 }
Chris Lattner934edb22007-12-28 05:31:15 +00007561 }
Mike Stump11289f42009-09-09 15:08:12 +00007562
Douglas Gregorfe314812011-06-21 17:03:29 +00007563 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007564 if (const Expr *Result =
7565 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7566 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00007567 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00007568 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007569
Chris Lattner934edb22007-12-28 05:31:15 +00007570 // Everything else: we simply don't reason about them.
7571 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007572 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00007573 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007574}
Mike Stump11289f42009-09-09 15:08:12 +00007575
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007576/// EvalVal - This function is complements EvalAddr in the mutual recursion.
7577/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007578static const Expr *EvalVal(const Expr *E,
7579 SmallVectorImpl<const DeclRefExpr *> &refVars,
7580 const Decl *ParentDecl) {
7581 do {
7582 // We should only be called for evaluating non-pointer expressions, or
7583 // expressions with a pointer type that are not used as references but
7584 // instead
7585 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00007586
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007587 // Our "symbolic interpreter" is just a dispatch off the currently
7588 // viewed AST node. We then recursively traverse the AST by calling
7589 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00007590
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007591 E = E->IgnoreParens();
7592 switch (E->getStmtClass()) {
7593 case Stmt::ImplicitCastExprClass: {
7594 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7595 if (IE->getValueKind() == VK_LValue) {
7596 E = IE->getSubExpr();
7597 continue;
7598 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007599 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007600 }
Richard Smith40f08eb2014-01-30 22:05:38 +00007601
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007602 case Stmt::ExprWithCleanupsClass:
7603 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7604 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007605
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007606 case Stmt::DeclRefExprClass: {
7607 // When we hit a DeclRefExpr we are looking at code that refers to a
7608 // variable's name. If it's not a reference variable we check if it has
7609 // local storage within the function, and if so, return the expression.
7610 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7611
7612 // If we leave the immediate function, the lifetime isn't about to end.
7613 if (DR->refersToEnclosingVariableOrCapture())
7614 return nullptr;
7615
7616 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7617 // Check if it refers to itself, e.g. "int& i = i;".
7618 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007619 return DR;
7620
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007621 if (V->hasLocalStorage()) {
7622 if (!V->getType()->isReferenceType())
7623 return DR;
7624
7625 // Reference variable, follow through to the expression that
7626 // it points to.
7627 if (V->hasInit()) {
7628 // Add the reference variable to the "trail".
7629 refVars.push_back(DR);
7630 return EvalVal(V->getInit(), refVars, V);
7631 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007632 }
7633 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007634
7635 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007636 }
Mike Stump11289f42009-09-09 15:08:12 +00007637
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007638 case Stmt::UnaryOperatorClass: {
7639 // The only unary operator that make sense to handle here
7640 // is Deref. All others don't resolve to a "name." This includes
7641 // handling all sorts of rvalues passed to a unary operator.
7642 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007643
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007644 if (U->getOpcode() == UO_Deref)
7645 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007646
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007647 return nullptr;
7648 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007649
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007650 case Stmt::ArraySubscriptExprClass: {
7651 // Array subscripts are potential references to data on the stack. We
7652 // retrieve the DeclRefExpr* for the array variable if it indeed
7653 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00007654 const auto *ASE = cast<ArraySubscriptExpr>(E);
7655 if (ASE->isTypeDependent())
7656 return nullptr;
7657 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007658 }
Mike Stump11289f42009-09-09 15:08:12 +00007659
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007660 case Stmt::OMPArraySectionExprClass: {
7661 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7662 ParentDecl);
7663 }
Mike Stump11289f42009-09-09 15:08:12 +00007664
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007665 case Stmt::ConditionalOperatorClass: {
7666 // For conditional operators we need to see if either the LHS or RHS are
7667 // non-NULL Expr's. If one is non-NULL, we return it.
7668 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007669
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007670 // Handle the GNU extension for missing LHS.
7671 if (const Expr *LHSExpr = C->getLHS()) {
7672 // In C++, we can have a throw-expression, which has 'void' type.
7673 if (!LHSExpr->getType()->isVoidType())
7674 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7675 return LHS;
7676 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007677
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007678 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007679 if (C->getRHS()->getType()->isVoidType())
7680 return nullptr;
7681
7682 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007683 }
7684
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007685 // Accesses to members are potential references to data on the stack.
7686 case Stmt::MemberExprClass: {
7687 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00007688
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007689 // Check for indirect access. We only want direct field accesses.
7690 if (M->isArrow())
7691 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007692
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007693 // Check whether the member type is itself a reference, in which case
7694 // we're not going to refer to the member, but to what the member refers
7695 // to.
7696 if (M->getMemberDecl()->getType()->isReferenceType())
7697 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007698
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007699 return EvalVal(M->getBase(), refVars, ParentDecl);
7700 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00007701
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007702 case Stmt::MaterializeTemporaryExprClass:
7703 if (const Expr *Result =
7704 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7705 refVars, ParentDecl))
7706 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007707 return E;
7708
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007709 default:
7710 // Check that we don't return or take the address of a reference to a
7711 // temporary. This is only useful in C++.
7712 if (!E->isTypeDependent() && E->isRValue())
7713 return E;
7714
7715 // Everything else: we simply don't reason about them.
7716 return nullptr;
7717 }
7718 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007719}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007720
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007721void
7722Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7723 SourceLocation ReturnLoc,
7724 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00007725 const AttrVec *Attrs,
7726 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007727 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7728
7729 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00007730 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7731 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00007732 CheckNonNullExpr(*this, RetValExp))
7733 Diag(ReturnLoc, diag::warn_null_ret)
7734 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00007735
7736 // C++11 [basic.stc.dynamic.allocation]p4:
7737 // If an allocation function declared with a non-throwing
7738 // exception-specification fails to allocate storage, it shall return
7739 // a null pointer. Any other allocation function that fails to allocate
7740 // storage shall indicate failure only by throwing an exception [...]
7741 if (FD) {
7742 OverloadedOperatorKind Op = FD->getOverloadedOperator();
7743 if (Op == OO_New || Op == OO_Array_New) {
7744 const FunctionProtoType *Proto
7745 = FD->getType()->castAs<FunctionProtoType>();
7746 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7747 CheckNonNullExpr(*this, RetValExp))
7748 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7749 << FD << getLangOpts().CPlusPlus11;
7750 }
7751 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007752}
7753
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007754//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7755
7756/// Check for comparisons of floating point operands using != and ==.
7757/// Issue a warning if these are no self-comparisons, as they are not likely
7758/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00007759void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00007760 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7761 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007762
7763 // Special case: check for x == x (which is OK).
7764 // Do not emit warnings for such cases.
7765 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7766 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7767 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00007768 return;
Mike Stump11289f42009-09-09 15:08:12 +00007769
Ted Kremenekeda40e22007-11-29 00:59:04 +00007770 // Special case: check for comparisons against literals that can be exactly
7771 // represented by APFloat. In such cases, do not emit a warning. This
7772 // is a heuristic: often comparison against such literals are used to
7773 // detect if a value in a variable has not changed. This clearly can
7774 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00007775 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7776 if (FLL->isExact())
7777 return;
7778 } else
7779 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7780 if (FLR->isExact())
7781 return;
Mike Stump11289f42009-09-09 15:08:12 +00007782
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007783 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00007784 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007785 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007786 return;
Mike Stump11289f42009-09-09 15:08:12 +00007787
David Blaikie1f4ff152012-07-16 20:47:22 +00007788 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007789 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007790 return;
Mike Stump11289f42009-09-09 15:08:12 +00007791
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007792 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00007793 Diag(Loc, diag::warn_floatingpoint_eq)
7794 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007795}
John McCallca01b222010-01-04 23:21:16 +00007796
John McCall70aa5392010-01-06 05:24:50 +00007797//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7798//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00007799
John McCall70aa5392010-01-06 05:24:50 +00007800namespace {
John McCallca01b222010-01-04 23:21:16 +00007801
John McCall70aa5392010-01-06 05:24:50 +00007802/// Structure recording the 'active' range of an integer-valued
7803/// expression.
7804struct IntRange {
7805 /// The number of bits active in the int.
7806 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00007807
John McCall70aa5392010-01-06 05:24:50 +00007808 /// True if the int is known not to have negative values.
7809 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00007810
John McCall70aa5392010-01-06 05:24:50 +00007811 IntRange(unsigned Width, bool NonNegative)
7812 : Width(Width), NonNegative(NonNegative)
7813 {}
John McCallca01b222010-01-04 23:21:16 +00007814
John McCall817d4af2010-11-10 23:38:19 +00007815 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00007816 static IntRange forBoolType() {
7817 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00007818 }
7819
John McCall817d4af2010-11-10 23:38:19 +00007820 /// Returns the range of an opaque value of the given integral type.
7821 static IntRange forValueOfType(ASTContext &C, QualType T) {
7822 return forValueOfCanonicalType(C,
7823 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00007824 }
7825
John McCall817d4af2010-11-10 23:38:19 +00007826 /// Returns the range of an opaque value of a canonical integral type.
7827 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00007828 assert(T->isCanonicalUnqualified());
7829
7830 if (const VectorType *VT = dyn_cast<VectorType>(T))
7831 T = VT->getElementType().getTypePtr();
7832 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7833 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007834 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7835 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00007836
David Majnemer6a426652013-06-07 22:07:20 +00007837 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00007838 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00007839 EnumDecl *Enum = ET->getDecl();
7840 if (!Enum->isCompleteDefinition())
7841 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00007842
David Majnemer6a426652013-06-07 22:07:20 +00007843 unsigned NumPositive = Enum->getNumPositiveBits();
7844 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00007845
David Majnemer6a426652013-06-07 22:07:20 +00007846 if (NumNegative == 0)
7847 return IntRange(NumPositive, true/*NonNegative*/);
7848 else
7849 return IntRange(std::max(NumPositive + 1, NumNegative),
7850 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00007851 }
John McCall70aa5392010-01-06 05:24:50 +00007852
7853 const BuiltinType *BT = cast<BuiltinType>(T);
7854 assert(BT->isInteger());
7855
7856 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7857 }
7858
John McCall817d4af2010-11-10 23:38:19 +00007859 /// Returns the "target" range of a canonical integral type, i.e.
7860 /// the range of values expressible in the type.
7861 ///
7862 /// This matches forValueOfCanonicalType except that enums have the
7863 /// full range of their type, not the range of their enumerators.
7864 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7865 assert(T->isCanonicalUnqualified());
7866
7867 if (const VectorType *VT = dyn_cast<VectorType>(T))
7868 T = VT->getElementType().getTypePtr();
7869 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7870 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007871 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7872 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007873 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00007874 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007875
7876 const BuiltinType *BT = cast<BuiltinType>(T);
7877 assert(BT->isInteger());
7878
7879 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7880 }
7881
7882 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00007883 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00007884 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00007885 L.NonNegative && R.NonNegative);
7886 }
7887
John McCall817d4af2010-11-10 23:38:19 +00007888 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00007889 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00007890 return IntRange(std::min(L.Width, R.Width),
7891 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00007892 }
7893};
7894
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007895IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007896 if (value.isSigned() && value.isNegative())
7897 return IntRange(value.getMinSignedBits(), false);
7898
7899 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00007900 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007901
7902 // isNonNegative() just checks the sign bit without considering
7903 // signedness.
7904 return IntRange(value.getActiveBits(), true);
7905}
7906
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007907IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7908 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007909 if (result.isInt())
7910 return GetValueRange(C, result.getInt(), MaxWidth);
7911
7912 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00007913 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7914 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7915 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7916 R = IntRange::join(R, El);
7917 }
John McCall70aa5392010-01-06 05:24:50 +00007918 return R;
7919 }
7920
7921 if (result.isComplexInt()) {
7922 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7923 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7924 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00007925 }
7926
7927 // This can happen with lossless casts to intptr_t of "based" lvalues.
7928 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00007929 // FIXME: The only reason we need to pass the type in here is to get
7930 // the sign right on this one case. It would be nice if APValue
7931 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007932 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00007933 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00007934}
John McCall70aa5392010-01-06 05:24:50 +00007935
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007936QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007937 QualType Ty = E->getType();
7938 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7939 Ty = AtomicRHS->getValueType();
7940 return Ty;
7941}
7942
John McCall70aa5392010-01-06 05:24:50 +00007943/// Pseudo-evaluate the given integer expression, estimating the
7944/// range of values it might take.
7945///
7946/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007947IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007948 E = E->IgnoreParens();
7949
7950 // Try a full evaluation first.
7951 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007952 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00007953 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007954
7955 // I think we only want to look through implicit casts here; if the
7956 // user has an explicit widening cast, we should treat the value as
7957 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007958 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00007959 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00007960 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7961
Eli Friedmane6d33952013-07-08 20:20:06 +00007962 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00007963
George Burgess IVdf1ed002016-01-13 01:52:39 +00007964 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7965 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00007966
John McCall70aa5392010-01-06 05:24:50 +00007967 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00007968 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00007969 return OutputTypeRange;
7970
7971 IntRange SubRange
7972 = GetExprRange(C, CE->getSubExpr(),
7973 std::min(MaxWidth, OutputTypeRange.Width));
7974
7975 // Bail out if the subexpr's range is as wide as the cast type.
7976 if (SubRange.Width >= OutputTypeRange.Width)
7977 return OutputTypeRange;
7978
7979 // Otherwise, we take the smaller width, and we're non-negative if
7980 // either the output type or the subexpr is.
7981 return IntRange(SubRange.Width,
7982 SubRange.NonNegative || OutputTypeRange.NonNegative);
7983 }
7984
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007985 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007986 // If we can fold the condition, just take that operand.
7987 bool CondResult;
7988 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7989 return GetExprRange(C, CondResult ? CO->getTrueExpr()
7990 : CO->getFalseExpr(),
7991 MaxWidth);
7992
7993 // Otherwise, conservatively merge.
7994 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7995 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7996 return IntRange::join(L, R);
7997 }
7998
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007999 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008000 switch (BO->getOpcode()) {
8001
8002 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00008003 case BO_LAnd:
8004 case BO_LOr:
8005 case BO_LT:
8006 case BO_GT:
8007 case BO_LE:
8008 case BO_GE:
8009 case BO_EQ:
8010 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00008011 return IntRange::forBoolType();
8012
John McCallc3688382011-07-13 06:35:24 +00008013 // The type of the assignments is the type of the LHS, so the RHS
8014 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00008015 case BO_MulAssign:
8016 case BO_DivAssign:
8017 case BO_RemAssign:
8018 case BO_AddAssign:
8019 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00008020 case BO_XorAssign:
8021 case BO_OrAssign:
8022 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00008023 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00008024
John McCallc3688382011-07-13 06:35:24 +00008025 // Simple assignments just pass through the RHS, which will have
8026 // been coerced to the LHS type.
8027 case BO_Assign:
8028 // TODO: bitfields?
8029 return GetExprRange(C, BO->getRHS(), MaxWidth);
8030
John McCall70aa5392010-01-06 05:24:50 +00008031 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008032 case BO_PtrMemD:
8033 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00008034 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008035
John McCall2ce81ad2010-01-06 22:07:33 +00008036 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00008037 case BO_And:
8038 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00008039 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8040 GetExprRange(C, BO->getRHS(), MaxWidth));
8041
John McCall70aa5392010-01-06 05:24:50 +00008042 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00008043 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00008044 // ...except that we want to treat '1 << (blah)' as logically
8045 // positive. It's an important idiom.
8046 if (IntegerLiteral *I
8047 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8048 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008049 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00008050 return IntRange(R.Width, /*NonNegative*/ true);
8051 }
8052 }
8053 // fallthrough
8054
John McCalle3027922010-08-25 11:45:40 +00008055 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00008056 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008057
John McCall2ce81ad2010-01-06 22:07:33 +00008058 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00008059 case BO_Shr:
8060 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00008061 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8062
8063 // If the shift amount is a positive constant, drop the width by
8064 // that much.
8065 llvm::APSInt shift;
8066 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8067 shift.isNonNegative()) {
8068 unsigned zext = shift.getZExtValue();
8069 if (zext >= L.Width)
8070 L.Width = (L.NonNegative ? 0 : 1);
8071 else
8072 L.Width -= zext;
8073 }
8074
8075 return L;
8076 }
8077
8078 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008079 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008080 return GetExprRange(C, BO->getRHS(), MaxWidth);
8081
John McCall2ce81ad2010-01-06 22:07:33 +00008082 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008083 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008084 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008085 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008086 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008087
John McCall51431812011-07-14 22:39:48 +00008088 // The width of a division result is mostly determined by the size
8089 // of the LHS.
8090 case BO_Div: {
8091 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008092 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008093 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8094
8095 // If the divisor is constant, use that.
8096 llvm::APSInt divisor;
8097 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8098 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8099 if (log2 >= L.Width)
8100 L.Width = (L.NonNegative ? 0 : 1);
8101 else
8102 L.Width = std::min(L.Width - log2, MaxWidth);
8103 return L;
8104 }
8105
8106 // Otherwise, just use the LHS's width.
8107 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8108 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8109 }
8110
8111 // The result of a remainder can't be larger than the result of
8112 // either side.
8113 case BO_Rem: {
8114 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008115 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008116 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8117 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8118
8119 IntRange meet = IntRange::meet(L, R);
8120 meet.Width = std::min(meet.Width, MaxWidth);
8121 return meet;
8122 }
8123
8124 // The default behavior is okay for these.
8125 case BO_Mul:
8126 case BO_Add:
8127 case BO_Xor:
8128 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008129 break;
8130 }
8131
John McCall51431812011-07-14 22:39:48 +00008132 // The default case is to treat the operation as if it were closed
8133 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008134 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8135 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8136 return IntRange::join(L, R);
8137 }
8138
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008139 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008140 switch (UO->getOpcode()) {
8141 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008142 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008143 return IntRange::forBoolType();
8144
8145 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008146 case UO_Deref:
8147 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00008148 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008149
8150 default:
8151 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8152 }
8153 }
8154
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008155 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00008156 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8157
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008158 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00008159 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00008160 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00008161
Eli Friedmane6d33952013-07-08 20:20:06 +00008162 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008163}
John McCall263a48b2010-01-04 23:31:57 +00008164
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008165IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008166 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00008167}
8168
John McCall263a48b2010-01-04 23:31:57 +00008169/// Checks whether the given value, which currently has the given
8170/// source semantics, has the same value when coerced through the
8171/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008172bool IsSameFloatAfterCast(const llvm::APFloat &value,
8173 const llvm::fltSemantics &Src,
8174 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008175 llvm::APFloat truncated = value;
8176
8177 bool ignored;
8178 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8179 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8180
8181 return truncated.bitwiseIsEqual(value);
8182}
8183
8184/// Checks whether the given value, which currently has the given
8185/// source semantics, has the same value when coerced through the
8186/// target semantics.
8187///
8188/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008189bool IsSameFloatAfterCast(const APValue &value,
8190 const llvm::fltSemantics &Src,
8191 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008192 if (value.isFloat())
8193 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8194
8195 if (value.isVector()) {
8196 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8197 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8198 return false;
8199 return true;
8200 }
8201
8202 assert(value.isComplexFloat());
8203 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8204 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8205}
8206
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008207void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008208
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008209bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00008210 // Suppress cases where we are comparing against an enum constant.
8211 if (const DeclRefExpr *DR =
8212 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8213 if (isa<EnumConstantDecl>(DR->getDecl()))
8214 return false;
8215
8216 // Suppress cases where the '0' value is expanded from a macro.
8217 if (E->getLocStart().isMacroID())
8218 return false;
8219
John McCallcc7e5bf2010-05-06 08:58:33 +00008220 llvm::APSInt Value;
8221 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8222}
8223
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008224bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00008225 // Strip off implicit integral promotions.
8226 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008227 if (ICE->getCastKind() != CK_IntegralCast &&
8228 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00008229 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008230 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00008231 }
8232
8233 return E->getType()->isEnumeralType();
8234}
8235
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008236void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00008237 // Disable warning in template instantiations.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008238 if (S.inTemplateInstantiation())
Richard Trieu36594562013-11-01 21:47:19 +00008239 return;
8240
John McCalle3027922010-08-25 11:45:40 +00008241 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00008242 if (E->isValueDependent())
8243 return;
8244
John McCalle3027922010-08-25 11:45:40 +00008245 if (op == BO_LT && 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" << "false" << 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_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008250 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008251 << ">= 0" << "true" << HasEnumType(E->getLHS())
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_GT && 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 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008256 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008257 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008258 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008259 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008260 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8261 }
8262}
8263
Benjamin Kramer7320b992016-06-15 14:20:56 +00008264void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8265 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008266 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00008267 // Disable warning in template instantiations.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008268 if (S.inTemplateInstantiation())
Richard Trieudd51d742013-11-01 21:19:43 +00008269 return;
8270
Richard Trieu0f097742014-04-04 04:13:47 +00008271 // TODO: Investigate using GetExprRange() to get tighter bounds
8272 // on the bit ranges.
8273 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00008274 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00008275 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00008276 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8277 unsigned OtherWidth = OtherRange.Width;
8278
8279 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8280
Richard Trieu560910c2012-11-14 22:50:24 +00008281 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00008282 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00008283 return;
8284
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008285 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00008286 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008287
Richard Trieu0f097742014-04-04 04:13:47 +00008288 // Used for diagnostic printout.
8289 enum {
8290 LiteralConstant = 0,
8291 CXXBoolLiteralTrue,
8292 CXXBoolLiteralFalse
8293 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008294
Richard Trieu0f097742014-04-04 04:13:47 +00008295 if (!OtherIsBooleanType) {
8296 QualType ConstantT = Constant->getType();
8297 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00008298
Richard Trieu0f097742014-04-04 04:13:47 +00008299 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8300 return;
8301 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8302 "comparison with non-integer type");
8303
8304 bool ConstantSigned = ConstantT->isSignedIntegerType();
8305 bool CommonSigned = CommonT->isSignedIntegerType();
8306
8307 bool EqualityOnly = false;
8308
8309 if (CommonSigned) {
8310 // The common type is signed, therefore no signed to unsigned conversion.
8311 if (!OtherRange.NonNegative) {
8312 // Check that the constant is representable in type OtherT.
8313 if (ConstantSigned) {
8314 if (OtherWidth >= Value.getMinSignedBits())
8315 return;
8316 } else { // !ConstantSigned
8317 if (OtherWidth >= Value.getActiveBits() + 1)
8318 return;
8319 }
8320 } else { // !OtherSigned
8321 // Check that the constant is representable in type OtherT.
8322 // Negative values are out of range.
8323 if (ConstantSigned) {
8324 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8325 return;
8326 } else { // !ConstantSigned
8327 if (OtherWidth >= Value.getActiveBits())
8328 return;
8329 }
Richard Trieu560910c2012-11-14 22:50:24 +00008330 }
Richard Trieu0f097742014-04-04 04:13:47 +00008331 } else { // !CommonSigned
8332 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00008333 if (OtherWidth >= Value.getActiveBits())
8334 return;
Craig Toppercf360162014-06-18 05:13:11 +00008335 } else { // OtherSigned
8336 assert(!ConstantSigned &&
8337 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00008338 // Check to see if the constant is representable in OtherT.
8339 if (OtherWidth > Value.getActiveBits())
8340 return;
8341 // Check to see if the constant is equivalent to a negative value
8342 // cast to CommonT.
8343 if (S.Context.getIntWidth(ConstantT) ==
8344 S.Context.getIntWidth(CommonT) &&
8345 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8346 return;
8347 // The constant value rests between values that OtherT can represent
8348 // after conversion. Relational comparison still works, but equality
8349 // comparisons will be tautological.
8350 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008351 }
8352 }
Richard Trieu0f097742014-04-04 04:13:47 +00008353
8354 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8355
8356 if (op == BO_EQ || op == BO_NE) {
8357 IsTrue = op == BO_NE;
8358 } else if (EqualityOnly) {
8359 return;
8360 } else if (RhsConstant) {
8361 if (op == BO_GT || op == BO_GE)
8362 IsTrue = !PositiveConstant;
8363 else // op == BO_LT || op == BO_LE
8364 IsTrue = PositiveConstant;
8365 } else {
8366 if (op == BO_LT || op == BO_LE)
8367 IsTrue = !PositiveConstant;
8368 else // op == BO_GT || op == BO_GE
8369 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008370 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008371 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00008372 // Other isKnownToHaveBooleanValue
8373 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8374 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8375 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8376
8377 static const struct LinkedConditions {
8378 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8379 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8380 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8381 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8382 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8383 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8384
8385 } TruthTable = {
8386 // Constant on LHS. | Constant on RHS. |
8387 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
8388 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8389 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8390 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8391 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8392 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8393 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8394 };
8395
8396 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8397
8398 enum ConstantValue ConstVal = Zero;
8399 if (Value.isUnsigned() || Value.isNonNegative()) {
8400 if (Value == 0) {
8401 LiteralOrBoolConstant =
8402 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8403 ConstVal = Zero;
8404 } else if (Value == 1) {
8405 LiteralOrBoolConstant =
8406 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8407 ConstVal = One;
8408 } else {
8409 LiteralOrBoolConstant = LiteralConstant;
8410 ConstVal = GT_One;
8411 }
8412 } else {
8413 ConstVal = LT_Zero;
8414 }
8415
8416 CompareBoolWithConstantResult CmpRes;
8417
8418 switch (op) {
8419 case BO_LT:
8420 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8421 break;
8422 case BO_GT:
8423 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8424 break;
8425 case BO_LE:
8426 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8427 break;
8428 case BO_GE:
8429 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8430 break;
8431 case BO_EQ:
8432 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8433 break;
8434 case BO_NE:
8435 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8436 break;
8437 default:
8438 CmpRes = Unkwn;
8439 break;
8440 }
8441
8442 if (CmpRes == AFals) {
8443 IsTrue = false;
8444 } else if (CmpRes == ATrue) {
8445 IsTrue = true;
8446 } else {
8447 return;
8448 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008449 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008450
8451 // If this is a comparison to an enum constant, include that
8452 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00008453 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008454 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8455 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8456
8457 SmallString<64> PrettySourceValue;
8458 llvm::raw_svector_ostream OS(PrettySourceValue);
8459 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00008460 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008461 else
8462 OS << Value;
8463
Richard Trieu0f097742014-04-04 04:13:47 +00008464 S.DiagRuntimeBehavior(
8465 E->getOperatorLoc(), E,
8466 S.PDiag(diag::warn_out_of_range_compare)
8467 << OS.str() << LiteralOrBoolConstant
8468 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8469 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008470}
8471
John McCallcc7e5bf2010-05-06 08:58:33 +00008472/// Analyze the operands of the given comparison. Implements the
8473/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008474void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00008475 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8476 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008477}
John McCall263a48b2010-01-04 23:31:57 +00008478
John McCallca01b222010-01-04 23:21:16 +00008479/// \brief Implements -Wsign-compare.
8480///
Richard Trieu82402a02011-09-15 21:56:47 +00008481/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008482void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008483 // The type the comparison is being performed in.
8484 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00008485
8486 // Only analyze comparison operators where both sides have been converted to
8487 // the same type.
8488 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8489 return AnalyzeImpConvsInComparison(S, E);
8490
8491 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00008492 if (E->isValueDependent())
8493 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008494
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008495 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8496 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008497
8498 bool IsComparisonConstant = false;
8499
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008500 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008501 // of 'true' or 'false'.
8502 if (T->isIntegralType(S.Context)) {
8503 llvm::APSInt RHSValue;
8504 bool IsRHSIntegralLiteral =
8505 RHS->isIntegerConstantExpr(RHSValue, S.Context);
8506 llvm::APSInt LHSValue;
8507 bool IsLHSIntegralLiteral =
8508 LHS->isIntegerConstantExpr(LHSValue, S.Context);
8509 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8510 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8511 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8512 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8513 else
8514 IsComparisonConstant =
8515 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008516 } else if (!T->hasUnsignedIntegerRepresentation())
8517 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008518
John McCallcc7e5bf2010-05-06 08:58:33 +00008519 // We don't do anything special if this isn't an unsigned integral
8520 // comparison: we're only interested in integral comparisons, and
8521 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00008522 //
8523 // We also don't care about value-dependent expressions or expressions
8524 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008525 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00008526 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008527
John McCallcc7e5bf2010-05-06 08:58:33 +00008528 // Check to see if one of the (unmodified) operands is of different
8529 // signedness.
8530 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00008531 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8532 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00008533 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00008534 signedOperand = LHS;
8535 unsignedOperand = RHS;
8536 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8537 signedOperand = RHS;
8538 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00008539 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00008540 CheckTrivialUnsignedComparison(S, E);
8541 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008542 }
8543
John McCallcc7e5bf2010-05-06 08:58:33 +00008544 // Otherwise, calculate the effective range of the signed operand.
8545 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00008546
John McCallcc7e5bf2010-05-06 08:58:33 +00008547 // Go ahead and analyze implicit conversions in the operands. Note
8548 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00008549 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8550 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00008551
John McCallcc7e5bf2010-05-06 08:58:33 +00008552 // If the signed range is non-negative, -Wsign-compare won't fire,
8553 // but we should still check for comparisons which are always true
8554 // or false.
8555 if (signedRange.NonNegative)
8556 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008557
8558 // For (in)equality comparisons, if the unsigned operand is a
8559 // constant which cannot collide with a overflowed signed operand,
8560 // then reinterpreting the signed operand as unsigned will not
8561 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00008562 if (E->isEqualityOp()) {
8563 unsigned comparisonWidth = S.Context.getIntWidth(T);
8564 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00008565
John McCallcc7e5bf2010-05-06 08:58:33 +00008566 // We should never be unable to prove that the unsigned operand is
8567 // non-negative.
8568 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8569
8570 if (unsignedRange.Width < comparisonWidth)
8571 return;
8572 }
8573
Douglas Gregorbfb4a212012-05-01 01:53:49 +00008574 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8575 S.PDiag(diag::warn_mixed_sign_comparison)
8576 << LHS->getType() << RHS->getType()
8577 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00008578}
8579
John McCall1f425642010-11-11 03:21:53 +00008580/// Analyzes an attempt to assign the given value to a bitfield.
8581///
8582/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008583bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8584 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00008585 assert(Bitfield->isBitField());
8586 if (Bitfield->isInvalidDecl())
8587 return false;
8588
John McCalldeebbcf2010-11-11 05:33:51 +00008589 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00008590 QualType BitfieldType = Bitfield->getType();
8591 if (BitfieldType->isBooleanType())
8592 return false;
8593
8594 if (BitfieldType->isEnumeralType()) {
8595 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
8596 // If the underlying enum type was not explicitly specified as an unsigned
8597 // type and the enum contain only positive values, MSVC++ will cause an
8598 // inconsistency by storing this as a signed type.
8599 if (S.getLangOpts().CPlusPlus11 &&
8600 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
8601 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
8602 BitfieldEnumDecl->getNumNegativeBits() == 0) {
8603 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
8604 << BitfieldEnumDecl->getNameAsString();
8605 }
8606 }
8607
John McCalldeebbcf2010-11-11 05:33:51 +00008608 if (Bitfield->getType()->isBooleanType())
8609 return false;
8610
Douglas Gregor789adec2011-02-04 13:09:01 +00008611 // Ignore value- or type-dependent expressions.
8612 if (Bitfield->getBitWidth()->isValueDependent() ||
8613 Bitfield->getBitWidth()->isTypeDependent() ||
8614 Init->isValueDependent() ||
8615 Init->isTypeDependent())
8616 return false;
8617
John McCall1f425642010-11-11 03:21:53 +00008618 Expr *OriginalInit = Init->IgnoreParenImpCasts();
8619
Richard Smith5fab0c92011-12-28 19:48:30 +00008620 llvm::APSInt Value;
8621 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00008622 return false;
8623
John McCall1f425642010-11-11 03:21:53 +00008624 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00008625 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00008626
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008627 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00008628 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008629 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8630 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00008631
John McCall1f425642010-11-11 03:21:53 +00008632 if (OriginalWidth <= FieldWidth)
8633 return false;
8634
Eli Friedmanc267a322012-01-26 23:11:39 +00008635 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00008636 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00008637 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00008638
Eli Friedmanc267a322012-01-26 23:11:39 +00008639 // Check whether the stored value is equal to the original value.
8640 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00008641 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00008642 return false;
8643
Eli Friedmanc267a322012-01-26 23:11:39 +00008644 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00008645 // therefore don't strictly fit into a signed bitfield of width 1.
8646 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00008647 return false;
8648
John McCall1f425642010-11-11 03:21:53 +00008649 std::string PrettyValue = Value.toString(10);
8650 std::string PrettyTrunc = TruncatedValue.toString(10);
8651
8652 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8653 << PrettyValue << PrettyTrunc << OriginalInit->getType()
8654 << Init->getSourceRange();
8655
8656 return true;
8657}
8658
John McCalld2a53122010-11-09 23:24:47 +00008659/// Analyze the given simple or compound assignment for warning-worthy
8660/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008661void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00008662 // Just recurse on the LHS.
8663 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8664
8665 // We want to recurse on the RHS as normal unless we're assigning to
8666 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00008667 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008668 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00008669 E->getOperatorLoc())) {
8670 // Recurse, ignoring any implicit conversions on the RHS.
8671 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8672 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00008673 }
8674 }
8675
8676 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8677}
8678
John McCall263a48b2010-01-04 23:31:57 +00008679/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008680void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8681 SourceLocation CContext, unsigned diag,
8682 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008683 if (pruneControlFlow) {
8684 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8685 S.PDiag(diag)
8686 << SourceType << T << E->getSourceRange()
8687 << SourceRange(CContext));
8688 return;
8689 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00008690 S.Diag(E->getExprLoc(), diag)
8691 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8692}
8693
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008694/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008695void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8696 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008697 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008698}
8699
Richard Trieube234c32016-04-21 21:04:55 +00008700
8701/// Diagnose an implicit cast from a floating point value to an integer value.
8702void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8703
8704 SourceLocation CContext) {
8705 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00008706 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00008707
8708 Expr *InnerE = E->IgnoreParenImpCasts();
8709 // We also want to warn on, e.g., "int i = -1.234"
8710 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8711 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8712 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8713
8714 const bool IsLiteral =
8715 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8716
8717 llvm::APFloat Value(0.0);
8718 bool IsConstant =
8719 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8720 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00008721 return DiagnoseImpCast(S, E, T, CContext,
8722 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00008723 }
8724
Chandler Carruth016ef402011-04-10 08:36:24 +00008725 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00008726
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00008727 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8728 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00008729 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8730 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00008731 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00008732 if (IsLiteral) return;
8733 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8734 PruneWarnings);
8735 }
8736
8737 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00008738 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00008739 // Warn on floating point literal to integer.
8740 DiagID = diag::warn_impcast_literal_float_to_integer;
8741 } else if (IntegerValue == 0) {
8742 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
8743 return DiagnoseImpCast(S, E, T, CContext,
8744 diag::warn_impcast_float_integer, PruneWarnings);
8745 }
8746 // Warn on non-zero to zero conversion.
8747 DiagID = diag::warn_impcast_float_to_integer_zero;
8748 } else {
8749 if (IntegerValue.isUnsigned()) {
8750 if (!IntegerValue.isMaxValue()) {
8751 return DiagnoseImpCast(S, E, T, CContext,
8752 diag::warn_impcast_float_integer, PruneWarnings);
8753 }
8754 } else { // IntegerValue.isSigned()
8755 if (!IntegerValue.isMaxSignedValue() &&
8756 !IntegerValue.isMinSignedValue()) {
8757 return DiagnoseImpCast(S, E, T, CContext,
8758 diag::warn_impcast_float_integer, PruneWarnings);
8759 }
8760 }
8761 // Warn on evaluatable floating point expression to integer conversion.
8762 DiagID = diag::warn_impcast_float_to_integer;
8763 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008764
Eli Friedman07185912013-08-29 23:44:43 +00008765 // FIXME: Force the precision of the source value down so we don't print
8766 // digits which are usually useless (we don't really care here if we
8767 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
8768 // would automatically print the shortest representation, but it's a bit
8769 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00008770 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00008771 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
8772 precision = (precision * 59 + 195) / 196;
8773 Value.toString(PrettySourceValue, precision);
8774
David Blaikie9b88cc02012-05-15 17:18:27 +00008775 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00008776 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00008777 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00008778 else
David Blaikie9b88cc02012-05-15 17:18:27 +00008779 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00008780
Richard Trieube234c32016-04-21 21:04:55 +00008781 if (PruneWarnings) {
8782 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8783 S.PDiag(DiagID)
8784 << E->getType() << T.getUnqualifiedType()
8785 << PrettySourceValue << PrettyTargetValue
8786 << E->getSourceRange() << SourceRange(CContext));
8787 } else {
8788 S.Diag(E->getExprLoc(), DiagID)
8789 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8790 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8791 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008792}
8793
John McCall18a2c2c2010-11-09 22:22:12 +00008794std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8795 if (!Range.Width) return "0";
8796
8797 llvm::APSInt ValueInRange = Value;
8798 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00008799 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00008800 return ValueInRange.toString(10);
8801}
8802
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008803bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008804 if (!isa<ImplicitCastExpr>(Ex))
8805 return false;
8806
8807 Expr *InnerE = Ex->IgnoreParenImpCasts();
8808 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8809 const Type *Source =
8810 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8811 if (Target->isDependentType())
8812 return false;
8813
8814 const BuiltinType *FloatCandidateBT =
8815 dyn_cast<BuiltinType>(ToBool ? Source : Target);
8816 const Type *BoolCandidateType = ToBool ? Target : Source;
8817
8818 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8819 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8820}
8821
8822void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8823 SourceLocation CC) {
8824 unsigned NumArgs = TheCall->getNumArgs();
8825 for (unsigned i = 0; i < NumArgs; ++i) {
8826 Expr *CurrA = TheCall->getArg(i);
8827 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8828 continue;
8829
8830 bool IsSwapped = ((i > 0) &&
8831 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8832 IsSwapped |= ((i < (NumArgs - 1)) &&
8833 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8834 if (IsSwapped) {
8835 // Warn on this floating-point to bool conversion.
8836 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8837 CurrA->getType(), CC,
8838 diag::warn_impcast_floating_point_to_bool);
8839 }
8840 }
8841}
8842
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008843void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00008844 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
8845 E->getExprLoc()))
8846 return;
8847
Richard Trieu09d6b802016-01-08 23:35:06 +00008848 // Don't warn on functions which have return type nullptr_t.
8849 if (isa<CallExpr>(E))
8850 return;
8851
Richard Trieu5b993502014-10-15 03:42:06 +00008852 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
8853 const Expr::NullPointerConstantKind NullKind =
8854 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
8855 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
8856 return;
8857
8858 // Return if target type is a safe conversion.
8859 if (T->isAnyPointerType() || T->isBlockPointerType() ||
8860 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8861 return;
8862
8863 SourceLocation Loc = E->getSourceRange().getBegin();
8864
Richard Trieu0a5e1662016-02-13 00:58:53 +00008865 // Venture through the macro stacks to get to the source of macro arguments.
8866 // The new location is a better location than the complete location that was
8867 // passed in.
8868 while (S.SourceMgr.isMacroArgExpansion(Loc))
8869 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8870
8871 while (S.SourceMgr.isMacroArgExpansion(CC))
8872 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8873
Richard Trieu5b993502014-10-15 03:42:06 +00008874 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00008875 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8876 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8877 Loc, S.SourceMgr, S.getLangOpts());
8878 if (MacroName == "NULL")
8879 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00008880 }
8881
8882 // Only warn if the null and context location are in the same macro expansion.
8883 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8884 return;
8885
8886 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8887 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8888 << FixItHint::CreateReplacement(Loc,
8889 S.getFixItZeroLiteralForType(T, Loc));
8890}
8891
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008892void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8893 ObjCArrayLiteral *ArrayLiteral);
8894void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8895 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00008896
8897/// Check a single element within a collection literal against the
8898/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008899void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8900 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008901 // Skip a bitcast to 'id' or qualified 'id'.
8902 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8903 if (ICE->getCastKind() == CK_BitCast &&
8904 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8905 Element = ICE->getSubExpr();
8906 }
8907
8908 QualType ElementType = Element->getType();
8909 ExprResult ElementResult(Element);
8910 if (ElementType->getAs<ObjCObjectPointerType>() &&
8911 S.CheckSingleAssignmentConstraints(TargetElementType,
8912 ElementResult,
8913 false, false)
8914 != Sema::Compatible) {
8915 S.Diag(Element->getLocStart(),
8916 diag::warn_objc_collection_literal_element)
8917 << ElementType << ElementKind << TargetElementType
8918 << Element->getSourceRange();
8919 }
8920
8921 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8922 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8923 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8924 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8925}
8926
8927/// Check an Objective-C array literal being converted to the given
8928/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008929void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8930 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008931 if (!S.NSArrayDecl)
8932 return;
8933
8934 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8935 if (!TargetObjCPtr)
8936 return;
8937
8938 if (TargetObjCPtr->isUnspecialized() ||
8939 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8940 != S.NSArrayDecl->getCanonicalDecl())
8941 return;
8942
8943 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8944 if (TypeArgs.size() != 1)
8945 return;
8946
8947 QualType TargetElementType = TypeArgs[0];
8948 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8949 checkObjCCollectionLiteralElement(S, TargetElementType,
8950 ArrayLiteral->getElement(I),
8951 0);
8952 }
8953}
8954
8955/// Check an Objective-C dictionary literal being converted to the given
8956/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008957void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8958 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008959 if (!S.NSDictionaryDecl)
8960 return;
8961
8962 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8963 if (!TargetObjCPtr)
8964 return;
8965
8966 if (TargetObjCPtr->isUnspecialized() ||
8967 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8968 != S.NSDictionaryDecl->getCanonicalDecl())
8969 return;
8970
8971 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8972 if (TypeArgs.size() != 2)
8973 return;
8974
8975 QualType TargetKeyType = TypeArgs[0];
8976 QualType TargetObjectType = TypeArgs[1];
8977 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8978 auto Element = DictionaryLiteral->getKeyValueElement(I);
8979 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8980 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8981 }
8982}
8983
Richard Trieufc404c72016-02-05 23:02:38 +00008984// Helper function to filter out cases for constant width constant conversion.
8985// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008986bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8987 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00008988 // If initializing from a constant, and the constant starts with '0',
8989 // then it is a binary, octal, or hexadecimal. Allow these constants
8990 // to fill all the bits, even if there is a sign change.
8991 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8992 const char FirstLiteralCharacter =
8993 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8994 if (FirstLiteralCharacter == '0')
8995 return false;
8996 }
8997
8998 // If the CC location points to a '{', and the type is char, then assume
8999 // assume it is an array initialization.
9000 if (CC.isValid() && T->isCharType()) {
9001 const char FirstContextCharacter =
9002 S.getSourceManager().getCharacterData(CC)[0];
9003 if (FirstContextCharacter == '{')
9004 return false;
9005 }
9006
9007 return true;
9008}
9009
John McCallcc7e5bf2010-05-06 08:58:33 +00009010void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00009011 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009012 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00009013
John McCallcc7e5bf2010-05-06 08:58:33 +00009014 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9015 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9016 if (Source == Target) return;
9017 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00009018
Chandler Carruthc22845a2011-07-26 05:40:03 +00009019 // If the conversion context location is invalid don't complain. We also
9020 // don't want to emit a warning if the issue occurs from the expansion of
9021 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9022 // delay this check as long as possible. Once we detect we are in that
9023 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009024 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00009025 return;
9026
Richard Trieu021baa32011-09-23 20:10:00 +00009027 // Diagnose implicit casts to bool.
9028 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9029 if (isa<StringLiteral>(E))
9030 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00009031 // and expressions, for instance, assert(0 && "error here"), are
9032 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00009033 return DiagnoseImpCast(S, E, T, CC,
9034 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00009035 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9036 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9037 // This covers the literal expressions that evaluate to Objective-C
9038 // objects.
9039 return DiagnoseImpCast(S, E, T, CC,
9040 diag::warn_impcast_objective_c_literal_to_bool);
9041 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009042 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9043 // Warn on pointer to bool conversion that is always true.
9044 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9045 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00009046 }
Richard Trieu021baa32011-09-23 20:10:00 +00009047 }
John McCall263a48b2010-01-04 23:31:57 +00009048
Douglas Gregor5054cb02015-07-07 03:58:22 +00009049 // Check implicit casts from Objective-C collection literals to specialized
9050 // collection types, e.g., NSArray<NSString *> *.
9051 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9052 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9053 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9054 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9055
John McCall263a48b2010-01-04 23:31:57 +00009056 // Strip vector types.
9057 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009058 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009059 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009060 return;
John McCallacf0ee52010-10-08 02:01:28 +00009061 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009062 }
Chris Lattneree7286f2011-06-14 04:51:15 +00009063
9064 // If the vector cast is cast between two vectors of the same size, it is
9065 // a bitcast, not a conversion.
9066 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9067 return;
John McCall263a48b2010-01-04 23:31:57 +00009068
9069 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9070 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9071 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00009072 if (auto VecTy = dyn_cast<VectorType>(Target))
9073 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00009074
9075 // Strip complex types.
9076 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009077 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009078 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009079 return;
9080
John McCallacf0ee52010-10-08 02:01:28 +00009081 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009082 }
John McCall263a48b2010-01-04 23:31:57 +00009083
9084 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9085 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9086 }
9087
9088 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9089 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9090
9091 // If the source is floating point...
9092 if (SourceBT && SourceBT->isFloatingPoint()) {
9093 // ...and the target is floating point...
9094 if (TargetBT && TargetBT->isFloatingPoint()) {
9095 // ...then warn if we're dropping FP rank.
9096
9097 // Builtin FP kinds are ordered by increasing FP rank.
9098 if (SourceBT->getKind() > TargetBT->getKind()) {
9099 // Don't warn about float constants that are precisely
9100 // representable in the target type.
9101 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009102 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00009103 // Value might be a float, a float vector, or a float complex.
9104 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00009105 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9106 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00009107 return;
9108 }
9109
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009110 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009111 return;
9112
John McCallacf0ee52010-10-08 02:01:28 +00009113 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00009114 }
9115 // ... or possibly if we're increasing rank, too
9116 else if (TargetBT->getKind() > SourceBT->getKind()) {
9117 if (S.SourceMgr.isInSystemMacro(CC))
9118 return;
9119
9120 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00009121 }
9122 return;
9123 }
9124
Richard Trieube234c32016-04-21 21:04:55 +00009125 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00009126 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009127 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009128 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00009129
Richard Trieube234c32016-04-21 21:04:55 +00009130 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00009131 }
John McCall263a48b2010-01-04 23:31:57 +00009132
Richard Smith54894fd2015-12-30 01:06:52 +00009133 // Detect the case where a call result is converted from floating-point to
9134 // to bool, and the final argument to the call is converted from bool, to
9135 // discover this typo:
9136 //
9137 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9138 //
9139 // FIXME: This is an incredibly special case; is there some more general
9140 // way to detect this class of misplaced-parentheses bug?
9141 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009142 // Check last argument of function call to see if it is an
9143 // implicit cast from a type matching the type the result
9144 // is being cast to.
9145 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00009146 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009147 Expr *LastA = CEx->getArg(NumArgs - 1);
9148 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00009149 if (isa<ImplicitCastExpr>(LastA) &&
9150 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009151 // Warn on this floating-point to bool conversion
9152 DiagnoseImpCast(S, E, T, CC,
9153 diag::warn_impcast_floating_point_to_bool);
9154 }
9155 }
9156 }
John McCall263a48b2010-01-04 23:31:57 +00009157 return;
9158 }
9159
Richard Trieu5b993502014-10-15 03:42:06 +00009160 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00009161
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009162 S.DiscardMisalignedMemberAddress(Target, E);
9163
David Blaikie9366d2b2012-06-19 21:19:06 +00009164 if (!Source->isIntegerType() || !Target->isIntegerType())
9165 return;
9166
David Blaikie7555b6a2012-05-15 16:56:36 +00009167 // TODO: remove this early return once the false positives for constant->bool
9168 // in templates, macros, etc, are reduced or removed.
9169 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9170 return;
9171
John McCallcc7e5bf2010-05-06 08:58:33 +00009172 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00009173 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00009174
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009175 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00009176 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009177 // TODO: this should happen for bitfield stores, too.
9178 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00009179 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009180 if (S.SourceMgr.isInSystemMacro(CC))
9181 return;
9182
John McCall18a2c2c2010-11-09 22:22:12 +00009183 std::string PrettySourceValue = Value.toString(10);
9184 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009185
Ted Kremenek33ba9952011-10-22 02:37:33 +00009186 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9187 S.PDiag(diag::warn_impcast_integer_precision_constant)
9188 << PrettySourceValue << PrettyTargetValue
9189 << E->getType() << T << E->getSourceRange()
9190 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00009191 return;
9192 }
9193
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009194 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9195 if (S.SourceMgr.isInSystemMacro(CC))
9196 return;
9197
David Blaikie9455da02012-04-12 22:40:54 +00009198 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00009199 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9200 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00009201 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00009202 }
9203
Richard Trieudcb55572016-01-29 23:51:16 +00009204 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9205 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9206 // Warn when doing a signed to signed conversion, warn if the positive
9207 // source value is exactly the width of the target type, which will
9208 // cause a negative value to be stored.
9209
9210 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00009211 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9212 !S.SourceMgr.isInSystemMacro(CC)) {
9213 if (isSameWidthConstantConversion(S, E, T, CC)) {
9214 std::string PrettySourceValue = Value.toString(10);
9215 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00009216
Richard Trieufc404c72016-02-05 23:02:38 +00009217 S.DiagRuntimeBehavior(
9218 E->getExprLoc(), E,
9219 S.PDiag(diag::warn_impcast_integer_precision_constant)
9220 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9221 << E->getSourceRange() << clang::SourceRange(CC));
9222 return;
Richard Trieudcb55572016-01-29 23:51:16 +00009223 }
9224 }
Richard Trieufc404c72016-02-05 23:02:38 +00009225
Richard Trieudcb55572016-01-29 23:51:16 +00009226 // Fall through for non-constants to give a sign conversion warning.
9227 }
9228
John McCallcc7e5bf2010-05-06 08:58:33 +00009229 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9230 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9231 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009232 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009233 return;
9234
John McCallcc7e5bf2010-05-06 08:58:33 +00009235 unsigned DiagID = diag::warn_impcast_integer_sign;
9236
9237 // Traditionally, gcc has warned about this under -Wsign-compare.
9238 // We also want to warn about it in -Wconversion.
9239 // So if -Wconversion is off, use a completely identical diagnostic
9240 // in the sign-compare group.
9241 // The conditional-checking code will
9242 if (ICContext) {
9243 DiagID = diag::warn_impcast_integer_sign_conditional;
9244 *ICContext = true;
9245 }
9246
John McCallacf0ee52010-10-08 02:01:28 +00009247 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00009248 }
9249
Douglas Gregora78f1932011-02-22 02:45:07 +00009250 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00009251 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9252 // type, to give us better diagnostics.
9253 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009254 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00009255 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9256 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9257 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9258 SourceType = S.Context.getTypeDeclType(Enum);
9259 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9260 }
9261 }
9262
Douglas Gregora78f1932011-02-22 02:45:07 +00009263 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9264 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00009265 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9266 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009267 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009268 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009269 return;
9270
Douglas Gregor364f7db2011-03-12 00:14:31 +00009271 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00009272 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009273 }
John McCall263a48b2010-01-04 23:31:57 +00009274}
9275
David Blaikie18e9ac72012-05-15 21:57:38 +00009276void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9277 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009278
9279void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00009280 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009281 E = E->IgnoreParenImpCasts();
9282
9283 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00009284 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009285
John McCallacf0ee52010-10-08 02:01:28 +00009286 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009287 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009288 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00009289}
9290
David Blaikie18e9ac72012-05-15 21:57:38 +00009291void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9292 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00009293 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009294
9295 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00009296 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9297 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009298
9299 // If -Wconversion would have warned about either of the candidates
9300 // for a signedness conversion to the context type...
9301 if (!Suspicious) return;
9302
9303 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009304 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00009305 return;
9306
John McCallcc7e5bf2010-05-06 08:58:33 +00009307 // ...then check whether it would have warned about either of the
9308 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00009309 if (E->getType() == T) return;
9310
9311 Suspicious = false;
9312 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9313 E->getType(), CC, &Suspicious);
9314 if (!Suspicious)
9315 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00009316 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009317}
9318
Richard Trieu65724892014-11-15 06:37:39 +00009319/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9320/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009321void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00009322 if (S.getLangOpts().Bool)
9323 return;
9324 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9325}
9326
John McCallcc7e5bf2010-05-06 08:58:33 +00009327/// AnalyzeImplicitConversions - Find and report any interesting
9328/// implicit conversions in the given expression. There are a couple
9329/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009330void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00009331 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00009332 Expr *E = OrigE->IgnoreParenImpCasts();
9333
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00009334 if (E->isTypeDependent() || E->isValueDependent())
9335 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00009336
John McCallcc7e5bf2010-05-06 08:58:33 +00009337 // For conditional operators, we analyze the arguments as if they
9338 // were being fed directly into the output.
9339 if (isa<ConditionalOperator>(E)) {
9340 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00009341 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009342 return;
9343 }
9344
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009345 // Check implicit argument conversions for function calls.
9346 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9347 CheckImplicitArgumentConversions(S, Call, CC);
9348
John McCallcc7e5bf2010-05-06 08:58:33 +00009349 // Go ahead and check any implicit conversions we might have skipped.
9350 // The non-canonical typecheck is just an optimization;
9351 // CheckImplicitConversion will filter out dead implicit conversions.
9352 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009353 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009354
9355 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00009356
9357 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9358 // The bound subexpressions in a PseudoObjectExpr are not reachable
9359 // as transitive children.
9360 // FIXME: Use a more uniform representation for this.
9361 for (auto *SE : POE->semantics())
9362 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9363 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00009364 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00009365
John McCallcc7e5bf2010-05-06 08:58:33 +00009366 // Skip past explicit casts.
9367 if (isa<ExplicitCastExpr>(E)) {
9368 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00009369 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009370 }
9371
John McCalld2a53122010-11-09 23:24:47 +00009372 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9373 // Do a somewhat different check with comparison operators.
9374 if (BO->isComparisonOp())
9375 return AnalyzeComparison(S, BO);
9376
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009377 // And with simple assignments.
9378 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00009379 return AnalyzeAssignment(S, BO);
9380 }
John McCallcc7e5bf2010-05-06 08:58:33 +00009381
9382 // These break the otherwise-useful invariant below. Fortunately,
9383 // we don't really need to recurse into them, because any internal
9384 // expressions should have been analyzed already when they were
9385 // built into statements.
9386 if (isa<StmtExpr>(E)) return;
9387
9388 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00009389 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00009390
9391 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00009392 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00009393 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00009394 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00009395 for (Stmt *SubStmt : E->children()) {
9396 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00009397 if (!ChildExpr)
9398 continue;
9399
Richard Trieu955231d2014-01-25 01:10:35 +00009400 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00009401 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00009402 // Ignore checking string literals that are in logical and operators.
9403 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00009404 continue;
9405 AnalyzeImplicitConversions(S, ChildExpr, CC);
9406 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009407
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009408 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00009409 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9410 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009411 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00009412
9413 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9414 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009415 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009416 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009417
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009418 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9419 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00009420 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009421}
9422
9423} // end anonymous namespace
9424
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009425/// Diagnose integer type and any valid implicit convertion to it.
9426static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9427 // Taking into account implicit conversions,
9428 // allow any integer.
9429 if (!E->getType()->isIntegerType()) {
9430 S.Diag(E->getLocStart(),
9431 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9432 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009433 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009434 // Potentially emit standard warnings for implicit conversions if enabled
9435 // using -Wconversion.
9436 CheckImplicitConversion(S, E, IntT, E->getLocStart());
9437 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009438}
9439
Richard Trieuc1888e02014-06-28 23:25:37 +00009440// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9441// Returns true when emitting a warning about taking the address of a reference.
9442static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00009443 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00009444 E = E->IgnoreParenImpCasts();
9445
9446 const FunctionDecl *FD = nullptr;
9447
9448 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9449 if (!DRE->getDecl()->getType()->isReferenceType())
9450 return false;
9451 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9452 if (!M->getMemberDecl()->getType()->isReferenceType())
9453 return false;
9454 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00009455 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00009456 return false;
9457 FD = Call->getDirectCallee();
9458 } else {
9459 return false;
9460 }
9461
9462 SemaRef.Diag(E->getExprLoc(), PD);
9463
9464 // If possible, point to location of function.
9465 if (FD) {
9466 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9467 }
9468
9469 return true;
9470}
9471
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009472// Returns true if the SourceLocation is expanded from any macro body.
9473// Returns false if the SourceLocation is invalid, is from not in a macro
9474// expansion, or is from expanded from a top-level macro argument.
9475static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9476 if (Loc.isInvalid())
9477 return false;
9478
9479 while (Loc.isMacroID()) {
9480 if (SM.isMacroBodyExpansion(Loc))
9481 return true;
9482 Loc = SM.getImmediateMacroCallerLoc(Loc);
9483 }
9484
9485 return false;
9486}
9487
Richard Trieu3bb8b562014-02-26 02:36:06 +00009488/// \brief Diagnose pointers that are always non-null.
9489/// \param E the expression containing the pointer
9490/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9491/// compared to a null pointer
9492/// \param IsEqual True when the comparison is equal to a null pointer
9493/// \param Range Extra SourceRange to highlight in the diagnostic
9494void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9495 Expr::NullPointerConstantKind NullKind,
9496 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00009497 if (!E)
9498 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009499
9500 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009501 if (E->getExprLoc().isMacroID()) {
9502 const SourceManager &SM = getSourceManager();
9503 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9504 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00009505 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009506 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009507 E = E->IgnoreImpCasts();
9508
9509 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9510
Richard Trieuf7432752014-06-06 21:39:26 +00009511 if (isa<CXXThisExpr>(E)) {
9512 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9513 : diag::warn_this_bool_conversion;
9514 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9515 return;
9516 }
9517
Richard Trieu3bb8b562014-02-26 02:36:06 +00009518 bool IsAddressOf = false;
9519
9520 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9521 if (UO->getOpcode() != UO_AddrOf)
9522 return;
9523 IsAddressOf = true;
9524 E = UO->getSubExpr();
9525 }
9526
Richard Trieuc1888e02014-06-28 23:25:37 +00009527 if (IsAddressOf) {
9528 unsigned DiagID = IsCompare
9529 ? diag::warn_address_of_reference_null_compare
9530 : diag::warn_address_of_reference_bool_conversion;
9531 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9532 << IsEqual;
9533 if (CheckForReference(*this, E, PD)) {
9534 return;
9535 }
9536 }
9537
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009538 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9539 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00009540 std::string Str;
9541 llvm::raw_string_ostream S(Str);
9542 E->printPretty(S, nullptr, getPrintingPolicy());
9543 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9544 : diag::warn_cast_nonnull_to_bool;
9545 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9546 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009547 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00009548 };
9549
9550 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9551 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9552 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009553 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9554 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009555 return;
9556 }
9557 }
9558 }
9559
Richard Trieu3bb8b562014-02-26 02:36:06 +00009560 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00009561 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009562 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9563 D = R->getDecl();
9564 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9565 D = M->getMemberDecl();
9566 }
9567
9568 // Weak Decls can be null.
9569 if (!D || D->isWeak())
9570 return;
George Burgess IV850269a2015-12-08 22:02:00 +00009571
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009572 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00009573 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9574 if (getCurFunction() &&
9575 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009576 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9577 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009578 return;
9579 }
9580
9581 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +00009582 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +00009583 assert(ParamIter != FD->param_end());
9584 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9585
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009586 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9587 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009588 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +00009589 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009590 }
George Burgess IV850269a2015-12-08 22:02:00 +00009591
9592 for (unsigned ArgNo : NonNull->args()) {
9593 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009594 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009595 return;
9596 }
George Burgess IV850269a2015-12-08 22:02:00 +00009597 }
9598 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009599 }
9600 }
George Burgess IV850269a2015-12-08 22:02:00 +00009601 }
9602
Richard Trieu3bb8b562014-02-26 02:36:06 +00009603 QualType T = D->getType();
9604 const bool IsArray = T->isArrayType();
9605 const bool IsFunction = T->isFunctionType();
9606
Richard Trieuc1888e02014-06-28 23:25:37 +00009607 // Address of function is used to silence the function warning.
9608 if (IsAddressOf && IsFunction) {
9609 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009610 }
9611
9612 // Found nothing.
9613 if (!IsAddressOf && !IsFunction && !IsArray)
9614 return;
9615
9616 // Pretty print the expression for the diagnostic.
9617 std::string Str;
9618 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00009619 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00009620
9621 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9622 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00009623 enum {
9624 AddressOf,
9625 FunctionPointer,
9626 ArrayPointer
9627 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009628 if (IsAddressOf)
9629 DiagType = AddressOf;
9630 else if (IsFunction)
9631 DiagType = FunctionPointer;
9632 else if (IsArray)
9633 DiagType = ArrayPointer;
9634 else
9635 llvm_unreachable("Could not determine diagnostic.");
9636 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9637 << Range << IsEqual;
9638
9639 if (!IsFunction)
9640 return;
9641
9642 // Suggest '&' to silence the function warning.
9643 Diag(E->getExprLoc(), diag::note_function_warning_silence)
9644 << FixItHint::CreateInsertion(E->getLocStart(), "&");
9645
9646 // Check to see if '()' fixit should be emitted.
9647 QualType ReturnType;
9648 UnresolvedSet<4> NonTemplateOverloads;
9649 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9650 if (ReturnType.isNull())
9651 return;
9652
9653 if (IsCompare) {
9654 // There are two cases here. If there is null constant, the only suggest
9655 // for a pointer return type. If the null is 0, then suggest if the return
9656 // type is a pointer or an integer type.
9657 if (!ReturnType->isPointerType()) {
9658 if (NullKind == Expr::NPCK_ZeroExpression ||
9659 NullKind == Expr::NPCK_ZeroLiteral) {
9660 if (!ReturnType->isIntegerType())
9661 return;
9662 } else {
9663 return;
9664 }
9665 }
9666 } else { // !IsCompare
9667 // For function to bool, only suggest if the function pointer has bool
9668 // return type.
9669 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9670 return;
9671 }
9672 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00009673 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00009674}
9675
John McCallcc7e5bf2010-05-06 08:58:33 +00009676/// Diagnoses "dangerous" implicit conversions within the given
9677/// expression (which is a full expression). Implements -Wconversion
9678/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009679///
9680/// \param CC the "context" location of the implicit conversion, i.e.
9681/// the most location of the syntactic entity requiring the implicit
9682/// conversion
9683void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009684 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00009685 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00009686 return;
9687
9688 // Don't diagnose for value- or type-dependent expressions.
9689 if (E->isTypeDependent() || E->isValueDependent())
9690 return;
9691
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009692 // Check for array bounds violations in cases where the check isn't triggered
9693 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9694 // ArraySubscriptExpr is on the RHS of a variable initialization.
9695 CheckArrayAccess(E);
9696
John McCallacf0ee52010-10-08 02:01:28 +00009697 // This is not the right CC for (e.g.) a variable initialization.
9698 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009699}
9700
Richard Trieu65724892014-11-15 06:37:39 +00009701/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9702/// Input argument E is a logical expression.
9703void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9704 ::CheckBoolLikeConversion(*this, E, CC);
9705}
9706
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009707/// Diagnose when expression is an integer constant expression and its evaluation
9708/// results in integer overflow
9709void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00009710 // Use a work list to deal with nested struct initializers.
9711 SmallVector<Expr *, 2> Exprs(1, E);
9712
9713 do {
9714 Expr *E = Exprs.pop_back_val();
9715
9716 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9717 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9718 continue;
9719 }
9720
9721 if (auto InitList = dyn_cast<InitListExpr>(E))
9722 Exprs.append(InitList->inits().begin(), InitList->inits().end());
9723 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009724}
9725
Richard Smithc406cb72013-01-17 01:17:56 +00009726namespace {
9727/// \brief Visitor for expressions which looks for unsequenced operations on the
9728/// same object.
9729class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009730 typedef EvaluatedExprVisitor<SequenceChecker> Base;
9731
Richard Smithc406cb72013-01-17 01:17:56 +00009732 /// \brief A tree of sequenced regions within an expression. Two regions are
9733 /// unsequenced if one is an ancestor or a descendent of the other. When we
9734 /// finish processing an expression with sequencing, such as a comma
9735 /// expression, we fold its tree nodes into its parent, since they are
9736 /// unsequenced with respect to nodes we will visit later.
9737 class SequenceTree {
9738 struct Value {
9739 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9740 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +00009741 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +00009742 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009743 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00009744
9745 public:
9746 /// \brief A region within an expression which may be sequenced with respect
9747 /// to some other region.
9748 class Seq {
9749 explicit Seq(unsigned N) : Index(N) {}
9750 unsigned Index;
9751 friend class SequenceTree;
9752 public:
9753 Seq() : Index(0) {}
9754 };
9755
9756 SequenceTree() { Values.push_back(Value(0)); }
9757 Seq root() const { return Seq(0); }
9758
9759 /// \brief Create a new sequence of operations, which is an unsequenced
9760 /// subset of \p Parent. This sequence of operations is sequenced with
9761 /// respect to other children of \p Parent.
9762 Seq allocate(Seq Parent) {
9763 Values.push_back(Value(Parent.Index));
9764 return Seq(Values.size() - 1);
9765 }
9766
9767 /// \brief Merge a sequence of operations into its parent.
9768 void merge(Seq S) {
9769 Values[S.Index].Merged = true;
9770 }
9771
9772 /// \brief Determine whether two operations are unsequenced. This operation
9773 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9774 /// should have been merged into its parent as appropriate.
9775 bool isUnsequenced(Seq Cur, Seq Old) {
9776 unsigned C = representative(Cur.Index);
9777 unsigned Target = representative(Old.Index);
9778 while (C >= Target) {
9779 if (C == Target)
9780 return true;
9781 C = Values[C].Parent;
9782 }
9783 return false;
9784 }
9785
9786 private:
9787 /// \brief Pick a representative for a sequence.
9788 unsigned representative(unsigned K) {
9789 if (Values[K].Merged)
9790 // Perform path compression as we go.
9791 return Values[K].Parent = representative(Values[K].Parent);
9792 return K;
9793 }
9794 };
9795
9796 /// An object for which we can track unsequenced uses.
9797 typedef NamedDecl *Object;
9798
9799 /// Different flavors of object usage which we track. We only track the
9800 /// least-sequenced usage of each kind.
9801 enum UsageKind {
9802 /// A read of an object. Multiple unsequenced reads are OK.
9803 UK_Use,
9804 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00009805 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00009806 UK_ModAsValue,
9807 /// A modification of an object which is not sequenced before the value
9808 /// computation of the expression, such as n++.
9809 UK_ModAsSideEffect,
9810
9811 UK_Count = UK_ModAsSideEffect + 1
9812 };
9813
9814 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00009815 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00009816 Expr *Use;
9817 SequenceTree::Seq Seq;
9818 };
9819
9820 struct UsageInfo {
9821 UsageInfo() : Diagnosed(false) {}
9822 Usage Uses[UK_Count];
9823 /// Have we issued a diagnostic for this variable already?
9824 bool Diagnosed;
9825 };
9826 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9827
9828 Sema &SemaRef;
9829 /// Sequenced regions within the expression.
9830 SequenceTree Tree;
9831 /// Declaration modifications and references which we have seen.
9832 UsageInfoMap UsageMap;
9833 /// The region we are currently within.
9834 SequenceTree::Seq Region;
9835 /// Filled in with declarations which were modified as a side-effect
9836 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009837 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00009838 /// Expressions to check later. We defer checking these to reduce
9839 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009840 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00009841
9842 /// RAII object wrapping the visitation of a sequenced subexpression of an
9843 /// expression. At the end of this process, the side-effects of the evaluation
9844 /// become sequenced with respect to the value computation of the result, so
9845 /// we downgrade any UK_ModAsSideEffect within the evaluation to
9846 /// UK_ModAsValue.
9847 struct SequencedSubexpression {
9848 SequencedSubexpression(SequenceChecker &Self)
9849 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9850 Self.ModAsSideEffect = &ModAsSideEffect;
9851 }
9852 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +00009853 for (auto &M : llvm::reverse(ModAsSideEffect)) {
9854 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +00009855 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +00009856 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9857 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +00009858 }
9859 Self.ModAsSideEffect = OldModAsSideEffect;
9860 }
9861
9862 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009863 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9864 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00009865 };
9866
Richard Smith40238f02013-06-20 22:21:56 +00009867 /// RAII object wrapping the visitation of a subexpression which we might
9868 /// choose to evaluate as a constant. If any subexpression is evaluated and
9869 /// found to be non-constant, this allows us to suppress the evaluation of
9870 /// the outer expression.
9871 class EvaluationTracker {
9872 public:
9873 EvaluationTracker(SequenceChecker &Self)
9874 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9875 Self.EvalTracker = this;
9876 }
9877 ~EvaluationTracker() {
9878 Self.EvalTracker = Prev;
9879 if (Prev)
9880 Prev->EvalOK &= EvalOK;
9881 }
9882
9883 bool evaluate(const Expr *E, bool &Result) {
9884 if (!EvalOK || E->isValueDependent())
9885 return false;
9886 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9887 return EvalOK;
9888 }
9889
9890 private:
9891 SequenceChecker &Self;
9892 EvaluationTracker *Prev;
9893 bool EvalOK;
9894 } *EvalTracker;
9895
Richard Smithc406cb72013-01-17 01:17:56 +00009896 /// \brief Find the object which is produced by the specified expression,
9897 /// if any.
9898 Object getObject(Expr *E, bool Mod) const {
9899 E = E->IgnoreParenCasts();
9900 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9901 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9902 return getObject(UO->getSubExpr(), Mod);
9903 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9904 if (BO->getOpcode() == BO_Comma)
9905 return getObject(BO->getRHS(), Mod);
9906 if (Mod && BO->isAssignmentOp())
9907 return getObject(BO->getLHS(), Mod);
9908 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9909 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9910 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9911 return ME->getMemberDecl();
9912 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9913 // FIXME: If this is a reference, map through to its value.
9914 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00009915 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00009916 }
9917
9918 /// \brief Note that an object was modified or used by an expression.
9919 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9920 Usage &U = UI.Uses[UK];
9921 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9922 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9923 ModAsSideEffect->push_back(std::make_pair(O, U));
9924 U.Use = Ref;
9925 U.Seq = Region;
9926 }
9927 }
9928 /// \brief Check whether a modification or use conflicts with a prior usage.
9929 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9930 bool IsModMod) {
9931 if (UI.Diagnosed)
9932 return;
9933
9934 const Usage &U = UI.Uses[OtherKind];
9935 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9936 return;
9937
9938 Expr *Mod = U.Use;
9939 Expr *ModOrUse = Ref;
9940 if (OtherKind == UK_Use)
9941 std::swap(Mod, ModOrUse);
9942
9943 SemaRef.Diag(Mod->getExprLoc(),
9944 IsModMod ? diag::warn_unsequenced_mod_mod
9945 : diag::warn_unsequenced_mod_use)
9946 << O << SourceRange(ModOrUse->getExprLoc());
9947 UI.Diagnosed = true;
9948 }
9949
9950 void notePreUse(Object O, Expr *Use) {
9951 UsageInfo &U = UsageMap[O];
9952 // Uses conflict with other modifications.
9953 checkUsage(O, U, Use, UK_ModAsValue, false);
9954 }
9955 void notePostUse(Object O, Expr *Use) {
9956 UsageInfo &U = UsageMap[O];
9957 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9958 addUsage(U, O, Use, UK_Use);
9959 }
9960
9961 void notePreMod(Object O, Expr *Mod) {
9962 UsageInfo &U = UsageMap[O];
9963 // Modifications conflict with other modifications and with uses.
9964 checkUsage(O, U, Mod, UK_ModAsValue, true);
9965 checkUsage(O, U, Mod, UK_Use, false);
9966 }
9967 void notePostMod(Object O, Expr *Use, UsageKind UK) {
9968 UsageInfo &U = UsageMap[O];
9969 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9970 addUsage(U, O, Use, UK);
9971 }
9972
9973public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009974 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00009975 : Base(S.Context), SemaRef(S), Region(Tree.root()),
9976 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009977 Visit(E);
9978 }
9979
9980 void VisitStmt(Stmt *S) {
9981 // Skip all statements which aren't expressions for now.
9982 }
9983
9984 void VisitExpr(Expr *E) {
9985 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00009986 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00009987 }
9988
9989 void VisitCastExpr(CastExpr *E) {
9990 Object O = Object();
9991 if (E->getCastKind() == CK_LValueToRValue)
9992 O = getObject(E->getSubExpr(), false);
9993
9994 if (O)
9995 notePreUse(O, E);
9996 VisitExpr(E);
9997 if (O)
9998 notePostUse(O, E);
9999 }
10000
10001 void VisitBinComma(BinaryOperator *BO) {
10002 // C++11 [expr.comma]p1:
10003 // Every value computation and side effect associated with the left
10004 // expression is sequenced before every value computation and side
10005 // effect associated with the right expression.
10006 SequenceTree::Seq LHS = Tree.allocate(Region);
10007 SequenceTree::Seq RHS = Tree.allocate(Region);
10008 SequenceTree::Seq OldRegion = Region;
10009
10010 {
10011 SequencedSubexpression SeqLHS(*this);
10012 Region = LHS;
10013 Visit(BO->getLHS());
10014 }
10015
10016 Region = RHS;
10017 Visit(BO->getRHS());
10018
10019 Region = OldRegion;
10020
10021 // Forget that LHS and RHS are sequenced. They are both unsequenced
10022 // with respect to other stuff.
10023 Tree.merge(LHS);
10024 Tree.merge(RHS);
10025 }
10026
10027 void VisitBinAssign(BinaryOperator *BO) {
10028 // The modification is sequenced after the value computation of the LHS
10029 // and RHS, so check it before inspecting the operands and update the
10030 // map afterwards.
10031 Object O = getObject(BO->getLHS(), true);
10032 if (!O)
10033 return VisitExpr(BO);
10034
10035 notePreMod(O, BO);
10036
10037 // C++11 [expr.ass]p7:
10038 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10039 // only once.
10040 //
10041 // Therefore, for a compound assignment operator, O is considered used
10042 // everywhere except within the evaluation of E1 itself.
10043 if (isa<CompoundAssignOperator>(BO))
10044 notePreUse(O, BO);
10045
10046 Visit(BO->getLHS());
10047
10048 if (isa<CompoundAssignOperator>(BO))
10049 notePostUse(O, BO);
10050
10051 Visit(BO->getRHS());
10052
Richard Smith83e37bee2013-06-26 23:16:51 +000010053 // C++11 [expr.ass]p1:
10054 // the assignment is sequenced [...] before the value computation of the
10055 // assignment expression.
10056 // C11 6.5.16/3 has no such rule.
10057 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10058 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010059 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010060
Richard Smithc406cb72013-01-17 01:17:56 +000010061 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10062 VisitBinAssign(CAO);
10063 }
10064
10065 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10066 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10067 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10068 Object O = getObject(UO->getSubExpr(), true);
10069 if (!O)
10070 return VisitExpr(UO);
10071
10072 notePreMod(O, UO);
10073 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000010074 // C++11 [expr.pre.incr]p1:
10075 // the expression ++x is equivalent to x+=1
10076 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10077 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010078 }
10079
10080 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10081 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10082 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10083 Object O = getObject(UO->getSubExpr(), true);
10084 if (!O)
10085 return VisitExpr(UO);
10086
10087 notePreMod(O, UO);
10088 Visit(UO->getSubExpr());
10089 notePostMod(O, UO, UK_ModAsSideEffect);
10090 }
10091
10092 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10093 void VisitBinLOr(BinaryOperator *BO) {
10094 // The side-effects of the LHS of an '&&' are sequenced before the
10095 // value computation of the RHS, and hence before the value computation
10096 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10097 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000010098 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010099 {
10100 SequencedSubexpression Sequenced(*this);
10101 Visit(BO->getLHS());
10102 }
10103
10104 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010105 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010106 if (!Result)
10107 Visit(BO->getRHS());
10108 } else {
10109 // Check for unsequenced operations in the RHS, treating it as an
10110 // entirely separate evaluation.
10111 //
10112 // FIXME: If there are operations in the RHS which are unsequenced
10113 // with respect to operations outside the RHS, and those operations
10114 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000010115 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010116 }
Richard Smithc406cb72013-01-17 01:17:56 +000010117 }
10118 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000010119 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010120 {
10121 SequencedSubexpression Sequenced(*this);
10122 Visit(BO->getLHS());
10123 }
10124
10125 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010126 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010127 if (Result)
10128 Visit(BO->getRHS());
10129 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000010130 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010131 }
Richard Smithc406cb72013-01-17 01:17:56 +000010132 }
10133
10134 // Only visit the condition, unless we can be sure which subexpression will
10135 // be chosen.
10136 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000010137 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000010138 {
10139 SequencedSubexpression Sequenced(*this);
10140 Visit(CO->getCond());
10141 }
Richard Smithc406cb72013-01-17 01:17:56 +000010142
10143 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010144 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000010145 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010146 else {
Richard Smithd33f5202013-01-17 23:18:09 +000010147 WorkList.push_back(CO->getTrueExpr());
10148 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010149 }
Richard Smithc406cb72013-01-17 01:17:56 +000010150 }
10151
Richard Smithe3dbfe02013-06-30 10:40:20 +000010152 void VisitCallExpr(CallExpr *CE) {
10153 // C++11 [intro.execution]p15:
10154 // When calling a function [...], every value computation and side effect
10155 // associated with any argument expression, or with the postfix expression
10156 // designating the called function, is sequenced before execution of every
10157 // expression or statement in the body of the function [and thus before
10158 // the value computation of its result].
10159 SequencedSubexpression Sequenced(*this);
10160 Base::VisitCallExpr(CE);
10161
10162 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10163 }
10164
Richard Smithc406cb72013-01-17 01:17:56 +000010165 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010166 // This is a call, so all subexpressions are sequenced before the result.
10167 SequencedSubexpression Sequenced(*this);
10168
Richard Smithc406cb72013-01-17 01:17:56 +000010169 if (!CCE->isListInitialization())
10170 return VisitExpr(CCE);
10171
10172 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010173 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010174 SequenceTree::Seq Parent = Region;
10175 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10176 E = CCE->arg_end();
10177 I != E; ++I) {
10178 Region = Tree.allocate(Parent);
10179 Elts.push_back(Region);
10180 Visit(*I);
10181 }
10182
10183 // Forget that the initializers are sequenced.
10184 Region = Parent;
10185 for (unsigned I = 0; I < Elts.size(); ++I)
10186 Tree.merge(Elts[I]);
10187 }
10188
10189 void VisitInitListExpr(InitListExpr *ILE) {
10190 if (!SemaRef.getLangOpts().CPlusPlus11)
10191 return VisitExpr(ILE);
10192
10193 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010194 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010195 SequenceTree::Seq Parent = Region;
10196 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10197 Expr *E = ILE->getInit(I);
10198 if (!E) continue;
10199 Region = Tree.allocate(Parent);
10200 Elts.push_back(Region);
10201 Visit(E);
10202 }
10203
10204 // Forget that the initializers are sequenced.
10205 Region = Parent;
10206 for (unsigned I = 0; I < Elts.size(); ++I)
10207 Tree.merge(Elts[I]);
10208 }
10209};
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010210} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +000010211
10212void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010213 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000010214 WorkList.push_back(E);
10215 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000010216 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000010217 SequenceChecker(*this, Item, WorkList);
10218 }
Richard Smithc406cb72013-01-17 01:17:56 +000010219}
10220
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010221void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10222 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010223 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000010224 if (!E->isInstantiationDependent())
10225 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010226 if (!IsConstexpr && !E->isValueDependent())
10227 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010228 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000010229}
10230
John McCall1f425642010-11-11 03:21:53 +000010231void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10232 FieldDecl *BitField,
10233 Expr *Init) {
10234 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10235}
10236
David Majnemer61a5bbf2015-04-07 22:08:51 +000010237static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10238 SourceLocation Loc) {
10239 if (!PType->isVariablyModifiedType())
10240 return;
10241 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10242 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10243 return;
10244 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000010245 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10246 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10247 return;
10248 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000010249 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10250 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10251 return;
10252 }
10253
10254 const ArrayType *AT = S.Context.getAsArrayType(PType);
10255 if (!AT)
10256 return;
10257
10258 if (AT->getSizeModifier() != ArrayType::Star) {
10259 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10260 return;
10261 }
10262
10263 S.Diag(Loc, diag::err_array_star_in_function_definition);
10264}
10265
Mike Stump0c2ec772010-01-21 03:59:47 +000010266/// CheckParmsForFunctionDef - Check that the parameters of the given
10267/// function are appropriate for the definition of a function. This
10268/// takes care of any checks that cannot be performed on the
10269/// declaration itself, e.g., that the types of each of the function
10270/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000010271bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000010272 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010273 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000010274 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010275 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10276 // function declarator that is part of a function definition of
10277 // that function shall not have incomplete type.
10278 //
10279 // This is also C++ [dcl.fct]p6.
10280 if (!Param->isInvalidDecl() &&
10281 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010282 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010283 Param->setInvalidDecl();
10284 HasInvalidParm = true;
10285 }
10286
10287 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10288 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000010289 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000010290 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000010291 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000010292 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000010293 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000010294
10295 // C99 6.7.5.3p12:
10296 // If the function declarator is not part of a definition of that
10297 // function, parameters may have incomplete type and may use the [*]
10298 // notation in their sequences of declarator specifiers to specify
10299 // variable length array types.
10300 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000010301 // FIXME: This diagnostic should point the '[*]' if source-location
10302 // information is added for it.
10303 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010304
10305 // MSVC destroys objects passed by value in the callee. Therefore a
10306 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010307 // object's destructor. However, we don't perform any direct access check
10308 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +000010309 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10310 .getCXXABI()
10311 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +000010312 if (!Param->isInvalidDecl()) {
10313 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10314 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10315 if (!ClassDecl->isInvalidDecl() &&
10316 !ClassDecl->hasIrrelevantDestructor() &&
10317 !ClassDecl->isDependentContext()) {
10318 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10319 MarkFunctionReferenced(Param->getLocation(), Destructor);
10320 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10321 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010322 }
10323 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010324 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010325
10326 // Parameters with the pass_object_size attribute only need to be marked
10327 // constant at function definitions. Because we lack information about
10328 // whether we're on a declaration or definition when we're instantiating the
10329 // attribute, we need to check for constness here.
10330 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10331 if (!Param->getType().isConstQualified())
10332 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10333 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000010334 }
10335
10336 return HasInvalidParm;
10337}
John McCall2b5c1b22010-08-12 21:44:57 +000010338
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010339/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10340/// or MemberExpr.
10341static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10342 ASTContext &Context) {
10343 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10344 return Context.getDeclAlign(DRE->getDecl());
10345
10346 if (const auto *ME = dyn_cast<MemberExpr>(E))
10347 return Context.getDeclAlign(ME->getMemberDecl());
10348
10349 return TypeAlign;
10350}
10351
John McCall2b5c1b22010-08-12 21:44:57 +000010352/// CheckCastAlign - Implements -Wcast-align, which warns when a
10353/// pointer cast increases the alignment requirements.
10354void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10355 // This is actually a lot of work to potentially be doing on every
10356 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010357 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000010358 return;
10359
10360 // Ignore dependent types.
10361 if (T->isDependentType() || Op->getType()->isDependentType())
10362 return;
10363
10364 // Require that the destination be a pointer type.
10365 const PointerType *DestPtr = T->getAs<PointerType>();
10366 if (!DestPtr) return;
10367
10368 // If the destination has alignment 1, we're done.
10369 QualType DestPointee = DestPtr->getPointeeType();
10370 if (DestPointee->isIncompleteType()) return;
10371 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10372 if (DestAlign.isOne()) return;
10373
10374 // Require that the source be a pointer type.
10375 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10376 if (!SrcPtr) return;
10377 QualType SrcPointee = SrcPtr->getPointeeType();
10378
10379 // Whitelist casts from cv void*. We already implicitly
10380 // whitelisted casts to cv void*, since they have alignment 1.
10381 // Also whitelist casts involving incomplete types, which implicitly
10382 // includes 'void'.
10383 if (SrcPointee->isIncompleteType()) return;
10384
10385 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010386
10387 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10388 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10389 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10390 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10391 if (UO->getOpcode() == UO_AddrOf)
10392 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10393 }
10394
John McCall2b5c1b22010-08-12 21:44:57 +000010395 if (SrcAlign >= DestAlign) return;
10396
10397 Diag(TRange.getBegin(), diag::warn_cast_align)
10398 << Op->getType() << T
10399 << static_cast<unsigned>(SrcAlign.getQuantity())
10400 << static_cast<unsigned>(DestAlign.getQuantity())
10401 << TRange << Op->getSourceRange();
10402}
10403
Chandler Carruth28389f02011-08-05 09:10:50 +000010404/// \brief Check whether this array fits the idiom of a size-one tail padded
10405/// array member of a struct.
10406///
10407/// We avoid emitting out-of-bounds access warnings for such arrays as they are
10408/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000010409static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000010410 const NamedDecl *ND) {
10411 if (Size != 1 || !ND) return false;
10412
10413 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10414 if (!FD) return false;
10415
10416 // Don't consider sizes resulting from macro expansions or template argument
10417 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000010418
10419 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010420 while (TInfo) {
10421 TypeLoc TL = TInfo->getTypeLoc();
10422 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000010423 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10424 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010425 TInfo = TDL->getTypeSourceInfo();
10426 continue;
10427 }
David Blaikie6adc78e2013-02-18 22:06:02 +000010428 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10429 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000010430 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10431 return false;
10432 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010433 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000010434 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010435
10436 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000010437 if (!RD) return false;
10438 if (RD->isUnion()) return false;
10439 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10440 if (!CRD->isStandardLayout()) return false;
10441 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010442
Benjamin Kramer8c543672011-08-06 03:04:42 +000010443 // See if this is the last field decl in the record.
10444 const Decl *D = FD;
10445 while ((D = D->getNextDeclInContext()))
10446 if (isa<FieldDecl>(D))
10447 return false;
10448 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000010449}
10450
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010451void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010452 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000010453 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010454 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010455 if (IndexExpr->isValueDependent())
10456 return;
10457
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010458 const Type *EffectiveType =
10459 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010460 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010461 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010462 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010463 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000010464 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000010465
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010466 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000010467 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000010468 return;
Richard Smith13f67182011-12-16 19:31:14 +000010469 if (IndexNegated)
10470 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000010471
Craig Topperc3ec1492014-05-26 06:22:03 +000010472 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000010473 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10474 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +000010475 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +000010476 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +000010477
Ted Kremeneke4b316c2011-02-23 23:06:04 +000010478 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010479 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000010480 if (!size.isStrictlyPositive())
10481 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010482
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010483 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000010484 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010485 // Make sure we're comparing apples to apples when comparing index to size
10486 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10487 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000010488 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000010489 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010490 if (ptrarith_typesize != array_typesize) {
10491 // There's a cast to a different size type involved
10492 uint64_t ratio = array_typesize / ptrarith_typesize;
10493 // TODO: Be smarter about handling cases where array_typesize is not a
10494 // multiple of ptrarith_typesize
10495 if (ptrarith_typesize * ratio == array_typesize)
10496 size *= llvm::APInt(size.getBitWidth(), ratio);
10497 }
10498 }
10499
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010500 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010501 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010502 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010503 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010504
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010505 // For array subscripting the index must be less than size, but for pointer
10506 // arithmetic also allow the index (offset) to be equal to size since
10507 // computing the next address after the end of the array is legal and
10508 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010509 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000010510 return;
10511
10512 // Also don't warn for arrays of size 1 which are members of some
10513 // structure. These are often used to approximate flexible arrays in C89
10514 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010515 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000010516 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010517
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010518 // Suppress the warning if the subscript expression (as identified by the
10519 // ']' location) and the index expression are both from macro expansions
10520 // within a system header.
10521 if (ASE) {
10522 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10523 ASE->getRBracketLoc());
10524 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10525 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10526 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000010527 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010528 return;
10529 }
10530 }
10531
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010532 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010533 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010534 DiagID = diag::warn_array_index_exceeds_bounds;
10535
10536 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10537 PDiag(DiagID) << index.toString(10, true)
10538 << size.toString(10, true)
10539 << (unsigned)size.getLimitedValue(~0U)
10540 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010541 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010542 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010543 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010544 DiagID = diag::warn_ptr_arith_precedes_bounds;
10545 if (index.isNegative()) index = -index;
10546 }
10547
10548 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10549 PDiag(DiagID) << index.toString(10, true)
10550 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000010551 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000010552
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000010553 if (!ND) {
10554 // Try harder to find a NamedDecl to point at in the note.
10555 while (const ArraySubscriptExpr *ASE =
10556 dyn_cast<ArraySubscriptExpr>(BaseExpr))
10557 BaseExpr = ASE->getBase()->IgnoreParenCasts();
10558 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10559 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10560 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10561 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10562 }
10563
Chandler Carruth1af88f12011-02-17 21:10:52 +000010564 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010565 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10566 PDiag(diag::note_array_index_out_of_bounds)
10567 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000010568}
10569
Ted Kremenekdf26df72011-03-01 18:41:00 +000010570void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010571 int AllowOnePastEnd = 0;
10572 while (expr) {
10573 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000010574 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010575 case Stmt::ArraySubscriptExprClass: {
10576 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010577 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010578 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +000010579 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010580 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010581 case Stmt::OMPArraySectionExprClass: {
10582 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10583 if (ASE->getLowerBound())
10584 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10585 /*ASE=*/nullptr, AllowOnePastEnd > 0);
10586 return;
10587 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010588 case Stmt::UnaryOperatorClass: {
10589 // Only unwrap the * and & unary operators
10590 const UnaryOperator *UO = cast<UnaryOperator>(expr);
10591 expr = UO->getSubExpr();
10592 switch (UO->getOpcode()) {
10593 case UO_AddrOf:
10594 AllowOnePastEnd++;
10595 break;
10596 case UO_Deref:
10597 AllowOnePastEnd--;
10598 break;
10599 default:
10600 return;
10601 }
10602 break;
10603 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010604 case Stmt::ConditionalOperatorClass: {
10605 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10606 if (const Expr *lhs = cond->getLHS())
10607 CheckArrayAccess(lhs);
10608 if (const Expr *rhs = cond->getRHS())
10609 CheckArrayAccess(rhs);
10610 return;
10611 }
10612 default:
10613 return;
10614 }
Peter Collingbourne91147592011-04-15 00:35:48 +000010615 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010616}
John McCall31168b02011-06-15 23:02:42 +000010617
10618//===--- CHECK: Objective-C retain cycles ----------------------------------//
10619
10620namespace {
10621 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +000010622 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +000010623 VarDecl *Variable;
10624 SourceRange Range;
10625 SourceLocation Loc;
10626 bool Indirect;
10627
10628 void setLocsFrom(Expr *e) {
10629 Loc = e->getExprLoc();
10630 Range = e->getSourceRange();
10631 }
10632 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010633} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010634
10635/// Consider whether capturing the given variable can possibly lead to
10636/// a retain cycle.
10637static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010638 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000010639 // lifetime. In MRR, it's captured strongly if the variable is
10640 // __block and has an appropriate type.
10641 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10642 return false;
10643
10644 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010645 if (ref)
10646 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000010647 return true;
10648}
10649
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010650static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000010651 while (true) {
10652 e = e->IgnoreParens();
10653 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10654 switch (cast->getCastKind()) {
10655 case CK_BitCast:
10656 case CK_LValueBitCast:
10657 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000010658 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000010659 e = cast->getSubExpr();
10660 continue;
10661
John McCall31168b02011-06-15 23:02:42 +000010662 default:
10663 return false;
10664 }
10665 }
10666
10667 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10668 ObjCIvarDecl *ivar = ref->getDecl();
10669 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10670 return false;
10671
10672 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010673 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000010674 return false;
10675
10676 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10677 owner.Indirect = true;
10678 return true;
10679 }
10680
10681 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10682 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10683 if (!var) return false;
10684 return considerVariable(var, ref, owner);
10685 }
10686
John McCall31168b02011-06-15 23:02:42 +000010687 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10688 if (member->isArrow()) return false;
10689
10690 // Don't count this as an indirect ownership.
10691 e = member->getBase();
10692 continue;
10693 }
10694
John McCallfe96e0b2011-11-06 09:01:30 +000010695 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10696 // Only pay attention to pseudo-objects on property references.
10697 ObjCPropertyRefExpr *pre
10698 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10699 ->IgnoreParens());
10700 if (!pre) return false;
10701 if (pre->isImplicitProperty()) return false;
10702 ObjCPropertyDecl *property = pre->getExplicitProperty();
10703 if (!property->isRetaining() &&
10704 !(property->getPropertyIvarDecl() &&
10705 property->getPropertyIvarDecl()->getType()
10706 .getObjCLifetime() == Qualifiers::OCL_Strong))
10707 return false;
10708
10709 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010710 if (pre->isSuperReceiver()) {
10711 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10712 if (!owner.Variable)
10713 return false;
10714 owner.Loc = pre->getLocation();
10715 owner.Range = pre->getSourceRange();
10716 return true;
10717 }
John McCallfe96e0b2011-11-06 09:01:30 +000010718 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10719 ->getSourceExpr());
10720 continue;
10721 }
10722
John McCall31168b02011-06-15 23:02:42 +000010723 // Array ivars?
10724
10725 return false;
10726 }
10727}
10728
10729namespace {
10730 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10731 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10732 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010733 Context(Context), Variable(variable), Capturer(nullptr),
10734 VarWillBeReased(false) {}
10735 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000010736 VarDecl *Variable;
10737 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010738 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +000010739
10740 void VisitDeclRefExpr(DeclRefExpr *ref) {
10741 if (ref->getDecl() == Variable && !Capturer)
10742 Capturer = ref;
10743 }
10744
John McCall31168b02011-06-15 23:02:42 +000010745 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10746 if (Capturer) return;
10747 Visit(ref->getBase());
10748 if (Capturer && ref->isFreeIvar())
10749 Capturer = ref;
10750 }
10751
10752 void VisitBlockExpr(BlockExpr *block) {
10753 // Look inside nested blocks
10754 if (block->getBlockDecl()->capturesVariable(Variable))
10755 Visit(block->getBlockDecl()->getBody());
10756 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000010757
10758 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
10759 if (Capturer) return;
10760 if (OVE->getSourceExpr())
10761 Visit(OVE->getSourceExpr());
10762 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010763 void VisitBinaryOperator(BinaryOperator *BinOp) {
10764 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
10765 return;
10766 Expr *LHS = BinOp->getLHS();
10767 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
10768 if (DRE->getDecl() != Variable)
10769 return;
10770 if (Expr *RHS = BinOp->getRHS()) {
10771 RHS = RHS->IgnoreParenCasts();
10772 llvm::APSInt Value;
10773 VarWillBeReased =
10774 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
10775 }
10776 }
10777 }
John McCall31168b02011-06-15 23:02:42 +000010778 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010779} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010780
10781/// Check whether the given argument is a block which captures a
10782/// variable.
10783static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
10784 assert(owner.Variable && owner.Loc.isValid());
10785
10786 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000010787
10788 // Look through [^{...} copy] and Block_copy(^{...}).
10789 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
10790 Selector Cmd = ME->getSelector();
10791 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
10792 e = ME->getInstanceReceiver();
10793 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000010794 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000010795 e = e->IgnoreParenCasts();
10796 }
10797 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
10798 if (CE->getNumArgs() == 1) {
10799 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000010800 if (Fn) {
10801 const IdentifierInfo *FnI = Fn->getIdentifier();
10802 if (FnI && FnI->isStr("_Block_copy")) {
10803 e = CE->getArg(0)->IgnoreParenCasts();
10804 }
10805 }
Jordan Rose67e887c2012-09-17 17:54:30 +000010806 }
10807 }
10808
John McCall31168b02011-06-15 23:02:42 +000010809 BlockExpr *block = dyn_cast<BlockExpr>(e);
10810 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000010811 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000010812
10813 FindCaptureVisitor visitor(S.Context, owner.Variable);
10814 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010815 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000010816}
10817
10818static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10819 RetainCycleOwner &owner) {
10820 assert(capturer);
10821 assert(owner.Variable && owner.Loc.isValid());
10822
10823 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10824 << owner.Variable << capturer->getSourceRange();
10825 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10826 << owner.Indirect << owner.Range;
10827}
10828
10829/// Check for a keyword selector that starts with the word 'add' or
10830/// 'set'.
10831static bool isSetterLikeSelector(Selector sel) {
10832 if (sel.isUnarySelector()) return false;
10833
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010834 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000010835 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010836 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000010837 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010838 else if (str.startswith("add")) {
10839 // Specially whitelist 'addOperationWithBlock:'.
10840 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
10841 return false;
10842 str = str.substr(3);
10843 }
John McCall31168b02011-06-15 23:02:42 +000010844 else
10845 return false;
10846
10847 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000010848 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000010849}
10850
Benjamin Kramer3a743452015-03-09 15:03:32 +000010851static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
10852 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010853 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
10854 Message->getReceiverInterface(),
10855 NSAPI::ClassId_NSMutableArray);
10856 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010857 return None;
10858 }
10859
10860 Selector Sel = Message->getSelector();
10861
10862 Optional<NSAPI::NSArrayMethodKind> MKOpt =
10863 S.NSAPIObj->getNSArrayMethodKind(Sel);
10864 if (!MKOpt) {
10865 return None;
10866 }
10867
10868 NSAPI::NSArrayMethodKind MK = *MKOpt;
10869
10870 switch (MK) {
10871 case NSAPI::NSMutableArr_addObject:
10872 case NSAPI::NSMutableArr_insertObjectAtIndex:
10873 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
10874 return 0;
10875 case NSAPI::NSMutableArr_replaceObjectAtIndex:
10876 return 1;
10877
10878 default:
10879 return None;
10880 }
10881
10882 return None;
10883}
10884
10885static
10886Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10887 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010888 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10889 Message->getReceiverInterface(),
10890 NSAPI::ClassId_NSMutableDictionary);
10891 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010892 return None;
10893 }
10894
10895 Selector Sel = Message->getSelector();
10896
10897 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10898 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10899 if (!MKOpt) {
10900 return None;
10901 }
10902
10903 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10904
10905 switch (MK) {
10906 case NSAPI::NSMutableDict_setObjectForKey:
10907 case NSAPI::NSMutableDict_setValueForKey:
10908 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10909 return 0;
10910
10911 default:
10912 return None;
10913 }
10914
10915 return None;
10916}
10917
10918static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010919 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10920 Message->getReceiverInterface(),
10921 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000010922
Alex Denisov5dfac812015-08-06 04:51:14 +000010923 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10924 Message->getReceiverInterface(),
10925 NSAPI::ClassId_NSMutableOrderedSet);
10926 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010927 return None;
10928 }
10929
10930 Selector Sel = Message->getSelector();
10931
10932 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10933 if (!MKOpt) {
10934 return None;
10935 }
10936
10937 NSAPI::NSSetMethodKind MK = *MKOpt;
10938
10939 switch (MK) {
10940 case NSAPI::NSMutableSet_addObject:
10941 case NSAPI::NSOrderedSet_setObjectAtIndex:
10942 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10943 case NSAPI::NSOrderedSet_insertObjectAtIndex:
10944 return 0;
10945 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10946 return 1;
10947 }
10948
10949 return None;
10950}
10951
10952void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10953 if (!Message->isInstanceMessage()) {
10954 return;
10955 }
10956
10957 Optional<int> ArgOpt;
10958
10959 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10960 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10961 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10962 return;
10963 }
10964
10965 int ArgIndex = *ArgOpt;
10966
Alex Denisove1d882c2015-03-04 17:55:52 +000010967 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10968 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10969 Arg = OE->getSourceExpr()->IgnoreImpCasts();
10970 }
10971
Alex Denisov5dfac812015-08-06 04:51:14 +000010972 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010973 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010974 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010975 Diag(Message->getSourceRange().getBegin(),
10976 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000010977 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000010978 }
10979 }
Alex Denisov5dfac812015-08-06 04:51:14 +000010980 } else {
10981 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10982
10983 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10984 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10985 }
10986
10987 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10988 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10989 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10990 ValueDecl *Decl = ReceiverRE->getDecl();
10991 Diag(Message->getSourceRange().getBegin(),
10992 diag::warn_objc_circular_container)
10993 << Decl->getName() << Decl->getName();
10994 if (!ArgRE->isObjCSelfExpr()) {
10995 Diag(Decl->getLocation(),
10996 diag::note_objc_circular_container_declared_here)
10997 << Decl->getName();
10998 }
10999 }
11000 }
11001 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11002 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11003 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11004 ObjCIvarDecl *Decl = IvarRE->getDecl();
11005 Diag(Message->getSourceRange().getBegin(),
11006 diag::warn_objc_circular_container)
11007 << Decl->getName() << Decl->getName();
11008 Diag(Decl->getLocation(),
11009 diag::note_objc_circular_container_declared_here)
11010 << Decl->getName();
11011 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011012 }
11013 }
11014 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011015}
11016
John McCall31168b02011-06-15 23:02:42 +000011017/// Check a message send to see if it's likely to cause a retain cycle.
11018void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11019 // Only check instance methods whose selector looks like a setter.
11020 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11021 return;
11022
11023 // Try to find a variable that the receiver is strongly owned by.
11024 RetainCycleOwner owner;
11025 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011026 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000011027 return;
11028 } else {
11029 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11030 owner.Variable = getCurMethodDecl()->getSelfDecl();
11031 owner.Loc = msg->getSuperLoc();
11032 owner.Range = msg->getSuperLoc();
11033 }
11034
11035 // Check whether the receiver is captured by any of the arguments.
11036 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
11037 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
11038 return diagnoseRetainCycle(*this, capturer, owner);
11039}
11040
11041/// Check a property assign to see if it's likely to cause a retain cycle.
11042void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11043 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011044 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000011045 return;
11046
11047 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11048 diagnoseRetainCycle(*this, capturer, owner);
11049}
11050
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011051void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11052 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000011053 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011054 return;
11055
11056 // Because we don't have an expression for the variable, we have to set the
11057 // location explicitly here.
11058 Owner.Loc = Var->getLocation();
11059 Owner.Range = Var->getSourceRange();
11060
11061 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11062 diagnoseRetainCycle(*this, Capturer, Owner);
11063}
11064
Ted Kremenek9304da92012-12-21 08:04:28 +000011065static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11066 Expr *RHS, bool isProperty) {
11067 // Check if RHS is an Objective-C object literal, which also can get
11068 // immediately zapped in a weak reference. Note that we explicitly
11069 // allow ObjCStringLiterals, since those are designed to never really die.
11070 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011071
Ted Kremenek64873352012-12-21 22:46:35 +000011072 // This enum needs to match with the 'select' in
11073 // warn_objc_arc_literal_assign (off-by-1).
11074 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11075 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11076 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011077
11078 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000011079 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000011080 << (isProperty ? 0 : 1)
11081 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011082
11083 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000011084}
11085
Ted Kremenekc1f014a2012-12-21 19:45:30 +000011086static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11087 Qualifiers::ObjCLifetime LT,
11088 Expr *RHS, bool isProperty) {
11089 // Strip off any implicit cast added to get to the one ARC-specific.
11090 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11091 if (cast->getCastKind() == CK_ARCConsumeObject) {
11092 S.Diag(Loc, diag::warn_arc_retained_assign)
11093 << (LT == Qualifiers::OCL_ExplicitNone)
11094 << (isProperty ? 0 : 1)
11095 << RHS->getSourceRange();
11096 return true;
11097 }
11098 RHS = cast->getSubExpr();
11099 }
11100
11101 if (LT == Qualifiers::OCL_Weak &&
11102 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11103 return true;
11104
11105 return false;
11106}
11107
Ted Kremenekb36234d2012-12-21 08:04:20 +000011108bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11109 QualType LHS, Expr *RHS) {
11110 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11111
11112 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11113 return false;
11114
11115 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11116 return true;
11117
11118 return false;
11119}
11120
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011121void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11122 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011123 QualType LHSType;
11124 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011125 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011126 ObjCPropertyRefExpr *PRE
11127 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11128 if (PRE && !PRE->isImplicitProperty()) {
11129 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11130 if (PD)
11131 LHSType = PD->getType();
11132 }
11133
11134 if (LHSType.isNull())
11135 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000011136
11137 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11138
11139 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011140 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000011141 getCurFunction()->markSafeWeakUse(LHS);
11142 }
11143
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011144 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11145 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000011146
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011147 // FIXME. Check for other life times.
11148 if (LT != Qualifiers::OCL_None)
11149 return;
11150
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011151 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011152 if (PRE->isImplicitProperty())
11153 return;
11154 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11155 if (!PD)
11156 return;
11157
Bill Wendling44426052012-12-20 19:22:21 +000011158 unsigned Attributes = PD->getPropertyAttributes();
11159 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011160 // when 'assign' attribute was not explicitly specified
11161 // by user, ignore it and rely on property type itself
11162 // for lifetime info.
11163 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11164 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11165 LHSType->isObjCRetainableType())
11166 return;
11167
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011168 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000011169 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011170 Diag(Loc, diag::warn_arc_retained_property_assign)
11171 << RHS->getSourceRange();
11172 return;
11173 }
11174 RHS = cast->getSubExpr();
11175 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011176 }
Bill Wendling44426052012-12-20 19:22:21 +000011177 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000011178 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11179 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000011180 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011181 }
11182}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011183
11184//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11185
11186namespace {
11187bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11188 SourceLocation StmtLoc,
11189 const NullStmt *Body) {
11190 // Do not warn if the body is a macro that expands to nothing, e.g:
11191 //
11192 // #define CALL(x)
11193 // if (condition)
11194 // CALL(0);
11195 //
11196 if (Body->hasLeadingEmptyMacro())
11197 return false;
11198
11199 // Get line numbers of statement and body.
11200 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000011201 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011202 &StmtLineInvalid);
11203 if (StmtLineInvalid)
11204 return false;
11205
11206 bool BodyLineInvalid;
11207 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11208 &BodyLineInvalid);
11209 if (BodyLineInvalid)
11210 return false;
11211
11212 // Warn if null statement and body are on the same line.
11213 if (StmtLine != BodyLine)
11214 return false;
11215
11216 return true;
11217}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011218} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011219
11220void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11221 const Stmt *Body,
11222 unsigned DiagID) {
11223 // Since this is a syntactic check, don't emit diagnostic for template
11224 // instantiations, this just adds noise.
11225 if (CurrentInstantiationScope)
11226 return;
11227
11228 // The body should be a null statement.
11229 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11230 if (!NBody)
11231 return;
11232
11233 // Do the usual checks.
11234 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11235 return;
11236
11237 Diag(NBody->getSemiLoc(), DiagID);
11238 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11239}
11240
11241void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11242 const Stmt *PossibleBody) {
11243 assert(!CurrentInstantiationScope); // Ensured by caller
11244
11245 SourceLocation StmtLoc;
11246 const Stmt *Body;
11247 unsigned DiagID;
11248 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11249 StmtLoc = FS->getRParenLoc();
11250 Body = FS->getBody();
11251 DiagID = diag::warn_empty_for_body;
11252 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11253 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11254 Body = WS->getBody();
11255 DiagID = diag::warn_empty_while_body;
11256 } else
11257 return; // Neither `for' nor `while'.
11258
11259 // The body should be a null statement.
11260 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11261 if (!NBody)
11262 return;
11263
11264 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011265 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011266 return;
11267
11268 // Do the usual checks.
11269 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11270 return;
11271
11272 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11273 // noise level low, emit diagnostics only if for/while is followed by a
11274 // CompoundStmt, e.g.:
11275 // for (int i = 0; i < n; i++);
11276 // {
11277 // a(i);
11278 // }
11279 // or if for/while is followed by a statement with more indentation
11280 // than for/while itself:
11281 // for (int i = 0; i < n; i++);
11282 // a(i);
11283 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11284 if (!ProbableTypo) {
11285 bool BodyColInvalid;
11286 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11287 PossibleBody->getLocStart(),
11288 &BodyColInvalid);
11289 if (BodyColInvalid)
11290 return;
11291
11292 bool StmtColInvalid;
11293 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11294 S->getLocStart(),
11295 &StmtColInvalid);
11296 if (StmtColInvalid)
11297 return;
11298
11299 if (BodyCol > StmtCol)
11300 ProbableTypo = true;
11301 }
11302
11303 if (ProbableTypo) {
11304 Diag(NBody->getSemiLoc(), DiagID);
11305 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11306 }
11307}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011308
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011309//===--- CHECK: Warn on self move with std::move. -------------------------===//
11310
11311/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11312void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11313 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011314 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11315 return;
11316
Richard Smith51ec0cf2017-02-21 01:17:38 +000011317 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011318 return;
11319
11320 // Strip parens and casts away.
11321 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11322 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11323
11324 // Check for a call expression
11325 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11326 if (!CE || CE->getNumArgs() != 1)
11327 return;
11328
11329 // Check for a call to std::move
11330 const FunctionDecl *FD = CE->getDirectCallee();
11331 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11332 !FD->getIdentifier()->isStr("move"))
11333 return;
11334
11335 // Get argument from std::move
11336 RHSExpr = CE->getArg(0);
11337
11338 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11339 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11340
11341 // Two DeclRefExpr's, check that the decls are the same.
11342 if (LHSDeclRef && RHSDeclRef) {
11343 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11344 return;
11345 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11346 RHSDeclRef->getDecl()->getCanonicalDecl())
11347 return;
11348
11349 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11350 << LHSExpr->getSourceRange()
11351 << RHSExpr->getSourceRange();
11352 return;
11353 }
11354
11355 // Member variables require a different approach to check for self moves.
11356 // MemberExpr's are the same if every nested MemberExpr refers to the same
11357 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11358 // the base Expr's are CXXThisExpr's.
11359 const Expr *LHSBase = LHSExpr;
11360 const Expr *RHSBase = RHSExpr;
11361 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11362 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11363 if (!LHSME || !RHSME)
11364 return;
11365
11366 while (LHSME && RHSME) {
11367 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11368 RHSME->getMemberDecl()->getCanonicalDecl())
11369 return;
11370
11371 LHSBase = LHSME->getBase();
11372 RHSBase = RHSME->getBase();
11373 LHSME = dyn_cast<MemberExpr>(LHSBase);
11374 RHSME = dyn_cast<MemberExpr>(RHSBase);
11375 }
11376
11377 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11378 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11379 if (LHSDeclRef && RHSDeclRef) {
11380 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11381 return;
11382 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11383 RHSDeclRef->getDecl()->getCanonicalDecl())
11384 return;
11385
11386 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11387 << LHSExpr->getSourceRange()
11388 << RHSExpr->getSourceRange();
11389 return;
11390 }
11391
11392 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11393 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11394 << LHSExpr->getSourceRange()
11395 << RHSExpr->getSourceRange();
11396}
11397
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011398//===--- Layout compatibility ----------------------------------------------//
11399
11400namespace {
11401
11402bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11403
11404/// \brief Check if two enumeration types are layout-compatible.
11405bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11406 // C++11 [dcl.enum] p8:
11407 // Two enumeration types are layout-compatible if they have the same
11408 // underlying type.
11409 return ED1->isComplete() && ED2->isComplete() &&
11410 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11411}
11412
11413/// \brief Check if two fields are layout-compatible.
11414bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11415 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11416 return false;
11417
11418 if (Field1->isBitField() != Field2->isBitField())
11419 return false;
11420
11421 if (Field1->isBitField()) {
11422 // Make sure that the bit-fields are the same length.
11423 unsigned Bits1 = Field1->getBitWidthValue(C);
11424 unsigned Bits2 = Field2->getBitWidthValue(C);
11425
11426 if (Bits1 != Bits2)
11427 return false;
11428 }
11429
11430 return true;
11431}
11432
11433/// \brief Check if two standard-layout structs are layout-compatible.
11434/// (C++11 [class.mem] p17)
11435bool isLayoutCompatibleStruct(ASTContext &C,
11436 RecordDecl *RD1,
11437 RecordDecl *RD2) {
11438 // If both records are C++ classes, check that base classes match.
11439 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11440 // If one of records is a CXXRecordDecl we are in C++ mode,
11441 // thus the other one is a CXXRecordDecl, too.
11442 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11443 // Check number of base classes.
11444 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11445 return false;
11446
11447 // Check the base classes.
11448 for (CXXRecordDecl::base_class_const_iterator
11449 Base1 = D1CXX->bases_begin(),
11450 BaseEnd1 = D1CXX->bases_end(),
11451 Base2 = D2CXX->bases_begin();
11452 Base1 != BaseEnd1;
11453 ++Base1, ++Base2) {
11454 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11455 return false;
11456 }
11457 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11458 // If only RD2 is a C++ class, it should have zero base classes.
11459 if (D2CXX->getNumBases() > 0)
11460 return false;
11461 }
11462
11463 // Check the fields.
11464 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11465 Field2End = RD2->field_end(),
11466 Field1 = RD1->field_begin(),
11467 Field1End = RD1->field_end();
11468 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11469 if (!isLayoutCompatible(C, *Field1, *Field2))
11470 return false;
11471 }
11472 if (Field1 != Field1End || Field2 != Field2End)
11473 return false;
11474
11475 return true;
11476}
11477
11478/// \brief Check if two standard-layout unions are layout-compatible.
11479/// (C++11 [class.mem] p18)
11480bool isLayoutCompatibleUnion(ASTContext &C,
11481 RecordDecl *RD1,
11482 RecordDecl *RD2) {
11483 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011484 for (auto *Field2 : RD2->fields())
11485 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011486
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011487 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011488 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11489 I = UnmatchedFields.begin(),
11490 E = UnmatchedFields.end();
11491
11492 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011493 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011494 bool Result = UnmatchedFields.erase(*I);
11495 (void) Result;
11496 assert(Result);
11497 break;
11498 }
11499 }
11500 if (I == E)
11501 return false;
11502 }
11503
11504 return UnmatchedFields.empty();
11505}
11506
11507bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11508 if (RD1->isUnion() != RD2->isUnion())
11509 return false;
11510
11511 if (RD1->isUnion())
11512 return isLayoutCompatibleUnion(C, RD1, RD2);
11513 else
11514 return isLayoutCompatibleStruct(C, RD1, RD2);
11515}
11516
11517/// \brief Check if two types are layout-compatible in C++11 sense.
11518bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11519 if (T1.isNull() || T2.isNull())
11520 return false;
11521
11522 // C++11 [basic.types] p11:
11523 // If two types T1 and T2 are the same type, then T1 and T2 are
11524 // layout-compatible types.
11525 if (C.hasSameType(T1, T2))
11526 return true;
11527
11528 T1 = T1.getCanonicalType().getUnqualifiedType();
11529 T2 = T2.getCanonicalType().getUnqualifiedType();
11530
11531 const Type::TypeClass TC1 = T1->getTypeClass();
11532 const Type::TypeClass TC2 = T2->getTypeClass();
11533
11534 if (TC1 != TC2)
11535 return false;
11536
11537 if (TC1 == Type::Enum) {
11538 return isLayoutCompatible(C,
11539 cast<EnumType>(T1)->getDecl(),
11540 cast<EnumType>(T2)->getDecl());
11541 } else if (TC1 == Type::Record) {
11542 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11543 return false;
11544
11545 return isLayoutCompatible(C,
11546 cast<RecordType>(T1)->getDecl(),
11547 cast<RecordType>(T2)->getDecl());
11548 }
11549
11550 return false;
11551}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011552} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011553
11554//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11555
11556namespace {
11557/// \brief Given a type tag expression find the type tag itself.
11558///
11559/// \param TypeExpr Type tag expression, as it appears in user's code.
11560///
11561/// \param VD Declaration of an identifier that appears in a type tag.
11562///
11563/// \param MagicValue Type tag magic value.
11564bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11565 const ValueDecl **VD, uint64_t *MagicValue) {
11566 while(true) {
11567 if (!TypeExpr)
11568 return false;
11569
11570 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11571
11572 switch (TypeExpr->getStmtClass()) {
11573 case Stmt::UnaryOperatorClass: {
11574 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11575 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11576 TypeExpr = UO->getSubExpr();
11577 continue;
11578 }
11579 return false;
11580 }
11581
11582 case Stmt::DeclRefExprClass: {
11583 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11584 *VD = DRE->getDecl();
11585 return true;
11586 }
11587
11588 case Stmt::IntegerLiteralClass: {
11589 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11590 llvm::APInt MagicValueAPInt = IL->getValue();
11591 if (MagicValueAPInt.getActiveBits() <= 64) {
11592 *MagicValue = MagicValueAPInt.getZExtValue();
11593 return true;
11594 } else
11595 return false;
11596 }
11597
11598 case Stmt::BinaryConditionalOperatorClass:
11599 case Stmt::ConditionalOperatorClass: {
11600 const AbstractConditionalOperator *ACO =
11601 cast<AbstractConditionalOperator>(TypeExpr);
11602 bool Result;
11603 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11604 if (Result)
11605 TypeExpr = ACO->getTrueExpr();
11606 else
11607 TypeExpr = ACO->getFalseExpr();
11608 continue;
11609 }
11610 return false;
11611 }
11612
11613 case Stmt::BinaryOperatorClass: {
11614 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11615 if (BO->getOpcode() == BO_Comma) {
11616 TypeExpr = BO->getRHS();
11617 continue;
11618 }
11619 return false;
11620 }
11621
11622 default:
11623 return false;
11624 }
11625 }
11626}
11627
11628/// \brief Retrieve the C type corresponding to type tag TypeExpr.
11629///
11630/// \param TypeExpr Expression that specifies a type tag.
11631///
11632/// \param MagicValues Registered magic values.
11633///
11634/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11635/// kind.
11636///
11637/// \param TypeInfo Information about the corresponding C type.
11638///
11639/// \returns true if the corresponding C type was found.
11640bool GetMatchingCType(
11641 const IdentifierInfo *ArgumentKind,
11642 const Expr *TypeExpr, const ASTContext &Ctx,
11643 const llvm::DenseMap<Sema::TypeTagMagicValue,
11644 Sema::TypeTagData> *MagicValues,
11645 bool &FoundWrongKind,
11646 Sema::TypeTagData &TypeInfo) {
11647 FoundWrongKind = false;
11648
11649 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000011650 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011651
11652 uint64_t MagicValue;
11653
11654 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11655 return false;
11656
11657 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000011658 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011659 if (I->getArgumentKind() != ArgumentKind) {
11660 FoundWrongKind = true;
11661 return false;
11662 }
11663 TypeInfo.Type = I->getMatchingCType();
11664 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11665 TypeInfo.MustBeNull = I->getMustBeNull();
11666 return true;
11667 }
11668 return false;
11669 }
11670
11671 if (!MagicValues)
11672 return false;
11673
11674 llvm::DenseMap<Sema::TypeTagMagicValue,
11675 Sema::TypeTagData>::const_iterator I =
11676 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11677 if (I == MagicValues->end())
11678 return false;
11679
11680 TypeInfo = I->second;
11681 return true;
11682}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011683} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011684
11685void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11686 uint64_t MagicValue, QualType Type,
11687 bool LayoutCompatible,
11688 bool MustBeNull) {
11689 if (!TypeTagForDatatypeMagicValues)
11690 TypeTagForDatatypeMagicValues.reset(
11691 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11692
11693 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11694 (*TypeTagForDatatypeMagicValues)[Magic] =
11695 TypeTagData(Type, LayoutCompatible, MustBeNull);
11696}
11697
11698namespace {
11699bool IsSameCharType(QualType T1, QualType T2) {
11700 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11701 if (!BT1)
11702 return false;
11703
11704 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11705 if (!BT2)
11706 return false;
11707
11708 BuiltinType::Kind T1Kind = BT1->getKind();
11709 BuiltinType::Kind T2Kind = BT2->getKind();
11710
11711 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
11712 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
11713 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11714 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11715}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011716} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011717
11718void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11719 const Expr * const *ExprArgs) {
11720 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11721 bool IsPointerAttr = Attr->getIsPointer();
11722
11723 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11724 bool FoundWrongKind;
11725 TypeTagData TypeInfo;
11726 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11727 TypeTagForDatatypeMagicValues.get(),
11728 FoundWrongKind, TypeInfo)) {
11729 if (FoundWrongKind)
11730 Diag(TypeTagExpr->getExprLoc(),
11731 diag::warn_type_tag_for_datatype_wrong_kind)
11732 << TypeTagExpr->getSourceRange();
11733 return;
11734 }
11735
11736 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11737 if (IsPointerAttr) {
11738 // Skip implicit cast of pointer to `void *' (as a function argument).
11739 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000011740 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000011741 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011742 ArgumentExpr = ICE->getSubExpr();
11743 }
11744 QualType ArgumentType = ArgumentExpr->getType();
11745
11746 // Passing a `void*' pointer shouldn't trigger a warning.
11747 if (IsPointerAttr && ArgumentType->isVoidPointerType())
11748 return;
11749
11750 if (TypeInfo.MustBeNull) {
11751 // Type tag with matching void type requires a null pointer.
11752 if (!ArgumentExpr->isNullPointerConstant(Context,
11753 Expr::NPC_ValueDependentIsNotNull)) {
11754 Diag(ArgumentExpr->getExprLoc(),
11755 diag::warn_type_safety_null_pointer_required)
11756 << ArgumentKind->getName()
11757 << ArgumentExpr->getSourceRange()
11758 << TypeTagExpr->getSourceRange();
11759 }
11760 return;
11761 }
11762
11763 QualType RequiredType = TypeInfo.Type;
11764 if (IsPointerAttr)
11765 RequiredType = Context.getPointerType(RequiredType);
11766
11767 bool mismatch = false;
11768 if (!TypeInfo.LayoutCompatible) {
11769 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
11770
11771 // C++11 [basic.fundamental] p1:
11772 // Plain char, signed char, and unsigned char are three distinct types.
11773 //
11774 // But we treat plain `char' as equivalent to `signed char' or `unsigned
11775 // char' depending on the current char signedness mode.
11776 if (mismatch)
11777 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
11778 RequiredType->getPointeeType())) ||
11779 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
11780 mismatch = false;
11781 } else
11782 if (IsPointerAttr)
11783 mismatch = !isLayoutCompatible(Context,
11784 ArgumentType->getPointeeType(),
11785 RequiredType->getPointeeType());
11786 else
11787 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
11788
11789 if (mismatch)
11790 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000011791 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011792 << TypeInfo.LayoutCompatible << RequiredType
11793 << ArgumentExpr->getSourceRange()
11794 << TypeTagExpr->getSourceRange();
11795}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011796
11797void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11798 CharUnits Alignment) {
11799 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
11800}
11801
11802void Sema::DiagnoseMisalignedMembers() {
11803 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000011804 const NamedDecl *ND = m.RD;
11805 if (ND->getName().empty()) {
11806 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
11807 ND = TD;
11808 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011809 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000011810 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011811 }
11812 MisalignedMembers.clear();
11813}
11814
11815void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011816 E = E->IgnoreParens();
11817 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011818 return;
11819 if (isa<UnaryOperator>(E) &&
11820 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
11821 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11822 if (isa<MemberExpr>(Op)) {
11823 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
11824 MisalignedMember(Op));
11825 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011826 (T->isIntegerType() ||
11827 (T->isPointerType() &&
11828 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011829 MisalignedMembers.erase(MA);
11830 }
11831 }
11832}
11833
11834void Sema::RefersToMemberWithReducedAlignment(
11835 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000011836 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
11837 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011838 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011839 if (!ME)
11840 return;
11841
11842 // For a chain of MemberExpr like "a.b.c.d" this list
11843 // will keep FieldDecl's like [d, c, b].
11844 SmallVector<FieldDecl *, 4> ReverseMemberChain;
11845 const MemberExpr *TopME = nullptr;
11846 bool AnyIsPacked = false;
11847 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011848 QualType BaseType = ME->getBase()->getType();
11849 if (ME->isArrow())
11850 BaseType = BaseType->getPointeeType();
11851 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
11852
11853 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011854 auto *FD = dyn_cast<FieldDecl>(MD);
11855 // We do not care about non-data members.
11856 if (!FD || FD->isInvalidDecl())
11857 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011858
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011859 AnyIsPacked =
11860 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
11861 ReverseMemberChain.push_back(FD);
11862
11863 TopME = ME;
11864 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
11865 } while (ME);
11866 assert(TopME && "We did not compute a topmost MemberExpr!");
11867
11868 // Not the scope of this diagnostic.
11869 if (!AnyIsPacked)
11870 return;
11871
11872 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
11873 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
11874 // TODO: The innermost base of the member expression may be too complicated.
11875 // For now, just disregard these cases. This is left for future
11876 // improvement.
11877 if (!DRE && !isa<CXXThisExpr>(TopBase))
11878 return;
11879
11880 // Alignment expected by the whole expression.
11881 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
11882
11883 // No need to do anything else with this case.
11884 if (ExpectedAlignment.isOne())
11885 return;
11886
11887 // Synthesize offset of the whole access.
11888 CharUnits Offset;
11889 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
11890 I++) {
11891 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
11892 }
11893
11894 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
11895 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
11896 ReverseMemberChain.back()->getParent()->getTypeForDecl());
11897
11898 // The base expression of the innermost MemberExpr may give
11899 // stronger guarantees than the class containing the member.
11900 if (DRE && !TopME->isArrow()) {
11901 const ValueDecl *VD = DRE->getDecl();
11902 if (!VD->getType()->isReferenceType())
11903 CompleteObjectAlignment =
11904 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
11905 }
11906
11907 // Check if the synthesized offset fulfills the alignment.
11908 if (Offset % ExpectedAlignment != 0 ||
11909 // It may fulfill the offset it but the effective alignment may still be
11910 // lower than the expected expression alignment.
11911 CompleteObjectAlignment < ExpectedAlignment) {
11912 // If this happens, we want to determine a sensible culprit of this.
11913 // Intuitively, watching the chain of member expressions from right to
11914 // left, we start with the required alignment (as required by the field
11915 // type) but some packed attribute in that chain has reduced the alignment.
11916 // It may happen that another packed structure increases it again. But if
11917 // we are here such increase has not been enough. So pointing the first
11918 // FieldDecl that either is packed or else its RecordDecl is,
11919 // seems reasonable.
11920 FieldDecl *FD = nullptr;
11921 CharUnits Alignment;
11922 for (FieldDecl *FDI : ReverseMemberChain) {
11923 if (FDI->hasAttr<PackedAttr>() ||
11924 FDI->getParent()->hasAttr<PackedAttr>()) {
11925 FD = FDI;
11926 Alignment = std::min(
11927 Context.getTypeAlignInChars(FD->getType()),
11928 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
11929 break;
11930 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011931 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011932 assert(FD && "We did not find a packed FieldDecl!");
11933 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011934 }
11935}
11936
11937void Sema::CheckAddressOfPackedMember(Expr *rhs) {
11938 using namespace std::placeholders;
11939 RefersToMemberWithReducedAlignment(
11940 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
11941 _2, _3, _4));
11942}
11943