blob: bbb4b7592edda20549d4d894b3583c0412f3cca1 [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"
Yaxun Liu39195062017-08-04 18:16:31 +000028#include "clang/Basic/SyncScope.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000029#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000030#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000031#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000033#include "clang/Sema/Lookup.h"
34#include "clang/Sema/ScopeInfo.h"
35#include "clang/Sema/Sema.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000036#include "clang/Sema/SemaInternal.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000037#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000038#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "llvm/ADT/SmallString.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000040#include "llvm/Support/ConvertUTF.h"
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +000041#include "llvm/Support/Format.h"
42#include "llvm/Support/Locale.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000043#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000044
Chris Lattnerb87b1b32007-08-10 20:18:51 +000045using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000046using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000047
Chris Lattnera26fb342009-02-18 17:49:48 +000048SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
49 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000050 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
51 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000052}
53
John McCallbebede42011-02-26 05:39:39 +000054/// Checks that a call expression's argument count is the desired number.
55/// This is useful when doing custom type-checking. Returns true on error.
56static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
57 unsigned argCount = call->getNumArgs();
58 if (argCount == desiredArgCount) return false;
59
60 if (argCount < desiredArgCount)
61 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
62 << 0 /*function call*/ << desiredArgCount << argCount
63 << call->getSourceRange();
64
65 // Highlight all the excess arguments.
66 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
67 call->getArg(argCount - 1)->getLocEnd());
68
69 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
70 << 0 /*function call*/ << desiredArgCount << argCount
71 << call->getArg(1)->getSourceRange();
72}
73
Julien Lerouge4a5b4442012-04-28 17:39:16 +000074/// Check that the first argument to __builtin_annotation is an integer
75/// and the second argument is a non-wide string literal.
76static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
77 if (checkArgCount(S, TheCall, 2))
78 return true;
79
80 // First argument should be an integer.
81 Expr *ValArg = TheCall->getArg(0);
82 QualType Ty = ValArg->getType();
83 if (!Ty->isIntegerType()) {
84 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
85 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000086 return true;
87 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000088
89 // Second argument should be a constant string.
90 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
91 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
92 if (!Literal || !Literal->isAscii()) {
93 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
94 << StrArg->getSourceRange();
95 return true;
96 }
97
98 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000099 return false;
100}
101
Richard Smith6cbd65d2013-07-11 02:27:57 +0000102/// Check that the argument to __builtin_addressof is a glvalue, and set the
103/// result type to the corresponding pointer type.
104static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
105 if (checkArgCount(S, TheCall, 1))
106 return true;
107
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000108 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000109 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
110 if (ResultType.isNull())
111 return true;
112
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000113 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000114 TheCall->setType(ResultType);
115 return false;
116}
117
John McCall03107a42015-10-29 20:48:01 +0000118static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
119 if (checkArgCount(S, TheCall, 3))
120 return true;
121
122 // First two arguments should be integers.
123 for (unsigned I = 0; I < 2; ++I) {
124 Expr *Arg = TheCall->getArg(I);
125 QualType Ty = Arg->getType();
126 if (!Ty->isIntegerType()) {
127 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
128 << Ty << Arg->getSourceRange();
129 return true;
130 }
131 }
132
133 // Third argument should be a pointer to a non-const integer.
134 // IRGen correctly handles volatile, restrict, and address spaces, and
135 // the other qualifiers aren't possible.
136 {
137 Expr *Arg = TheCall->getArg(2);
138 QualType Ty = Arg->getType();
139 const auto *PtrTy = Ty->getAs<PointerType>();
140 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
141 !PtrTy->getPointeeType().isConstQualified())) {
142 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
143 << Ty << Arg->getSourceRange();
144 return true;
145 }
146 }
147
148 return false;
149}
150
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000151static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
152 CallExpr *TheCall, unsigned SizeIdx,
153 unsigned DstSizeIdx) {
154 if (TheCall->getNumArgs() <= SizeIdx ||
155 TheCall->getNumArgs() <= DstSizeIdx)
156 return;
157
158 const Expr *SizeArg = TheCall->getArg(SizeIdx);
159 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
160
161 llvm::APSInt Size, DstSize;
162
163 // find out if both sizes are known at compile time
164 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
165 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
166 return;
167
168 if (Size.ule(DstSize))
169 return;
170
171 // confirmed overflow so generate the diagnostic.
172 IdentifierInfo *FnName = FDecl->getIdentifier();
173 SourceLocation SL = TheCall->getLocStart();
174 SourceRange SR = TheCall->getSourceRange();
175
176 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
177}
178
Peter Collingbournef7706832014-12-12 23:41:25 +0000179static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
180 if (checkArgCount(S, BuiltinCall, 2))
181 return true;
182
183 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
184 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
185 Expr *Call = BuiltinCall->getArg(0);
186 Expr *Chain = BuiltinCall->getArg(1);
187
188 if (Call->getStmtClass() != Stmt::CallExprClass) {
189 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
190 << Call->getSourceRange();
191 return true;
192 }
193
194 auto CE = cast<CallExpr>(Call);
195 if (CE->getCallee()->getType()->isBlockPointerType()) {
196 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
197 << Call->getSourceRange();
198 return true;
199 }
200
201 const Decl *TargetDecl = CE->getCalleeDecl();
202 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
203 if (FD->getBuiltinID()) {
204 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
205 << Call->getSourceRange();
206 return true;
207 }
208
209 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
210 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
211 << Call->getSourceRange();
212 return true;
213 }
214
215 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
216 if (ChainResult.isInvalid())
217 return true;
218 if (!ChainResult.get()->getType()->isPointerType()) {
219 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
220 << Chain->getSourceRange();
221 return true;
222 }
223
David Majnemerced8bdf2015-02-25 17:36:15 +0000224 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000225 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
226 QualType BuiltinTy = S.Context.getFunctionType(
227 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
228 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
229
230 Builtin =
231 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
232
233 BuiltinCall->setType(CE->getType());
234 BuiltinCall->setValueKind(CE->getValueKind());
235 BuiltinCall->setObjectKind(CE->getObjectKind());
236 BuiltinCall->setCallee(Builtin);
237 BuiltinCall->setArg(1, ChainResult.get());
238
239 return false;
240}
241
Reid Kleckner1d59f992015-01-22 01:36:17 +0000242static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
243 Scope::ScopeFlags NeededScopeFlags,
244 unsigned DiagID) {
245 // Scopes aren't available during instantiation. Fortunately, builtin
246 // functions cannot be template args so they cannot be formed through template
247 // instantiation. Therefore checking once during the parse is sufficient.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000248 if (SemaRef.inTemplateInstantiation())
Reid Kleckner1d59f992015-01-22 01:36:17 +0000249 return false;
250
251 Scope *S = SemaRef.getCurScope();
252 while (S && !S->isSEHExceptScope())
253 S = S->getParent();
254 if (!S || !(S->getFlags() & NeededScopeFlags)) {
255 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
256 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
257 << DRE->getDecl()->getIdentifier();
258 return true;
259 }
260
261 return false;
262}
263
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000264static inline bool isBlockPointer(Expr *Arg) {
265 return Arg->getType()->isBlockPointerType();
266}
267
268/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
269/// void*, which is a requirement of device side enqueue.
270static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
271 const BlockPointerType *BPT =
272 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
273 ArrayRef<QualType> Params =
274 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
275 unsigned ArgCounter = 0;
276 bool IllegalParams = false;
277 // Iterate through the block parameters until either one is found that is not
278 // a local void*, or the block is valid.
279 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
280 I != E; ++I, ++ArgCounter) {
281 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
282 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
283 LangAS::opencl_local) {
284 // Get the location of the error. If a block literal has been passed
285 // (BlockExpr) then we can point straight to the offending argument,
286 // else we just point to the variable reference.
287 SourceLocation ErrorLoc;
288 if (isa<BlockExpr>(BlockArg)) {
289 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
290 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
291 } else if (isa<DeclRefExpr>(BlockArg)) {
292 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
293 }
294 S.Diag(ErrorLoc,
295 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
296 IllegalParams = true;
297 }
298 }
299
300 return IllegalParams;
301}
302
Joey Gouly84ae3362017-07-31 15:15:59 +0000303static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
304 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
305 S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
306 << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
307 return true;
308 }
309 return false;
310}
311
Joey Goulyfa76b492017-08-01 13:27:09 +0000312static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
313 if (checkArgCount(S, TheCall, 2))
314 return true;
315
316 if (checkOpenCLSubgroupExt(S, TheCall))
317 return true;
318
319 // First argument is an ndrange_t type.
320 Expr *NDRangeArg = TheCall->getArg(0);
321 if (NDRangeArg->getType().getAsString() != "ndrange_t") {
322 S.Diag(NDRangeArg->getLocStart(),
323 diag::err_opencl_builtin_expected_type)
324 << TheCall->getDirectCallee() << "'ndrange_t'";
325 return true;
326 }
327
328 Expr *BlockArg = TheCall->getArg(1);
329 if (!isBlockPointer(BlockArg)) {
330 S.Diag(BlockArg->getLocStart(),
331 diag::err_opencl_builtin_expected_type)
332 << TheCall->getDirectCallee() << "block";
333 return true;
334 }
335 return checkOpenCLBlockArgs(S, BlockArg);
336}
337
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000338/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
339/// get_kernel_work_group_size
340/// and get_kernel_preferred_work_group_size_multiple builtin functions.
341static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
342 if (checkArgCount(S, TheCall, 1))
343 return true;
344
345 Expr *BlockArg = TheCall->getArg(0);
346 if (!isBlockPointer(BlockArg)) {
347 S.Diag(BlockArg->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000348 diag::err_opencl_builtin_expected_type)
349 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000350 return true;
351 }
352 return checkOpenCLBlockArgs(S, BlockArg);
353}
354
Simon Pilgrim2c518802017-03-30 14:13:19 +0000355/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000356static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
357 const QualType &IntType);
358
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000359static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000360 unsigned Start, unsigned End) {
361 bool IllegalParams = false;
362 for (unsigned I = Start; I <= End; ++I)
363 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
364 S.Context.getSizeType());
365 return IllegalParams;
366}
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000367
368/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
369/// 'local void*' parameter of passed block.
370static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
371 Expr *BlockArg,
372 unsigned NumNonVarArgs) {
373 const BlockPointerType *BPT =
374 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
375 unsigned NumBlockParams =
376 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
377 unsigned TotalNumArgs = TheCall->getNumArgs();
378
379 // For each argument passed to the block, a corresponding uint needs to
380 // be passed to describe the size of the local memory.
381 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
382 S.Diag(TheCall->getLocStart(),
383 diag::err_opencl_enqueue_kernel_local_size_args);
384 return true;
385 }
386
387 // Check that the sizes of the local memory are specified by integers.
388 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
389 TotalNumArgs - 1);
390}
391
392/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
393/// overload formats specified in Table 6.13.17.1.
394/// int enqueue_kernel(queue_t queue,
395/// kernel_enqueue_flags_t flags,
396/// const ndrange_t ndrange,
397/// void (^block)(void))
398/// int enqueue_kernel(queue_t queue,
399/// kernel_enqueue_flags_t flags,
400/// const ndrange_t ndrange,
401/// uint num_events_in_wait_list,
402/// clk_event_t *event_wait_list,
403/// clk_event_t *event_ret,
404/// void (^block)(void))
405/// int enqueue_kernel(queue_t queue,
406/// kernel_enqueue_flags_t flags,
407/// const ndrange_t ndrange,
408/// void (^block)(local void*, ...),
409/// uint size0, ...)
410/// int enqueue_kernel(queue_t queue,
411/// kernel_enqueue_flags_t flags,
412/// const ndrange_t ndrange,
413/// uint num_events_in_wait_list,
414/// clk_event_t *event_wait_list,
415/// clk_event_t *event_ret,
416/// void (^block)(local void*, ...),
417/// uint size0, ...)
418static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
419 unsigned NumArgs = TheCall->getNumArgs();
420
421 if (NumArgs < 4) {
422 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
423 return true;
424 }
425
426 Expr *Arg0 = TheCall->getArg(0);
427 Expr *Arg1 = TheCall->getArg(1);
428 Expr *Arg2 = TheCall->getArg(2);
429 Expr *Arg3 = TheCall->getArg(3);
430
431 // First argument always needs to be a queue_t type.
432 if (!Arg0->getType()->isQueueT()) {
433 S.Diag(TheCall->getArg(0)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000434 diag::err_opencl_builtin_expected_type)
435 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000436 return true;
437 }
438
439 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
440 if (!Arg1->getType()->isIntegerType()) {
441 S.Diag(TheCall->getArg(1)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000442 diag::err_opencl_builtin_expected_type)
443 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000444 return true;
445 }
446
447 // Third argument is always an ndrange_t type.
Anastasia Stulovab42f3c02017-04-21 15:13:24 +0000448 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000449 S.Diag(TheCall->getArg(2)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000450 diag::err_opencl_builtin_expected_type)
451 << TheCall->getDirectCallee() << "'ndrange_t'";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000452 return true;
453 }
454
455 // With four arguments, there is only one form that the function could be
456 // called in: no events and no variable arguments.
457 if (NumArgs == 4) {
458 // check that the last argument is the right block type.
459 if (!isBlockPointer(Arg3)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000460 S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
461 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000462 return true;
463 }
464 // we have a block type, check the prototype
465 const BlockPointerType *BPT =
466 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
467 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
468 S.Diag(Arg3->getLocStart(),
469 diag::err_opencl_enqueue_kernel_blocks_no_args);
470 return true;
471 }
472 return false;
473 }
474 // we can have block + varargs.
475 if (isBlockPointer(Arg3))
476 return (checkOpenCLBlockArgs(S, Arg3) ||
477 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
478 // last two cases with either exactly 7 args or 7 args and varargs.
479 if (NumArgs >= 7) {
480 // check common block argument.
481 Expr *Arg6 = TheCall->getArg(6);
482 if (!isBlockPointer(Arg6)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000483 S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
484 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000485 return true;
486 }
487 if (checkOpenCLBlockArgs(S, Arg6))
488 return true;
489
490 // Forth argument has to be any integer type.
491 if (!Arg3->getType()->isIntegerType()) {
492 S.Diag(TheCall->getArg(3)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000493 diag::err_opencl_builtin_expected_type)
494 << TheCall->getDirectCallee() << "integer";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000495 return true;
496 }
497 // check remaining common arguments.
498 Expr *Arg4 = TheCall->getArg(4);
499 Expr *Arg5 = TheCall->getArg(5);
500
Anastasia Stulova2b461202016-11-14 15:34:01 +0000501 // Fifth argument is always passed as a pointer to clk_event_t.
502 if (!Arg4->isNullPointerConstant(S.Context,
503 Expr::NPC_ValueDependentIsNotNull) &&
504 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000505 S.Diag(TheCall->getArg(4)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000506 diag::err_opencl_builtin_expected_type)
507 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000508 << S.Context.getPointerType(S.Context.OCLClkEventTy);
509 return true;
510 }
511
Anastasia Stulova2b461202016-11-14 15:34:01 +0000512 // Sixth argument is always passed as a pointer to clk_event_t.
513 if (!Arg5->isNullPointerConstant(S.Context,
514 Expr::NPC_ValueDependentIsNotNull) &&
515 !(Arg5->getType()->isPointerType() &&
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000516 Arg5->getType()->getPointeeType()->isClkEventT())) {
517 S.Diag(TheCall->getArg(5)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000518 diag::err_opencl_builtin_expected_type)
519 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000520 << S.Context.getPointerType(S.Context.OCLClkEventTy);
521 return true;
522 }
523
524 if (NumArgs == 7)
525 return false;
526
527 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
528 }
529
530 // None of the specific case has been detected, give generic error
531 S.Diag(TheCall->getLocStart(),
532 diag::err_opencl_enqueue_kernel_incorrect_args);
533 return true;
534}
535
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000536/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000537static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000538 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000539}
540
541/// Returns true if pipe element type is different from the pointer.
542static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
543 const Expr *Arg0 = Call->getArg(0);
544 // First argument type should always be pipe.
545 if (!Arg0->getType()->isPipeType()) {
546 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000547 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000548 return true;
549 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000550 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000551 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
552 // Validates the access qualifier is compatible with the call.
553 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
554 // read_only and write_only, and assumed to be read_only if no qualifier is
555 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000556 switch (Call->getDirectCallee()->getBuiltinID()) {
557 case Builtin::BIread_pipe:
558 case Builtin::BIreserve_read_pipe:
559 case Builtin::BIcommit_read_pipe:
560 case Builtin::BIwork_group_reserve_read_pipe:
561 case Builtin::BIsub_group_reserve_read_pipe:
562 case Builtin::BIwork_group_commit_read_pipe:
563 case Builtin::BIsub_group_commit_read_pipe:
564 if (!(!AccessQual || AccessQual->isReadOnly())) {
565 S.Diag(Arg0->getLocStart(),
566 diag::err_opencl_builtin_pipe_invalid_access_modifier)
567 << "read_only" << Arg0->getSourceRange();
568 return true;
569 }
570 break;
571 case Builtin::BIwrite_pipe:
572 case Builtin::BIreserve_write_pipe:
573 case Builtin::BIcommit_write_pipe:
574 case Builtin::BIwork_group_reserve_write_pipe:
575 case Builtin::BIsub_group_reserve_write_pipe:
576 case Builtin::BIwork_group_commit_write_pipe:
577 case Builtin::BIsub_group_commit_write_pipe:
578 if (!(AccessQual && AccessQual->isWriteOnly())) {
579 S.Diag(Arg0->getLocStart(),
580 diag::err_opencl_builtin_pipe_invalid_access_modifier)
581 << "write_only" << Arg0->getSourceRange();
582 return true;
583 }
584 break;
585 default:
586 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000587 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000588 return false;
589}
590
591/// Returns true if pipe element type is different from the pointer.
592static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
593 const Expr *Arg0 = Call->getArg(0);
594 const Expr *ArgIdx = Call->getArg(Idx);
595 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000596 const QualType EltTy = PipeTy->getElementType();
597 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000598 // The Idx argument should be a pointer and the type of the pointer and
599 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000600 if (!ArgTy ||
601 !S.Context.hasSameType(
602 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000603 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000604 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000605 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000606 return true;
607 }
608 return false;
609}
610
611// \brief Performs semantic analysis for the read/write_pipe call.
612// \param S Reference to the semantic analyzer.
613// \param Call A pointer to the builtin call.
614// \return True if a semantic error has been found, false otherwise.
615static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000616 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
617 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000618 switch (Call->getNumArgs()) {
619 case 2: {
620 if (checkOpenCLPipeArg(S, Call))
621 return true;
622 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000623 // read/write_pipe(pipe T, T*).
624 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000625 if (checkOpenCLPipePacketType(S, Call, 1))
626 return true;
627 } break;
628
629 case 4: {
630 if (checkOpenCLPipeArg(S, Call))
631 return true;
632 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000633 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
634 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000635 if (!Call->getArg(1)->getType()->isReserveIDT()) {
636 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000637 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000638 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000639 return true;
640 }
641
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000642 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000643 const Expr *Arg2 = Call->getArg(2);
644 if (!Arg2->getType()->isIntegerType() &&
645 !Arg2->getType()->isUnsignedIntegerType()) {
646 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000647 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000648 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000649 return true;
650 }
651
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000652 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000653 if (checkOpenCLPipePacketType(S, Call, 3))
654 return true;
655 } break;
656 default:
657 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000658 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000659 return true;
660 }
661
662 return false;
663}
664
665// \brief Performs a semantic analysis on the {work_group_/sub_group_
666// /_}reserve_{read/write}_pipe
667// \param S Reference to the semantic analyzer.
668// \param Call The call to the builtin function to be analyzed.
669// \return True if a semantic error was found, false otherwise.
670static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
671 if (checkArgCount(S, Call, 2))
672 return true;
673
674 if (checkOpenCLPipeArg(S, Call))
675 return true;
676
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000677 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000678 if (!Call->getArg(1)->getType()->isIntegerType() &&
679 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
680 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000681 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000682 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000683 return true;
684 }
685
686 return false;
687}
688
689// \brief Performs a semantic analysis on {work_group_/sub_group_
690// /_}commit_{read/write}_pipe
691// \param S Reference to the semantic analyzer.
692// \param Call The call to the builtin function to be analyzed.
693// \return True if a semantic error was found, false otherwise.
694static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
695 if (checkArgCount(S, Call, 2))
696 return true;
697
698 if (checkOpenCLPipeArg(S, Call))
699 return true;
700
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000701 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000702 if (!Call->getArg(1)->getType()->isReserveIDT()) {
703 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000704 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000705 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000706 return true;
707 }
708
709 return false;
710}
711
712// \brief Performs a semantic analysis on the call to built-in Pipe
713// Query Functions.
714// \param S Reference to the semantic analyzer.
715// \param Call The call to the builtin function to be analyzed.
716// \return True if a semantic error was found, false otherwise.
717static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
718 if (checkArgCount(S, Call, 1))
719 return true;
720
721 if (!Call->getArg(0)->getType()->isPipeType()) {
722 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000723 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000724 return true;
725 }
726
727 return false;
728}
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +0000729// \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
Yaxun Liuf7449a12016-05-20 19:54:38 +0000730// \brief Performs semantic analysis for the to_global/local/private call.
731// \param S Reference to the semantic analyzer.
732// \param BuiltinID ID of the builtin function.
733// \param Call A pointer to the builtin call.
734// \return True if a semantic error has been found, false otherwise.
735static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
736 CallExpr *Call) {
Yaxun Liuf7449a12016-05-20 19:54:38 +0000737 if (Call->getNumArgs() != 1) {
738 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
739 << Call->getDirectCallee() << Call->getSourceRange();
740 return true;
741 }
742
743 auto RT = Call->getArg(0)->getType();
744 if (!RT->isPointerType() || RT->getPointeeType()
745 .getAddressSpace() == LangAS::opencl_constant) {
746 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
747 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
748 return true;
749 }
750
751 RT = RT->getPointeeType();
752 auto Qual = RT.getQualifiers();
753 switch (BuiltinID) {
754 case Builtin::BIto_global:
755 Qual.setAddressSpace(LangAS::opencl_global);
756 break;
757 case Builtin::BIto_local:
758 Qual.setAddressSpace(LangAS::opencl_local);
759 break;
760 default:
761 Qual.removeAddressSpace();
762 }
763 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
764 RT.getUnqualifiedType(), Qual)));
765
766 return false;
767}
768
John McCalldadc5752010-08-24 06:29:42 +0000769ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000770Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
771 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000772 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000773
Chris Lattner3be167f2010-10-01 23:23:24 +0000774 // Find out if any arguments are required to be integer constant expressions.
775 unsigned ICEArguments = 0;
776 ASTContext::GetBuiltinTypeError Error;
777 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
778 if (Error != ASTContext::GE_None)
779 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
780
781 // If any arguments are required to be ICE's, check and diagnose.
782 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
783 // Skip arguments not required to be ICE's.
784 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
785
786 llvm::APSInt Result;
787 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
788 return true;
789 ICEArguments &= ~(1 << ArgNo);
790 }
791
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000792 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000793 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000794 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000795 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000796 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000797 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000798 break;
Martin Storsjo022e7822017-07-17 20:49:45 +0000799 case Builtin::BI__builtin_ms_va_start:
Ted Kremeneka174c522008-07-09 17:58:53 +0000800 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000801 case Builtin::BI__builtin_va_start:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000802 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000803 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000804 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000805 case Builtin::BI__va_start: {
806 switch (Context.getTargetInfo().getTriple().getArch()) {
807 case llvm::Triple::arm:
808 case llvm::Triple::thumb:
809 if (SemaBuiltinVAStartARM(TheCall))
810 return ExprError();
811 break;
812 default:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000813 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000814 return ExprError();
815 break;
816 }
817 break;
818 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000819 case Builtin::BI__builtin_isgreater:
820 case Builtin::BI__builtin_isgreaterequal:
821 case Builtin::BI__builtin_isless:
822 case Builtin::BI__builtin_islessequal:
823 case Builtin::BI__builtin_islessgreater:
824 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000825 if (SemaBuiltinUnorderedCompare(TheCall))
826 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000827 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000828 case Builtin::BI__builtin_fpclassify:
829 if (SemaBuiltinFPClassification(TheCall, 6))
830 return ExprError();
831 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000832 case Builtin::BI__builtin_isfinite:
833 case Builtin::BI__builtin_isinf:
834 case Builtin::BI__builtin_isinf_sign:
835 case Builtin::BI__builtin_isnan:
836 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000837 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000838 return ExprError();
839 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000840 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000841 return SemaBuiltinShuffleVector(TheCall);
842 // TheCall will be freed by the smart pointer here, but that's fine, since
843 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000844 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000845 if (SemaBuiltinPrefetch(TheCall))
846 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000847 break;
David Majnemer51169932016-10-31 05:37:48 +0000848 case Builtin::BI__builtin_alloca_with_align:
849 if (SemaBuiltinAllocaWithAlign(TheCall))
850 return ExprError();
851 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000852 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000853 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000854 if (SemaBuiltinAssume(TheCall))
855 return ExprError();
856 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000857 case Builtin::BI__builtin_assume_aligned:
858 if (SemaBuiltinAssumeAligned(TheCall))
859 return ExprError();
860 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000861 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000862 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000863 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000864 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000865 case Builtin::BI__builtin_longjmp:
866 if (SemaBuiltinLongjmp(TheCall))
867 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000868 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000869 case Builtin::BI__builtin_setjmp:
870 if (SemaBuiltinSetjmp(TheCall))
871 return ExprError();
872 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000873 case Builtin::BI_setjmp:
874 case Builtin::BI_setjmpex:
875 if (checkArgCount(*this, TheCall, 1))
876 return true;
877 break;
John McCallbebede42011-02-26 05:39:39 +0000878
879 case Builtin::BI__builtin_classify_type:
880 if (checkArgCount(*this, TheCall, 1)) return true;
881 TheCall->setType(Context.IntTy);
882 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000883 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000884 if (checkArgCount(*this, TheCall, 1)) return true;
885 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000886 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000887 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000888 case Builtin::BI__sync_fetch_and_add_1:
889 case Builtin::BI__sync_fetch_and_add_2:
890 case Builtin::BI__sync_fetch_and_add_4:
891 case Builtin::BI__sync_fetch_and_add_8:
892 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000893 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000894 case Builtin::BI__sync_fetch_and_sub_1:
895 case Builtin::BI__sync_fetch_and_sub_2:
896 case Builtin::BI__sync_fetch_and_sub_4:
897 case Builtin::BI__sync_fetch_and_sub_8:
898 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000899 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000900 case Builtin::BI__sync_fetch_and_or_1:
901 case Builtin::BI__sync_fetch_and_or_2:
902 case Builtin::BI__sync_fetch_and_or_4:
903 case Builtin::BI__sync_fetch_and_or_8:
904 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000905 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000906 case Builtin::BI__sync_fetch_and_and_1:
907 case Builtin::BI__sync_fetch_and_and_2:
908 case Builtin::BI__sync_fetch_and_and_4:
909 case Builtin::BI__sync_fetch_and_and_8:
910 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000911 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000912 case Builtin::BI__sync_fetch_and_xor_1:
913 case Builtin::BI__sync_fetch_and_xor_2:
914 case Builtin::BI__sync_fetch_and_xor_4:
915 case Builtin::BI__sync_fetch_and_xor_8:
916 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000917 case Builtin::BI__sync_fetch_and_nand:
918 case Builtin::BI__sync_fetch_and_nand_1:
919 case Builtin::BI__sync_fetch_and_nand_2:
920 case Builtin::BI__sync_fetch_and_nand_4:
921 case Builtin::BI__sync_fetch_and_nand_8:
922 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000923 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000924 case Builtin::BI__sync_add_and_fetch_1:
925 case Builtin::BI__sync_add_and_fetch_2:
926 case Builtin::BI__sync_add_and_fetch_4:
927 case Builtin::BI__sync_add_and_fetch_8:
928 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000929 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000930 case Builtin::BI__sync_sub_and_fetch_1:
931 case Builtin::BI__sync_sub_and_fetch_2:
932 case Builtin::BI__sync_sub_and_fetch_4:
933 case Builtin::BI__sync_sub_and_fetch_8:
934 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000935 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000936 case Builtin::BI__sync_and_and_fetch_1:
937 case Builtin::BI__sync_and_and_fetch_2:
938 case Builtin::BI__sync_and_and_fetch_4:
939 case Builtin::BI__sync_and_and_fetch_8:
940 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000941 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000942 case Builtin::BI__sync_or_and_fetch_1:
943 case Builtin::BI__sync_or_and_fetch_2:
944 case Builtin::BI__sync_or_and_fetch_4:
945 case Builtin::BI__sync_or_and_fetch_8:
946 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000947 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000948 case Builtin::BI__sync_xor_and_fetch_1:
949 case Builtin::BI__sync_xor_and_fetch_2:
950 case Builtin::BI__sync_xor_and_fetch_4:
951 case Builtin::BI__sync_xor_and_fetch_8:
952 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000953 case Builtin::BI__sync_nand_and_fetch:
954 case Builtin::BI__sync_nand_and_fetch_1:
955 case Builtin::BI__sync_nand_and_fetch_2:
956 case Builtin::BI__sync_nand_and_fetch_4:
957 case Builtin::BI__sync_nand_and_fetch_8:
958 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000959 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000960 case Builtin::BI__sync_val_compare_and_swap_1:
961 case Builtin::BI__sync_val_compare_and_swap_2:
962 case Builtin::BI__sync_val_compare_and_swap_4:
963 case Builtin::BI__sync_val_compare_and_swap_8:
964 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000965 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000966 case Builtin::BI__sync_bool_compare_and_swap_1:
967 case Builtin::BI__sync_bool_compare_and_swap_2:
968 case Builtin::BI__sync_bool_compare_and_swap_4:
969 case Builtin::BI__sync_bool_compare_and_swap_8:
970 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000971 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000972 case Builtin::BI__sync_lock_test_and_set_1:
973 case Builtin::BI__sync_lock_test_and_set_2:
974 case Builtin::BI__sync_lock_test_and_set_4:
975 case Builtin::BI__sync_lock_test_and_set_8:
976 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000977 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000978 case Builtin::BI__sync_lock_release_1:
979 case Builtin::BI__sync_lock_release_2:
980 case Builtin::BI__sync_lock_release_4:
981 case Builtin::BI__sync_lock_release_8:
982 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000983 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000984 case Builtin::BI__sync_swap_1:
985 case Builtin::BI__sync_swap_2:
986 case Builtin::BI__sync_swap_4:
987 case Builtin::BI__sync_swap_8:
988 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000989 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000990 case Builtin::BI__builtin_nontemporal_load:
991 case Builtin::BI__builtin_nontemporal_store:
992 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000993#define BUILTIN(ID, TYPE, ATTRS)
994#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
995 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000996 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000997#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000998 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000999 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001000 return ExprError();
1001 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +00001002 case Builtin::BI__builtin_addressof:
1003 if (SemaBuiltinAddressof(*this, TheCall))
1004 return ExprError();
1005 break;
John McCall03107a42015-10-29 20:48:01 +00001006 case Builtin::BI__builtin_add_overflow:
1007 case Builtin::BI__builtin_sub_overflow:
1008 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +00001009 if (SemaBuiltinOverflow(*this, TheCall))
1010 return ExprError();
1011 break;
Richard Smith760520b2014-06-03 23:27:44 +00001012 case Builtin::BI__builtin_operator_new:
1013 case Builtin::BI__builtin_operator_delete:
1014 if (!getLangOpts().CPlusPlus) {
1015 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
1016 << (BuiltinID == Builtin::BI__builtin_operator_new
1017 ? "__builtin_operator_new"
1018 : "__builtin_operator_delete")
1019 << "C++";
1020 return ExprError();
1021 }
1022 // CodeGen assumes it can find the global new and delete to call,
1023 // so ensure that they are declared.
1024 DeclareGlobalNewDelete();
1025 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001026
1027 // check secure string manipulation functions where overflows
1028 // are detectable at compile time
1029 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001030 case Builtin::BI__builtin___memmove_chk:
1031 case Builtin::BI__builtin___memset_chk:
1032 case Builtin::BI__builtin___strlcat_chk:
1033 case Builtin::BI__builtin___strlcpy_chk:
1034 case Builtin::BI__builtin___strncat_chk:
1035 case Builtin::BI__builtin___strncpy_chk:
1036 case Builtin::BI__builtin___stpncpy_chk:
1037 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1038 break;
Steven Wu566c14e2014-09-24 04:37:33 +00001039 case Builtin::BI__builtin___memccpy_chk:
1040 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1041 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001042 case Builtin::BI__builtin___snprintf_chk:
1043 case Builtin::BI__builtin___vsnprintf_chk:
1044 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1045 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001046 case Builtin::BI__builtin_call_with_static_chain:
1047 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1048 return ExprError();
1049 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001050 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001051 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001052 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1053 diag::err_seh___except_block))
1054 return ExprError();
1055 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001056 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001057 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001058 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1059 diag::err_seh___except_filter))
1060 return ExprError();
1061 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001062 case Builtin::BI__GetExceptionInfo:
1063 if (checkArgCount(*this, TheCall, 1))
1064 return ExprError();
1065
1066 if (CheckCXXThrowOperand(
1067 TheCall->getLocStart(),
1068 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1069 TheCall))
1070 return ExprError();
1071
1072 TheCall->setType(Context.VoidPtrTy);
1073 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001074 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001075 case Builtin::BIread_pipe:
1076 case Builtin::BIwrite_pipe:
1077 // Since those two functions are declared with var args, we need a semantic
1078 // check for the argument.
1079 if (SemaBuiltinRWPipe(*this, TheCall))
1080 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001081 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001082 break;
1083 case Builtin::BIreserve_read_pipe:
1084 case Builtin::BIreserve_write_pipe:
1085 case Builtin::BIwork_group_reserve_read_pipe:
1086 case Builtin::BIwork_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001087 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1088 return ExprError();
1089 // Since return type of reserve_read/write_pipe built-in function is
1090 // reserve_id_t, which is not defined in the builtin def file , we used int
1091 // as return type and need to override the return type of these functions.
1092 TheCall->setType(Context.OCLReserveIDTy);
1093 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001094 case Builtin::BIsub_group_reserve_read_pipe:
1095 case Builtin::BIsub_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001096 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1097 SemaBuiltinReserveRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001098 return ExprError();
1099 // Since return type of reserve_read/write_pipe built-in function is
1100 // reserve_id_t, which is not defined in the builtin def file , we used int
1101 // as return type and need to override the return type of these functions.
1102 TheCall->setType(Context.OCLReserveIDTy);
1103 break;
1104 case Builtin::BIcommit_read_pipe:
1105 case Builtin::BIcommit_write_pipe:
1106 case Builtin::BIwork_group_commit_read_pipe:
1107 case Builtin::BIwork_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001108 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1109 return ExprError();
1110 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001111 case Builtin::BIsub_group_commit_read_pipe:
1112 case Builtin::BIsub_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001113 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1114 SemaBuiltinCommitRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001115 return ExprError();
1116 break;
1117 case Builtin::BIget_pipe_num_packets:
1118 case Builtin::BIget_pipe_max_packets:
1119 if (SemaBuiltinPipePackets(*this, TheCall))
1120 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001121 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001122 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001123 case Builtin::BIto_global:
1124 case Builtin::BIto_local:
1125 case Builtin::BIto_private:
1126 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1127 return ExprError();
1128 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001129 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1130 case Builtin::BIenqueue_kernel:
1131 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1132 return ExprError();
1133 break;
1134 case Builtin::BIget_kernel_work_group_size:
1135 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1136 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1137 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001138 break;
Joey Goulyfa76b492017-08-01 13:27:09 +00001139 break;
1140 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1141 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1142 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1143 return ExprError();
1144 break;
Mehdi Amini06d367c2016-10-24 20:39:34 +00001145 case Builtin::BI__builtin_os_log_format:
1146 case Builtin::BI__builtin_os_log_format_buffer_size:
1147 if (SemaBuiltinOSLogFormat(TheCall)) {
1148 return ExprError();
1149 }
1150 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001151 }
Richard Smith760520b2014-06-03 23:27:44 +00001152
Nate Begeman4904e322010-06-08 02:47:44 +00001153 // Since the target specific builtins for each arch overlap, only check those
1154 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001155 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001156 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001157 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001158 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001159 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001160 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001161 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1162 return ExprError();
1163 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001164 case llvm::Triple::aarch64:
1165 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001166 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001167 return ExprError();
1168 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001169 case llvm::Triple::mips:
1170 case llvm::Triple::mipsel:
1171 case llvm::Triple::mips64:
1172 case llvm::Triple::mips64el:
1173 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1174 return ExprError();
1175 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001176 case llvm::Triple::systemz:
1177 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1178 return ExprError();
1179 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001180 case llvm::Triple::x86:
1181 case llvm::Triple::x86_64:
1182 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1183 return ExprError();
1184 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001185 case llvm::Triple::ppc:
1186 case llvm::Triple::ppc64:
1187 case llvm::Triple::ppc64le:
1188 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1189 return ExprError();
1190 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001191 default:
1192 break;
1193 }
1194 }
1195
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001196 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001197}
1198
Nate Begeman91e1fea2010-06-14 05:21:25 +00001199// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001200static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001201 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001202 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001203 switch (Type.getEltType()) {
1204 case NeonTypeFlags::Int8:
1205 case NeonTypeFlags::Poly8:
1206 return shift ? 7 : (8 << IsQuad) - 1;
1207 case NeonTypeFlags::Int16:
1208 case NeonTypeFlags::Poly16:
1209 return shift ? 15 : (4 << IsQuad) - 1;
1210 case NeonTypeFlags::Int32:
1211 return shift ? 31 : (2 << IsQuad) - 1;
1212 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001213 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001214 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001215 case NeonTypeFlags::Poly128:
1216 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001217 case NeonTypeFlags::Float16:
1218 assert(!shift && "cannot shift float types!");
1219 return (4 << IsQuad) - 1;
1220 case NeonTypeFlags::Float32:
1221 assert(!shift && "cannot shift float types!");
1222 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001223 case NeonTypeFlags::Float64:
1224 assert(!shift && "cannot shift float types!");
1225 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001226 }
David Blaikie8a40f702012-01-17 06:56:22 +00001227 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001228}
1229
Bob Wilsone4d77232011-11-08 05:04:11 +00001230/// getNeonEltType - Return the QualType corresponding to the elements of
1231/// the vector type specified by the NeonTypeFlags. This is used to check
1232/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001233static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001234 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001235 switch (Flags.getEltType()) {
1236 case NeonTypeFlags::Int8:
1237 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1238 case NeonTypeFlags::Int16:
1239 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1240 case NeonTypeFlags::Int32:
1241 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1242 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001243 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001244 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1245 else
1246 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1247 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001248 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001249 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001250 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001251 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001252 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001253 if (IsInt64Long)
1254 return Context.UnsignedLongTy;
1255 else
1256 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001257 case NeonTypeFlags::Poly128:
1258 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001259 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001260 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001261 case NeonTypeFlags::Float32:
1262 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001263 case NeonTypeFlags::Float64:
1264 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001265 }
David Blaikie8a40f702012-01-17 06:56:22 +00001266 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001267}
1268
Tim Northover12670412014-02-19 10:37:05 +00001269bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001270 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001271 uint64_t mask = 0;
1272 unsigned TV = 0;
1273 int PtrArgNum = -1;
1274 bool HasConstPtr = false;
1275 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001276#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001277#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001278#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001279 }
1280
1281 // For NEON intrinsics which are overloaded on vector element type, validate
1282 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001283 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001284 if (mask) {
1285 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1286 return true;
1287
1288 TV = Result.getLimitedValue(64);
1289 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1290 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001291 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001292 }
1293
1294 if (PtrArgNum >= 0) {
1295 // Check that pointer arguments have the specified type.
1296 Expr *Arg = TheCall->getArg(PtrArgNum);
1297 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1298 Arg = ICE->getSubExpr();
1299 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1300 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001301
Tim Northovera2ee4332014-03-29 15:09:45 +00001302 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001303 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1304 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001305 bool IsInt64Long =
1306 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1307 QualType EltTy =
1308 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001309 if (HasConstPtr)
1310 EltTy = EltTy.withConst();
1311 QualType LHSTy = Context.getPointerType(EltTy);
1312 AssignConvertType ConvTy;
1313 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1314 if (RHS.isInvalid())
1315 return true;
1316 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1317 RHS.get(), AA_Assigning))
1318 return true;
1319 }
1320
1321 // For NEON intrinsics which take an immediate value as part of the
1322 // instruction, range check them here.
1323 unsigned i = 0, l = 0, u = 0;
1324 switch (BuiltinID) {
1325 default:
1326 return false;
Tim Northover12670412014-02-19 10:37:05 +00001327#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001328#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001329#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001330 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001331
Richard Sandiford28940af2014-04-16 08:47:51 +00001332 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001333}
1334
Tim Northovera2ee4332014-03-29 15:09:45 +00001335bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1336 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001337 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001338 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001339 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001340 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001341 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001342 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1343 BuiltinID == AArch64::BI__builtin_arm_strex ||
1344 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001345 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001346 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001347 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1348 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1349 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001350
1351 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1352
1353 // Ensure that we have the proper number of arguments.
1354 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1355 return true;
1356
1357 // Inspect the pointer argument of the atomic builtin. This should always be
1358 // a pointer type, whose element is an integral scalar or pointer type.
1359 // Because it is a pointer type, we don't have to worry about any implicit
1360 // casts here.
1361 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1362 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1363 if (PointerArgRes.isInvalid())
1364 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001365 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001366
1367 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1368 if (!pointerType) {
1369 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1370 << PointerArg->getType() << PointerArg->getSourceRange();
1371 return true;
1372 }
1373
1374 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1375 // task is to insert the appropriate casts into the AST. First work out just
1376 // what the appropriate type is.
1377 QualType ValType = pointerType->getPointeeType();
1378 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1379 if (IsLdrex)
1380 AddrType.addConst();
1381
1382 // Issue a warning if the cast is dodgy.
1383 CastKind CastNeeded = CK_NoOp;
1384 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1385 CastNeeded = CK_BitCast;
1386 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1387 << PointerArg->getType()
1388 << Context.getPointerType(AddrType)
1389 << AA_Passing << PointerArg->getSourceRange();
1390 }
1391
1392 // Finally, do the cast and replace the argument with the corrected version.
1393 AddrType = Context.getPointerType(AddrType);
1394 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1395 if (PointerArgRes.isInvalid())
1396 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001397 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001398
1399 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1400
1401 // In general, we allow ints, floats and pointers to be loaded and stored.
1402 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1403 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1404 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1405 << PointerArg->getType() << PointerArg->getSourceRange();
1406 return true;
1407 }
1408
1409 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001410 if (Context.getTypeSize(ValType) > MaxWidth) {
1411 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001412 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1413 << PointerArg->getType() << PointerArg->getSourceRange();
1414 return true;
1415 }
1416
1417 switch (ValType.getObjCLifetime()) {
1418 case Qualifiers::OCL_None:
1419 case Qualifiers::OCL_ExplicitNone:
1420 // okay
1421 break;
1422
1423 case Qualifiers::OCL_Weak:
1424 case Qualifiers::OCL_Strong:
1425 case Qualifiers::OCL_Autoreleasing:
1426 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1427 << ValType << PointerArg->getSourceRange();
1428 return true;
1429 }
1430
Tim Northover6aacd492013-07-16 09:47:53 +00001431 if (IsLdrex) {
1432 TheCall->setType(ValType);
1433 return false;
1434 }
1435
1436 // Initialize the argument to be stored.
1437 ExprResult ValArg = TheCall->getArg(0);
1438 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1439 Context, ValType, /*consume*/ false);
1440 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1441 if (ValArg.isInvalid())
1442 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001443 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001444
1445 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1446 // but the custom checker bypasses all default analysis.
1447 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001448 return false;
1449}
1450
Nate Begeman4904e322010-06-08 02:47:44 +00001451bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover6aacd492013-07-16 09:47:53 +00001452 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001453 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1454 BuiltinID == ARM::BI__builtin_arm_strex ||
1455 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001456 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001457 }
1458
Yi Kong26d104a2014-08-13 19:18:14 +00001459 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1460 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1461 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1462 }
1463
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001464 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1465 BuiltinID == ARM::BI__builtin_arm_wsr64)
1466 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1467
1468 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1469 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1470 BuiltinID == ARM::BI__builtin_arm_wsr ||
1471 BuiltinID == ARM::BI__builtin_arm_wsrp)
1472 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1473
Tim Northover12670412014-02-19 10:37:05 +00001474 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1475 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001476
Yi Kong4efadfb2014-07-03 16:01:25 +00001477 // For intrinsics which take an immediate value as part of the instruction,
1478 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001479 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001480 switch (BuiltinID) {
1481 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001482 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1483 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001484 case ARM::BI__builtin_arm_vcvtr_f:
1485 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001486 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001487 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001488 case ARM::BI__builtin_arm_isb:
1489 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001490 }
Nate Begemand773fe62010-06-13 04:47:52 +00001491
Nate Begemanf568b072010-08-03 21:32:34 +00001492 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001493 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001494}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001495
Tim Northover573cbee2014-05-24 12:52:07 +00001496bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001497 CallExpr *TheCall) {
Tim Northover573cbee2014-05-24 12:52:07 +00001498 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001499 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1500 BuiltinID == AArch64::BI__builtin_arm_strex ||
1501 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001502 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1503 }
1504
Yi Konga5548432014-08-13 19:18:20 +00001505 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1506 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1507 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1508 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1509 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1510 }
1511
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001512 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1513 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001514 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001515
1516 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1517 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1518 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1519 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1520 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1521
Tim Northovera2ee4332014-03-29 15:09:45 +00001522 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1523 return true;
1524
Yi Kong19a29ac2014-07-17 10:52:06 +00001525 // For intrinsics which take an immediate value as part of the instruction,
1526 // range check them here.
1527 unsigned i = 0, l = 0, u = 0;
1528 switch (BuiltinID) {
1529 default: return false;
1530 case AArch64::BI__builtin_arm_dmb:
1531 case AArch64::BI__builtin_arm_dsb:
1532 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1533 }
1534
Yi Kong19a29ac2014-07-17 10:52:06 +00001535 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001536}
1537
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001538// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1539// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1540// ordering for DSP is unspecified. MSA is ordered by the data format used
1541// by the underlying instruction i.e., df/m, df/n and then by size.
1542//
1543// FIXME: The size tests here should instead be tablegen'd along with the
1544// definitions from include/clang/Basic/BuiltinsMips.def.
1545// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1546// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001547bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001548 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001549 switch (BuiltinID) {
1550 default: return false;
1551 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1552 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001553 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1554 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1555 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1556 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1557 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001558 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1559 // df/m field.
1560 // These intrinsics take an unsigned 3 bit immediate.
1561 case Mips::BI__builtin_msa_bclri_b:
1562 case Mips::BI__builtin_msa_bnegi_b:
1563 case Mips::BI__builtin_msa_bseti_b:
1564 case Mips::BI__builtin_msa_sat_s_b:
1565 case Mips::BI__builtin_msa_sat_u_b:
1566 case Mips::BI__builtin_msa_slli_b:
1567 case Mips::BI__builtin_msa_srai_b:
1568 case Mips::BI__builtin_msa_srari_b:
1569 case Mips::BI__builtin_msa_srli_b:
1570 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1571 case Mips::BI__builtin_msa_binsli_b:
1572 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1573 // These intrinsics take an unsigned 4 bit immediate.
1574 case Mips::BI__builtin_msa_bclri_h:
1575 case Mips::BI__builtin_msa_bnegi_h:
1576 case Mips::BI__builtin_msa_bseti_h:
1577 case Mips::BI__builtin_msa_sat_s_h:
1578 case Mips::BI__builtin_msa_sat_u_h:
1579 case Mips::BI__builtin_msa_slli_h:
1580 case Mips::BI__builtin_msa_srai_h:
1581 case Mips::BI__builtin_msa_srari_h:
1582 case Mips::BI__builtin_msa_srli_h:
1583 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1584 case Mips::BI__builtin_msa_binsli_h:
1585 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1586 // These intrinsics take an unsigned 5 bit immedate.
1587 // The first block of intrinsics actually have an unsigned 5 bit field,
1588 // not a df/n field.
1589 case Mips::BI__builtin_msa_clei_u_b:
1590 case Mips::BI__builtin_msa_clei_u_h:
1591 case Mips::BI__builtin_msa_clei_u_w:
1592 case Mips::BI__builtin_msa_clei_u_d:
1593 case Mips::BI__builtin_msa_clti_u_b:
1594 case Mips::BI__builtin_msa_clti_u_h:
1595 case Mips::BI__builtin_msa_clti_u_w:
1596 case Mips::BI__builtin_msa_clti_u_d:
1597 case Mips::BI__builtin_msa_maxi_u_b:
1598 case Mips::BI__builtin_msa_maxi_u_h:
1599 case Mips::BI__builtin_msa_maxi_u_w:
1600 case Mips::BI__builtin_msa_maxi_u_d:
1601 case Mips::BI__builtin_msa_mini_u_b:
1602 case Mips::BI__builtin_msa_mini_u_h:
1603 case Mips::BI__builtin_msa_mini_u_w:
1604 case Mips::BI__builtin_msa_mini_u_d:
1605 case Mips::BI__builtin_msa_addvi_b:
1606 case Mips::BI__builtin_msa_addvi_h:
1607 case Mips::BI__builtin_msa_addvi_w:
1608 case Mips::BI__builtin_msa_addvi_d:
1609 case Mips::BI__builtin_msa_bclri_w:
1610 case Mips::BI__builtin_msa_bnegi_w:
1611 case Mips::BI__builtin_msa_bseti_w:
1612 case Mips::BI__builtin_msa_sat_s_w:
1613 case Mips::BI__builtin_msa_sat_u_w:
1614 case Mips::BI__builtin_msa_slli_w:
1615 case Mips::BI__builtin_msa_srai_w:
1616 case Mips::BI__builtin_msa_srari_w:
1617 case Mips::BI__builtin_msa_srli_w:
1618 case Mips::BI__builtin_msa_srlri_w:
1619 case Mips::BI__builtin_msa_subvi_b:
1620 case Mips::BI__builtin_msa_subvi_h:
1621 case Mips::BI__builtin_msa_subvi_w:
1622 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1623 case Mips::BI__builtin_msa_binsli_w:
1624 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1625 // These intrinsics take an unsigned 6 bit immediate.
1626 case Mips::BI__builtin_msa_bclri_d:
1627 case Mips::BI__builtin_msa_bnegi_d:
1628 case Mips::BI__builtin_msa_bseti_d:
1629 case Mips::BI__builtin_msa_sat_s_d:
1630 case Mips::BI__builtin_msa_sat_u_d:
1631 case Mips::BI__builtin_msa_slli_d:
1632 case Mips::BI__builtin_msa_srai_d:
1633 case Mips::BI__builtin_msa_srari_d:
1634 case Mips::BI__builtin_msa_srli_d:
1635 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1636 case Mips::BI__builtin_msa_binsli_d:
1637 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1638 // These intrinsics take a signed 5 bit immediate.
1639 case Mips::BI__builtin_msa_ceqi_b:
1640 case Mips::BI__builtin_msa_ceqi_h:
1641 case Mips::BI__builtin_msa_ceqi_w:
1642 case Mips::BI__builtin_msa_ceqi_d:
1643 case Mips::BI__builtin_msa_clti_s_b:
1644 case Mips::BI__builtin_msa_clti_s_h:
1645 case Mips::BI__builtin_msa_clti_s_w:
1646 case Mips::BI__builtin_msa_clti_s_d:
1647 case Mips::BI__builtin_msa_clei_s_b:
1648 case Mips::BI__builtin_msa_clei_s_h:
1649 case Mips::BI__builtin_msa_clei_s_w:
1650 case Mips::BI__builtin_msa_clei_s_d:
1651 case Mips::BI__builtin_msa_maxi_s_b:
1652 case Mips::BI__builtin_msa_maxi_s_h:
1653 case Mips::BI__builtin_msa_maxi_s_w:
1654 case Mips::BI__builtin_msa_maxi_s_d:
1655 case Mips::BI__builtin_msa_mini_s_b:
1656 case Mips::BI__builtin_msa_mini_s_h:
1657 case Mips::BI__builtin_msa_mini_s_w:
1658 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1659 // These intrinsics take an unsigned 8 bit immediate.
1660 case Mips::BI__builtin_msa_andi_b:
1661 case Mips::BI__builtin_msa_nori_b:
1662 case Mips::BI__builtin_msa_ori_b:
1663 case Mips::BI__builtin_msa_shf_b:
1664 case Mips::BI__builtin_msa_shf_h:
1665 case Mips::BI__builtin_msa_shf_w:
1666 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1667 case Mips::BI__builtin_msa_bseli_b:
1668 case Mips::BI__builtin_msa_bmnzi_b:
1669 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1670 // df/n format
1671 // These intrinsics take an unsigned 4 bit immediate.
1672 case Mips::BI__builtin_msa_copy_s_b:
1673 case Mips::BI__builtin_msa_copy_u_b:
1674 case Mips::BI__builtin_msa_insve_b:
1675 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001676 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1677 // These intrinsics take an unsigned 3 bit immediate.
1678 case Mips::BI__builtin_msa_copy_s_h:
1679 case Mips::BI__builtin_msa_copy_u_h:
1680 case Mips::BI__builtin_msa_insve_h:
1681 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001682 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1683 // These intrinsics take an unsigned 2 bit immediate.
1684 case Mips::BI__builtin_msa_copy_s_w:
1685 case Mips::BI__builtin_msa_copy_u_w:
1686 case Mips::BI__builtin_msa_insve_w:
1687 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001688 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1689 // These intrinsics take an unsigned 1 bit immediate.
1690 case Mips::BI__builtin_msa_copy_s_d:
1691 case Mips::BI__builtin_msa_copy_u_d:
1692 case Mips::BI__builtin_msa_insve_d:
1693 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001694 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1695 // Memory offsets and immediate loads.
1696 // These intrinsics take a signed 10 bit immediate.
Petar Jovanovic9b8b9e82017-03-31 16:16:43 +00001697 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001698 case Mips::BI__builtin_msa_ldi_h:
1699 case Mips::BI__builtin_msa_ldi_w:
1700 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1701 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1702 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1703 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1704 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1705 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1706 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1707 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1708 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001709 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001710
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001711 if (!m)
1712 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1713
1714 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1715 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001716}
1717
Kit Bartone50adcb2015-03-30 19:40:59 +00001718bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1719 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001720 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1721 BuiltinID == PPC::BI__builtin_divdeu ||
1722 BuiltinID == PPC::BI__builtin_bpermd;
1723 bool IsTarget64Bit = Context.getTargetInfo()
1724 .getTypeWidth(Context
1725 .getTargetInfo()
1726 .getIntPtrType()) == 64;
1727 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1728 BuiltinID == PPC::BI__builtin_divweu ||
1729 BuiltinID == PPC::BI__builtin_divde ||
1730 BuiltinID == PPC::BI__builtin_divdeu;
1731
1732 if (Is64BitBltin && !IsTarget64Bit)
1733 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1734 << TheCall->getSourceRange();
1735
1736 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1737 (BuiltinID == PPC::BI__builtin_bpermd &&
1738 !Context.getTargetInfo().hasFeature("bpermd")))
1739 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1740 << TheCall->getSourceRange();
1741
Kit Bartone50adcb2015-03-30 19:40:59 +00001742 switch (BuiltinID) {
1743 default: return false;
1744 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1745 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1746 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1747 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1748 case PPC::BI__builtin_tbegin:
1749 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1750 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1751 case PPC::BI__builtin_tabortwc:
1752 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1753 case PPC::BI__builtin_tabortwci:
1754 case PPC::BI__builtin_tabortdci:
1755 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1756 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
Tony Jiangbbc48e92017-05-24 15:13:32 +00001757 case PPC::BI__builtin_vsx_xxpermdi:
Tony Jiang9aa2c032017-05-24 15:54:13 +00001758 case PPC::BI__builtin_vsx_xxsldwi:
Tony Jiangbbc48e92017-05-24 15:13:32 +00001759 return SemaBuiltinVSX(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00001760 }
1761 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1762}
1763
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001764bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1765 CallExpr *TheCall) {
1766 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1767 Expr *Arg = TheCall->getArg(0);
1768 llvm::APSInt AbortCode(32);
1769 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1770 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1771 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1772 << Arg->getSourceRange();
1773 }
1774
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001775 // For intrinsics which take an immediate value as part of the instruction,
1776 // range check them here.
1777 unsigned i = 0, l = 0, u = 0;
1778 switch (BuiltinID) {
1779 default: return false;
1780 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1781 case SystemZ::BI__builtin_s390_verimb:
1782 case SystemZ::BI__builtin_s390_verimh:
1783 case SystemZ::BI__builtin_s390_verimf:
1784 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1785 case SystemZ::BI__builtin_s390_vfaeb:
1786 case SystemZ::BI__builtin_s390_vfaeh:
1787 case SystemZ::BI__builtin_s390_vfaef:
1788 case SystemZ::BI__builtin_s390_vfaebs:
1789 case SystemZ::BI__builtin_s390_vfaehs:
1790 case SystemZ::BI__builtin_s390_vfaefs:
1791 case SystemZ::BI__builtin_s390_vfaezb:
1792 case SystemZ::BI__builtin_s390_vfaezh:
1793 case SystemZ::BI__builtin_s390_vfaezf:
1794 case SystemZ::BI__builtin_s390_vfaezbs:
1795 case SystemZ::BI__builtin_s390_vfaezhs:
1796 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001797 case SystemZ::BI__builtin_s390_vfisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001798 case SystemZ::BI__builtin_s390_vfidb:
1799 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1800 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001801 case SystemZ::BI__builtin_s390_vftcisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001802 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1803 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1804 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1805 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1806 case SystemZ::BI__builtin_s390_vstrcb:
1807 case SystemZ::BI__builtin_s390_vstrch:
1808 case SystemZ::BI__builtin_s390_vstrcf:
1809 case SystemZ::BI__builtin_s390_vstrczb:
1810 case SystemZ::BI__builtin_s390_vstrczh:
1811 case SystemZ::BI__builtin_s390_vstrczf:
1812 case SystemZ::BI__builtin_s390_vstrcbs:
1813 case SystemZ::BI__builtin_s390_vstrchs:
1814 case SystemZ::BI__builtin_s390_vstrcfs:
1815 case SystemZ::BI__builtin_s390_vstrczbs:
1816 case SystemZ::BI__builtin_s390_vstrczhs:
1817 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001818 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
1819 case SystemZ::BI__builtin_s390_vfminsb:
1820 case SystemZ::BI__builtin_s390_vfmaxsb:
1821 case SystemZ::BI__builtin_s390_vfmindb:
1822 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001823 }
1824 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001825}
1826
Craig Topper5ba2c502015-11-07 08:08:31 +00001827/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1828/// This checks that the target supports __builtin_cpu_supports and
1829/// that the string argument is constant and valid.
1830static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1831 Expr *Arg = TheCall->getArg(0);
1832
1833 // Check if the argument is a string literal.
1834 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1835 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1836 << Arg->getSourceRange();
1837
1838 // Check the contents of the string.
1839 StringRef Feature =
1840 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1841 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1842 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1843 << Arg->getSourceRange();
1844 return false;
1845}
1846
Craig Toppera7e253e2016-09-23 04:48:31 +00001847// Check if the rounding mode is legal.
1848bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1849 // Indicates if this instruction has rounding control or just SAE.
1850 bool HasRC = false;
1851
1852 unsigned ArgNum = 0;
1853 switch (BuiltinID) {
1854 default:
1855 return false;
1856 case X86::BI__builtin_ia32_vcvttsd2si32:
1857 case X86::BI__builtin_ia32_vcvttsd2si64:
1858 case X86::BI__builtin_ia32_vcvttsd2usi32:
1859 case X86::BI__builtin_ia32_vcvttsd2usi64:
1860 case X86::BI__builtin_ia32_vcvttss2si32:
1861 case X86::BI__builtin_ia32_vcvttss2si64:
1862 case X86::BI__builtin_ia32_vcvttss2usi32:
1863 case X86::BI__builtin_ia32_vcvttss2usi64:
1864 ArgNum = 1;
1865 break;
1866 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1867 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1868 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1869 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1870 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1871 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1872 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1873 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1874 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1875 case X86::BI__builtin_ia32_exp2pd_mask:
1876 case X86::BI__builtin_ia32_exp2ps_mask:
1877 case X86::BI__builtin_ia32_getexppd512_mask:
1878 case X86::BI__builtin_ia32_getexpps512_mask:
1879 case X86::BI__builtin_ia32_rcp28pd_mask:
1880 case X86::BI__builtin_ia32_rcp28ps_mask:
1881 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1882 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1883 case X86::BI__builtin_ia32_vcomisd:
1884 case X86::BI__builtin_ia32_vcomiss:
1885 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1886 ArgNum = 3;
1887 break;
1888 case X86::BI__builtin_ia32_cmppd512_mask:
1889 case X86::BI__builtin_ia32_cmpps512_mask:
1890 case X86::BI__builtin_ia32_cmpsd_mask:
1891 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001892 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001893 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1894 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001895 case X86::BI__builtin_ia32_maxpd512_mask:
1896 case X86::BI__builtin_ia32_maxps512_mask:
1897 case X86::BI__builtin_ia32_maxsd_round_mask:
1898 case X86::BI__builtin_ia32_maxss_round_mask:
1899 case X86::BI__builtin_ia32_minpd512_mask:
1900 case X86::BI__builtin_ia32_minps512_mask:
1901 case X86::BI__builtin_ia32_minsd_round_mask:
1902 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001903 case X86::BI__builtin_ia32_rcp28sd_round_mask:
1904 case X86::BI__builtin_ia32_rcp28ss_round_mask:
1905 case X86::BI__builtin_ia32_reducepd512_mask:
1906 case X86::BI__builtin_ia32_reduceps512_mask:
1907 case X86::BI__builtin_ia32_rndscalepd_mask:
1908 case X86::BI__builtin_ia32_rndscaleps_mask:
1909 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1910 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1911 ArgNum = 4;
1912 break;
1913 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001914 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001915 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001916 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001917 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001918 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001919 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001920 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001921 case X86::BI__builtin_ia32_rangepd512_mask:
1922 case X86::BI__builtin_ia32_rangeps512_mask:
1923 case X86::BI__builtin_ia32_rangesd128_round_mask:
1924 case X86::BI__builtin_ia32_rangess128_round_mask:
1925 case X86::BI__builtin_ia32_reducesd_mask:
1926 case X86::BI__builtin_ia32_reducess_mask:
1927 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1928 case X86::BI__builtin_ia32_rndscaless_round_mask:
1929 ArgNum = 5;
1930 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00001931 case X86::BI__builtin_ia32_vcvtsd2si64:
1932 case X86::BI__builtin_ia32_vcvtsd2si32:
1933 case X86::BI__builtin_ia32_vcvtsd2usi32:
1934 case X86::BI__builtin_ia32_vcvtsd2usi64:
1935 case X86::BI__builtin_ia32_vcvtss2si32:
1936 case X86::BI__builtin_ia32_vcvtss2si64:
1937 case X86::BI__builtin_ia32_vcvtss2usi32:
1938 case X86::BI__builtin_ia32_vcvtss2usi64:
1939 ArgNum = 1;
1940 HasRC = true;
1941 break;
Craig Topper8e066312016-11-07 07:01:09 +00001942 case X86::BI__builtin_ia32_cvtsi2sd64:
1943 case X86::BI__builtin_ia32_cvtsi2ss32:
1944 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00001945 case X86::BI__builtin_ia32_cvtusi2sd64:
1946 case X86::BI__builtin_ia32_cvtusi2ss32:
1947 case X86::BI__builtin_ia32_cvtusi2ss64:
1948 ArgNum = 2;
1949 HasRC = true;
1950 break;
1951 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1952 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1953 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1954 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1955 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1956 case X86::BI__builtin_ia32_cvtps2qq512_mask:
1957 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1958 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1959 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1960 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1961 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001962 case X86::BI__builtin_ia32_sqrtpd512_mask:
1963 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001964 ArgNum = 3;
1965 HasRC = true;
1966 break;
1967 case X86::BI__builtin_ia32_addpd512_mask:
1968 case X86::BI__builtin_ia32_addps512_mask:
1969 case X86::BI__builtin_ia32_divpd512_mask:
1970 case X86::BI__builtin_ia32_divps512_mask:
1971 case X86::BI__builtin_ia32_mulpd512_mask:
1972 case X86::BI__builtin_ia32_mulps512_mask:
1973 case X86::BI__builtin_ia32_subpd512_mask:
1974 case X86::BI__builtin_ia32_subps512_mask:
1975 case X86::BI__builtin_ia32_addss_round_mask:
1976 case X86::BI__builtin_ia32_addsd_round_mask:
1977 case X86::BI__builtin_ia32_divss_round_mask:
1978 case X86::BI__builtin_ia32_divsd_round_mask:
1979 case X86::BI__builtin_ia32_mulss_round_mask:
1980 case X86::BI__builtin_ia32_mulsd_round_mask:
1981 case X86::BI__builtin_ia32_subss_round_mask:
1982 case X86::BI__builtin_ia32_subsd_round_mask:
1983 case X86::BI__builtin_ia32_scalefpd512_mask:
1984 case X86::BI__builtin_ia32_scalefps512_mask:
1985 case X86::BI__builtin_ia32_scalefsd_round_mask:
1986 case X86::BI__builtin_ia32_scalefss_round_mask:
1987 case X86::BI__builtin_ia32_getmantpd512_mask:
1988 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001989 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
1990 case X86::BI__builtin_ia32_sqrtsd_round_mask:
1991 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001992 case X86::BI__builtin_ia32_vfmaddpd512_mask:
1993 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1994 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1995 case X86::BI__builtin_ia32_vfmaddps512_mask:
1996 case X86::BI__builtin_ia32_vfmaddps512_mask3:
1997 case X86::BI__builtin_ia32_vfmaddps512_maskz:
1998 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1999 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2000 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2001 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2002 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2003 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2004 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2005 case X86::BI__builtin_ia32_vfmsubps512_mask3:
2006 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2007 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
2008 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
2009 case X86::BI__builtin_ia32_vfnmaddps512_mask:
2010 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
2011 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
2012 case X86::BI__builtin_ia32_vfnmsubps512_mask:
2013 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
2014 case X86::BI__builtin_ia32_vfmaddsd3_mask:
2015 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2016 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2017 case X86::BI__builtin_ia32_vfmaddss3_mask:
2018 case X86::BI__builtin_ia32_vfmaddss3_maskz:
2019 case X86::BI__builtin_ia32_vfmaddss3_mask3:
2020 ArgNum = 4;
2021 HasRC = true;
2022 break;
2023 case X86::BI__builtin_ia32_getmantsd_round_mask:
2024 case X86::BI__builtin_ia32_getmantss_round_mask:
2025 ArgNum = 5;
2026 HasRC = true;
2027 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00002028 }
2029
2030 llvm::APSInt Result;
2031
2032 // We can't check the value of a dependent argument.
2033 Expr *Arg = TheCall->getArg(ArgNum);
2034 if (Arg->isTypeDependent() || Arg->isValueDependent())
2035 return false;
2036
2037 // Check constant-ness first.
2038 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2039 return true;
2040
2041 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2042 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2043 // combined with ROUND_NO_EXC.
2044 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2045 Result == 8/*ROUND_NO_EXC*/ ||
2046 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2047 return false;
2048
2049 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2050 << Arg->getSourceRange();
2051}
2052
Craig Topperdf5beb22017-03-13 17:16:50 +00002053// Check if the gather/scatter scale is legal.
2054bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2055 CallExpr *TheCall) {
2056 unsigned ArgNum = 0;
2057 switch (BuiltinID) {
2058 default:
2059 return false;
2060 case X86::BI__builtin_ia32_gatherpfdpd:
2061 case X86::BI__builtin_ia32_gatherpfdps:
2062 case X86::BI__builtin_ia32_gatherpfqpd:
2063 case X86::BI__builtin_ia32_gatherpfqps:
2064 case X86::BI__builtin_ia32_scatterpfdpd:
2065 case X86::BI__builtin_ia32_scatterpfdps:
2066 case X86::BI__builtin_ia32_scatterpfqpd:
2067 case X86::BI__builtin_ia32_scatterpfqps:
2068 ArgNum = 3;
2069 break;
2070 case X86::BI__builtin_ia32_gatherd_pd:
2071 case X86::BI__builtin_ia32_gatherd_pd256:
2072 case X86::BI__builtin_ia32_gatherq_pd:
2073 case X86::BI__builtin_ia32_gatherq_pd256:
2074 case X86::BI__builtin_ia32_gatherd_ps:
2075 case X86::BI__builtin_ia32_gatherd_ps256:
2076 case X86::BI__builtin_ia32_gatherq_ps:
2077 case X86::BI__builtin_ia32_gatherq_ps256:
2078 case X86::BI__builtin_ia32_gatherd_q:
2079 case X86::BI__builtin_ia32_gatherd_q256:
2080 case X86::BI__builtin_ia32_gatherq_q:
2081 case X86::BI__builtin_ia32_gatherq_q256:
2082 case X86::BI__builtin_ia32_gatherd_d:
2083 case X86::BI__builtin_ia32_gatherd_d256:
2084 case X86::BI__builtin_ia32_gatherq_d:
2085 case X86::BI__builtin_ia32_gatherq_d256:
2086 case X86::BI__builtin_ia32_gather3div2df:
2087 case X86::BI__builtin_ia32_gather3div2di:
2088 case X86::BI__builtin_ia32_gather3div4df:
2089 case X86::BI__builtin_ia32_gather3div4di:
2090 case X86::BI__builtin_ia32_gather3div4sf:
2091 case X86::BI__builtin_ia32_gather3div4si:
2092 case X86::BI__builtin_ia32_gather3div8sf:
2093 case X86::BI__builtin_ia32_gather3div8si:
2094 case X86::BI__builtin_ia32_gather3siv2df:
2095 case X86::BI__builtin_ia32_gather3siv2di:
2096 case X86::BI__builtin_ia32_gather3siv4df:
2097 case X86::BI__builtin_ia32_gather3siv4di:
2098 case X86::BI__builtin_ia32_gather3siv4sf:
2099 case X86::BI__builtin_ia32_gather3siv4si:
2100 case X86::BI__builtin_ia32_gather3siv8sf:
2101 case X86::BI__builtin_ia32_gather3siv8si:
2102 case X86::BI__builtin_ia32_gathersiv8df:
2103 case X86::BI__builtin_ia32_gathersiv16sf:
2104 case X86::BI__builtin_ia32_gatherdiv8df:
2105 case X86::BI__builtin_ia32_gatherdiv16sf:
2106 case X86::BI__builtin_ia32_gathersiv8di:
2107 case X86::BI__builtin_ia32_gathersiv16si:
2108 case X86::BI__builtin_ia32_gatherdiv8di:
2109 case X86::BI__builtin_ia32_gatherdiv16si:
2110 case X86::BI__builtin_ia32_scatterdiv2df:
2111 case X86::BI__builtin_ia32_scatterdiv2di:
2112 case X86::BI__builtin_ia32_scatterdiv4df:
2113 case X86::BI__builtin_ia32_scatterdiv4di:
2114 case X86::BI__builtin_ia32_scatterdiv4sf:
2115 case X86::BI__builtin_ia32_scatterdiv4si:
2116 case X86::BI__builtin_ia32_scatterdiv8sf:
2117 case X86::BI__builtin_ia32_scatterdiv8si:
2118 case X86::BI__builtin_ia32_scattersiv2df:
2119 case X86::BI__builtin_ia32_scattersiv2di:
2120 case X86::BI__builtin_ia32_scattersiv4df:
2121 case X86::BI__builtin_ia32_scattersiv4di:
2122 case X86::BI__builtin_ia32_scattersiv4sf:
2123 case X86::BI__builtin_ia32_scattersiv4si:
2124 case X86::BI__builtin_ia32_scattersiv8sf:
2125 case X86::BI__builtin_ia32_scattersiv8si:
2126 case X86::BI__builtin_ia32_scattersiv8df:
2127 case X86::BI__builtin_ia32_scattersiv16sf:
2128 case X86::BI__builtin_ia32_scatterdiv8df:
2129 case X86::BI__builtin_ia32_scatterdiv16sf:
2130 case X86::BI__builtin_ia32_scattersiv8di:
2131 case X86::BI__builtin_ia32_scattersiv16si:
2132 case X86::BI__builtin_ia32_scatterdiv8di:
2133 case X86::BI__builtin_ia32_scatterdiv16si:
2134 ArgNum = 4;
2135 break;
2136 }
2137
2138 llvm::APSInt Result;
2139
2140 // We can't check the value of a dependent argument.
2141 Expr *Arg = TheCall->getArg(ArgNum);
2142 if (Arg->isTypeDependent() || Arg->isValueDependent())
2143 return false;
2144
2145 // Check constant-ness first.
2146 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2147 return true;
2148
2149 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2150 return false;
2151
2152 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2153 << Arg->getSourceRange();
2154}
2155
Craig Topperf0ddc892016-09-23 04:48:27 +00002156bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2157 if (BuiltinID == X86::BI__builtin_cpu_supports)
2158 return SemaBuiltinCpuSupports(*this, TheCall);
2159
Craig Toppera7e253e2016-09-23 04:48:31 +00002160 // If the intrinsic has rounding or SAE make sure its valid.
2161 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2162 return true;
2163
Craig Topperdf5beb22017-03-13 17:16:50 +00002164 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2165 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2166 return true;
2167
Craig Topperf0ddc892016-09-23 04:48:27 +00002168 // For intrinsics which take an immediate value as part of the instruction,
2169 // range check them here.
2170 int i = 0, l = 0, u = 0;
2171 switch (BuiltinID) {
2172 default:
2173 return false;
Richard Trieucc3949d2016-02-18 22:34:54 +00002174 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00002175 i = 1; l = 0; u = 3;
2176 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002177 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00002178 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2179 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2180 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2181 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002182 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002183 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002184 case X86::BI__builtin_ia32_vpermil2pd:
2185 case X86::BI__builtin_ia32_vpermil2pd256:
2186 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002187 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002188 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002189 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002190 case X86::BI__builtin_ia32_cmpb128_mask:
2191 case X86::BI__builtin_ia32_cmpw128_mask:
2192 case X86::BI__builtin_ia32_cmpd128_mask:
2193 case X86::BI__builtin_ia32_cmpq128_mask:
2194 case X86::BI__builtin_ia32_cmpb256_mask:
2195 case X86::BI__builtin_ia32_cmpw256_mask:
2196 case X86::BI__builtin_ia32_cmpd256_mask:
2197 case X86::BI__builtin_ia32_cmpq256_mask:
2198 case X86::BI__builtin_ia32_cmpb512_mask:
2199 case X86::BI__builtin_ia32_cmpw512_mask:
2200 case X86::BI__builtin_ia32_cmpd512_mask:
2201 case X86::BI__builtin_ia32_cmpq512_mask:
2202 case X86::BI__builtin_ia32_ucmpb128_mask:
2203 case X86::BI__builtin_ia32_ucmpw128_mask:
2204 case X86::BI__builtin_ia32_ucmpd128_mask:
2205 case X86::BI__builtin_ia32_ucmpq128_mask:
2206 case X86::BI__builtin_ia32_ucmpb256_mask:
2207 case X86::BI__builtin_ia32_ucmpw256_mask:
2208 case X86::BI__builtin_ia32_ucmpd256_mask:
2209 case X86::BI__builtin_ia32_ucmpq256_mask:
2210 case X86::BI__builtin_ia32_ucmpb512_mask:
2211 case X86::BI__builtin_ia32_ucmpw512_mask:
2212 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002213 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002214 case X86::BI__builtin_ia32_vpcomub:
2215 case X86::BI__builtin_ia32_vpcomuw:
2216 case X86::BI__builtin_ia32_vpcomud:
2217 case X86::BI__builtin_ia32_vpcomuq:
2218 case X86::BI__builtin_ia32_vpcomb:
2219 case X86::BI__builtin_ia32_vpcomw:
2220 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002221 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00002222 i = 2; l = 0; u = 7;
2223 break;
2224 case X86::BI__builtin_ia32_roundps:
2225 case X86::BI__builtin_ia32_roundpd:
2226 case X86::BI__builtin_ia32_roundps256:
2227 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002228 i = 1; l = 0; u = 15;
2229 break;
2230 case X86::BI__builtin_ia32_roundss:
2231 case X86::BI__builtin_ia32_roundsd:
2232 case X86::BI__builtin_ia32_rangepd128_mask:
2233 case X86::BI__builtin_ia32_rangepd256_mask:
2234 case X86::BI__builtin_ia32_rangepd512_mask:
2235 case X86::BI__builtin_ia32_rangeps128_mask:
2236 case X86::BI__builtin_ia32_rangeps256_mask:
2237 case X86::BI__builtin_ia32_rangeps512_mask:
2238 case X86::BI__builtin_ia32_getmantsd_round_mask:
2239 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002240 i = 2; l = 0; u = 15;
2241 break;
2242 case X86::BI__builtin_ia32_cmpps:
2243 case X86::BI__builtin_ia32_cmpss:
2244 case X86::BI__builtin_ia32_cmppd:
2245 case X86::BI__builtin_ia32_cmpsd:
2246 case X86::BI__builtin_ia32_cmpps256:
2247 case X86::BI__builtin_ia32_cmppd256:
2248 case X86::BI__builtin_ia32_cmpps128_mask:
2249 case X86::BI__builtin_ia32_cmppd128_mask:
2250 case X86::BI__builtin_ia32_cmpps256_mask:
2251 case X86::BI__builtin_ia32_cmppd256_mask:
2252 case X86::BI__builtin_ia32_cmpps512_mask:
2253 case X86::BI__builtin_ia32_cmppd512_mask:
2254 case X86::BI__builtin_ia32_cmpsd_mask:
2255 case X86::BI__builtin_ia32_cmpss_mask:
2256 i = 2; l = 0; u = 31;
2257 break;
2258 case X86::BI__builtin_ia32_xabort:
2259 i = 0; l = -128; u = 255;
2260 break;
2261 case X86::BI__builtin_ia32_pshufw:
2262 case X86::BI__builtin_ia32_aeskeygenassist128:
2263 i = 1; l = -128; u = 255;
2264 break;
2265 case X86::BI__builtin_ia32_vcvtps2ph:
2266 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper39c87102016-05-18 03:18:12 +00002267 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2268 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2269 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2270 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2271 case X86::BI__builtin_ia32_rndscaleps_mask:
2272 case X86::BI__builtin_ia32_rndscalepd_mask:
2273 case X86::BI__builtin_ia32_reducepd128_mask:
2274 case X86::BI__builtin_ia32_reducepd256_mask:
2275 case X86::BI__builtin_ia32_reducepd512_mask:
2276 case X86::BI__builtin_ia32_reduceps128_mask:
2277 case X86::BI__builtin_ia32_reduceps256_mask:
2278 case X86::BI__builtin_ia32_reduceps512_mask:
2279 case X86::BI__builtin_ia32_prold512_mask:
2280 case X86::BI__builtin_ia32_prolq512_mask:
2281 case X86::BI__builtin_ia32_prold128_mask:
2282 case X86::BI__builtin_ia32_prold256_mask:
2283 case X86::BI__builtin_ia32_prolq128_mask:
2284 case X86::BI__builtin_ia32_prolq256_mask:
2285 case X86::BI__builtin_ia32_prord128_mask:
2286 case X86::BI__builtin_ia32_prord256_mask:
2287 case X86::BI__builtin_ia32_prorq128_mask:
2288 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002289 case X86::BI__builtin_ia32_fpclasspd128_mask:
2290 case X86::BI__builtin_ia32_fpclasspd256_mask:
2291 case X86::BI__builtin_ia32_fpclassps128_mask:
2292 case X86::BI__builtin_ia32_fpclassps256_mask:
2293 case X86::BI__builtin_ia32_fpclassps512_mask:
2294 case X86::BI__builtin_ia32_fpclasspd512_mask:
2295 case X86::BI__builtin_ia32_fpclasssd_mask:
2296 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002297 i = 1; l = 0; u = 255;
2298 break;
2299 case X86::BI__builtin_ia32_palignr:
2300 case X86::BI__builtin_ia32_insertps128:
2301 case X86::BI__builtin_ia32_dpps:
2302 case X86::BI__builtin_ia32_dppd:
2303 case X86::BI__builtin_ia32_dpps256:
2304 case X86::BI__builtin_ia32_mpsadbw128:
2305 case X86::BI__builtin_ia32_mpsadbw256:
2306 case X86::BI__builtin_ia32_pcmpistrm128:
2307 case X86::BI__builtin_ia32_pcmpistri128:
2308 case X86::BI__builtin_ia32_pcmpistria128:
2309 case X86::BI__builtin_ia32_pcmpistric128:
2310 case X86::BI__builtin_ia32_pcmpistrio128:
2311 case X86::BI__builtin_ia32_pcmpistris128:
2312 case X86::BI__builtin_ia32_pcmpistriz128:
2313 case X86::BI__builtin_ia32_pclmulqdq128:
2314 case X86::BI__builtin_ia32_vperm2f128_pd256:
2315 case X86::BI__builtin_ia32_vperm2f128_ps256:
2316 case X86::BI__builtin_ia32_vperm2f128_si256:
2317 case X86::BI__builtin_ia32_permti256:
2318 i = 2; l = -128; u = 255;
2319 break;
2320 case X86::BI__builtin_ia32_palignr128:
2321 case X86::BI__builtin_ia32_palignr256:
Craig Topper39c87102016-05-18 03:18:12 +00002322 case X86::BI__builtin_ia32_palignr512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002323 case X86::BI__builtin_ia32_vcomisd:
2324 case X86::BI__builtin_ia32_vcomiss:
2325 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2326 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2327 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2328 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002329 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2330 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2331 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2332 i = 2; l = 0; u = 255;
2333 break;
2334 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2335 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2336 case X86::BI__builtin_ia32_fixupimmps512_mask:
2337 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2338 case X86::BI__builtin_ia32_fixupimmsd_mask:
2339 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2340 case X86::BI__builtin_ia32_fixupimmss_mask:
2341 case X86::BI__builtin_ia32_fixupimmss_maskz:
2342 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2343 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2344 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2345 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2346 case X86::BI__builtin_ia32_fixupimmps128_mask:
2347 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2348 case X86::BI__builtin_ia32_fixupimmps256_mask:
2349 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2350 case X86::BI__builtin_ia32_pternlogd512_mask:
2351 case X86::BI__builtin_ia32_pternlogd512_maskz:
2352 case X86::BI__builtin_ia32_pternlogq512_mask:
2353 case X86::BI__builtin_ia32_pternlogq512_maskz:
2354 case X86::BI__builtin_ia32_pternlogd128_mask:
2355 case X86::BI__builtin_ia32_pternlogd128_maskz:
2356 case X86::BI__builtin_ia32_pternlogd256_mask:
2357 case X86::BI__builtin_ia32_pternlogd256_maskz:
2358 case X86::BI__builtin_ia32_pternlogq128_mask:
2359 case X86::BI__builtin_ia32_pternlogq128_maskz:
2360 case X86::BI__builtin_ia32_pternlogq256_mask:
2361 case X86::BI__builtin_ia32_pternlogq256_maskz:
2362 i = 3; l = 0; u = 255;
2363 break;
Craig Topper9625db02017-03-12 22:19:10 +00002364 case X86::BI__builtin_ia32_gatherpfdpd:
2365 case X86::BI__builtin_ia32_gatherpfdps:
2366 case X86::BI__builtin_ia32_gatherpfqpd:
2367 case X86::BI__builtin_ia32_gatherpfqps:
2368 case X86::BI__builtin_ia32_scatterpfdpd:
2369 case X86::BI__builtin_ia32_scatterpfdps:
2370 case X86::BI__builtin_ia32_scatterpfqpd:
2371 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00002372 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00002373 break;
Craig Topper39c87102016-05-18 03:18:12 +00002374 case X86::BI__builtin_ia32_pcmpestrm128:
2375 case X86::BI__builtin_ia32_pcmpestri128:
2376 case X86::BI__builtin_ia32_pcmpestria128:
2377 case X86::BI__builtin_ia32_pcmpestric128:
2378 case X86::BI__builtin_ia32_pcmpestrio128:
2379 case X86::BI__builtin_ia32_pcmpestris128:
2380 case X86::BI__builtin_ia32_pcmpestriz128:
2381 i = 4; l = -128; u = 255;
2382 break;
2383 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2384 case X86::BI__builtin_ia32_rndscaless_round_mask:
2385 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002386 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002387 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002388 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002389}
2390
Richard Smith55ce3522012-06-25 20:30:08 +00002391/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2392/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2393/// Returns true when the format fits the function and the FormatStringInfo has
2394/// been populated.
2395bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2396 FormatStringInfo *FSI) {
2397 FSI->HasVAListArg = Format->getFirstArg() == 0;
2398 FSI->FormatIdx = Format->getFormatIdx() - 1;
2399 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002400
Richard Smith55ce3522012-06-25 20:30:08 +00002401 // The way the format attribute works in GCC, the implicit this argument
2402 // of member functions is counted. However, it doesn't appear in our own
2403 // lists, so decrement format_idx in that case.
2404 if (IsCXXMember) {
2405 if(FSI->FormatIdx == 0)
2406 return false;
2407 --FSI->FormatIdx;
2408 if (FSI->FirstDataArg != 0)
2409 --FSI->FirstDataArg;
2410 }
2411 return true;
2412}
Mike Stump11289f42009-09-09 15:08:12 +00002413
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002414/// Checks if a the given expression evaluates to null.
2415///
2416/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002417static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002418 // If the expression has non-null type, it doesn't evaluate to null.
2419 if (auto nullability
2420 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2421 if (*nullability == NullabilityKind::NonNull)
2422 return false;
2423 }
2424
Ted Kremeneka146db32014-01-17 06:24:47 +00002425 // As a special case, transparent unions initialized with zero are
2426 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002427 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002428 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2429 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002430 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002431 if (const InitListExpr *ILE =
2432 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002433 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002434 }
2435
2436 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002437 return (!Expr->isValueDependent() &&
2438 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2439 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002440}
2441
2442static void CheckNonNullArgument(Sema &S,
2443 const Expr *ArgExpr,
2444 SourceLocation CallSiteLoc) {
2445 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002446 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2447 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002448}
2449
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002450bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2451 FormatStringInfo FSI;
2452 if ((GetFormatStringType(Format) == FST_NSString) &&
2453 getFormatStringInfo(Format, false, &FSI)) {
2454 Idx = FSI.FormatIdx;
2455 return true;
2456 }
2457 return false;
2458}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002459/// \brief Diagnose use of %s directive in an NSString which is being passed
2460/// as formatting string to formatting method.
2461static void
2462DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2463 const NamedDecl *FDecl,
2464 Expr **Args,
2465 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002466 unsigned Idx = 0;
2467 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002468 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2469 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002470 Idx = 2;
2471 Format = true;
2472 }
2473 else
2474 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2475 if (S.GetFormatNSStringIdx(I, Idx)) {
2476 Format = true;
2477 break;
2478 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002479 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002480 if (!Format || NumArgs <= Idx)
2481 return;
2482 const Expr *FormatExpr = Args[Idx];
2483 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2484 FormatExpr = CSCE->getSubExpr();
2485 const StringLiteral *FormatString;
2486 if (const ObjCStringLiteral *OSL =
2487 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2488 FormatString = OSL->getString();
2489 else
2490 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2491 if (!FormatString)
2492 return;
2493 if (S.FormatStringHasSArg(FormatString)) {
2494 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2495 << "%s" << 1 << 1;
2496 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2497 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002498 }
2499}
2500
Douglas Gregorb4866e82015-06-19 18:13:19 +00002501/// Determine whether the given type has a non-null nullability annotation.
2502static bool isNonNullType(ASTContext &ctx, QualType type) {
2503 if (auto nullability = type->getNullability(ctx))
2504 return *nullability == NullabilityKind::NonNull;
2505
2506 return false;
2507}
2508
Ted Kremenek2bc73332014-01-17 06:24:43 +00002509static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002510 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002511 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002512 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002513 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002514 assert((FDecl || Proto) && "Need a function declaration or prototype");
2515
Ted Kremenek9aedc152014-01-17 06:24:56 +00002516 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002517 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002518 if (FDecl) {
2519 // Handle the nonnull attribute on the function/method declaration itself.
2520 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2521 if (!NonNull->args_size()) {
2522 // Easy case: all pointer arguments are nonnull.
2523 for (const auto *Arg : Args)
2524 if (S.isValidPointerAttrType(Arg->getType()))
2525 CheckNonNullArgument(S, Arg, CallSiteLoc);
2526 return;
2527 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002528
Douglas Gregorb4866e82015-06-19 18:13:19 +00002529 for (unsigned Val : NonNull->args()) {
2530 if (Val >= Args.size())
2531 continue;
2532 if (NonNullArgs.empty())
2533 NonNullArgs.resize(Args.size());
2534 NonNullArgs.set(Val);
2535 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002536 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002537 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002538
Douglas Gregorb4866e82015-06-19 18:13:19 +00002539 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2540 // Handle the nonnull attribute on the parameters of the
2541 // function/method.
2542 ArrayRef<ParmVarDecl*> parms;
2543 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2544 parms = FD->parameters();
2545 else
2546 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2547
2548 unsigned ParamIndex = 0;
2549 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2550 I != E; ++I, ++ParamIndex) {
2551 const ParmVarDecl *PVD = *I;
2552 if (PVD->hasAttr<NonNullAttr>() ||
2553 isNonNullType(S.Context, PVD->getType())) {
2554 if (NonNullArgs.empty())
2555 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002556
Douglas Gregorb4866e82015-06-19 18:13:19 +00002557 NonNullArgs.set(ParamIndex);
2558 }
2559 }
2560 } else {
2561 // If we have a non-function, non-method declaration but no
2562 // function prototype, try to dig out the function prototype.
2563 if (!Proto) {
2564 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2565 QualType type = VD->getType().getNonReferenceType();
2566 if (auto pointerType = type->getAs<PointerType>())
2567 type = pointerType->getPointeeType();
2568 else if (auto blockType = type->getAs<BlockPointerType>())
2569 type = blockType->getPointeeType();
2570 // FIXME: data member pointers?
2571
2572 // Dig out the function prototype, if there is one.
2573 Proto = type->getAs<FunctionProtoType>();
2574 }
2575 }
2576
2577 // Fill in non-null argument information from the nullability
2578 // information on the parameter types (if we have them).
2579 if (Proto) {
2580 unsigned Index = 0;
2581 for (auto paramType : Proto->getParamTypes()) {
2582 if (isNonNullType(S.Context, paramType)) {
2583 if (NonNullArgs.empty())
2584 NonNullArgs.resize(Args.size());
2585
2586 NonNullArgs.set(Index);
2587 }
2588
2589 ++Index;
2590 }
2591 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002592 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002593
Douglas Gregorb4866e82015-06-19 18:13:19 +00002594 // Check for non-null arguments.
2595 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2596 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002597 if (NonNullArgs[ArgIndex])
2598 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002599 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002600}
2601
Richard Smith55ce3522012-06-25 20:30:08 +00002602/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00002603/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2604/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002605void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00002606 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2607 bool IsMemberFunction, SourceLocation Loc,
2608 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002609 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002610 if (CurContext->isDependentContext())
2611 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002612
Ted Kremenekb8176da2010-09-09 04:33:05 +00002613 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002614 llvm::SmallBitVector CheckedVarArgs;
2615 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002616 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002617 // Only create vector if there are format attributes.
2618 CheckedVarArgs.resize(Args.size());
2619
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002620 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002621 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002622 }
Richard Smithd7293d72013-08-05 18:49:43 +00002623 }
Richard Smith55ce3522012-06-25 20:30:08 +00002624
2625 // Refuse POD arguments that weren't caught by the format string
2626 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00002627 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2628 if (CallType != VariadicDoesNotApply &&
2629 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002630 unsigned NumParams = Proto ? Proto->getNumParams()
2631 : FDecl && isa<FunctionDecl>(FDecl)
2632 ? cast<FunctionDecl>(FDecl)->getNumParams()
2633 : FDecl && isa<ObjCMethodDecl>(FDecl)
2634 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2635 : 0;
2636
Alp Toker9cacbab2014-01-20 20:26:09 +00002637 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002638 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002639 if (const Expr *Arg = Args[ArgIdx]) {
2640 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2641 checkVariadicArgument(Arg, CallType);
2642 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002643 }
Richard Smithd7293d72013-08-05 18:49:43 +00002644 }
Mike Stump11289f42009-09-09 15:08:12 +00002645
Douglas Gregorb4866e82015-06-19 18:13:19 +00002646 if (FDecl || Proto) {
2647 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002648
Richard Trieu41bc0992013-06-22 00:20:41 +00002649 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002650 if (FDecl) {
2651 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2652 CheckArgumentWithTypeTag(I, Args.data());
2653 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002654 }
George Burgess IVce6284b2017-01-28 02:19:40 +00002655
2656 if (FD)
2657 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00002658}
2659
2660/// CheckConstructorCall - Check a constructor call for correctness and safety
2661/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002662void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2663 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002664 const FunctionProtoType *Proto,
2665 SourceLocation Loc) {
2666 VariadicCallType CallType =
2667 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00002668 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2669 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002670}
2671
2672/// CheckFunctionCall - Check a direct function call for various correctness
2673/// and safety properties not strictly enforced by the C type system.
2674bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2675 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002676 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2677 isa<CXXMethodDecl>(FDecl);
2678 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2679 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002680 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2681 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002682 Expr** Args = TheCall->getArgs();
2683 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00002684
2685 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00002686 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002687 // If this is a call to a member operator, hide the first argument
2688 // from checkCall.
2689 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00002690 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00002691 ++Args;
2692 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00002693 } else if (IsMemberFunction)
2694 ImplicitThis =
2695 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2696
2697 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002698 IsMemberFunction, TheCall->getRParenLoc(),
2699 TheCall->getCallee()->getSourceRange(), CallType);
2700
2701 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2702 // None of the checks below are needed for functions that don't have
2703 // simple names (e.g., C++ conversion functions).
2704 if (!FnInfo)
2705 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002706
Richard Trieua7f30b12016-12-06 01:42:28 +00002707 CheckAbsoluteValueFunction(TheCall, FDecl);
2708 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00002709
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002710 if (getLangOpts().ObjC1)
2711 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002712
Anna Zaks22122702012-01-17 00:37:07 +00002713 unsigned CMId = FDecl->getMemoryFunctionKind();
2714 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002715 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002716
Anna Zaks201d4892012-01-13 21:52:01 +00002717 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002718 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002719 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002720 else if (CMId == Builtin::BIstrncat)
2721 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002722 else
Anna Zaks22122702012-01-17 00:37:07 +00002723 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002724
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002725 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002726}
2727
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002728bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002729 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002730 VariadicCallType CallType =
2731 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002732
George Burgess IVce6284b2017-01-28 02:19:40 +00002733 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2734 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002735 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002736
2737 return false;
2738}
2739
Richard Trieu664c4c62013-06-20 21:03:13 +00002740bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2741 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002742 QualType Ty;
2743 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002744 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002745 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002746 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002747 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002748 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002749
Douglas Gregorb4866e82015-06-19 18:13:19 +00002750 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2751 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002752 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002753
Richard Trieu664c4c62013-06-20 21:03:13 +00002754 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002755 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002756 CallType = VariadicDoesNotApply;
2757 } else if (Ty->isBlockPointerType()) {
2758 CallType = VariadicBlock;
2759 } else { // Ty->isFunctionPointerType()
2760 CallType = VariadicFunction;
2761 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002762
George Burgess IVce6284b2017-01-28 02:19:40 +00002763 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002764 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2765 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002766 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002767
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002768 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002769}
2770
Richard Trieu41bc0992013-06-22 00:20:41 +00002771/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2772/// such as function pointers returned from functions.
2773bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002774 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002775 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00002776 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002777 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002778 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002779 TheCall->getCallee()->getSourceRange(), CallType);
2780
2781 return false;
2782}
2783
Tim Northovere94a34c2014-03-11 10:49:14 +00002784static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002785 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002786 return false;
2787
JF Bastiendda2cb12016-04-18 18:01:49 +00002788 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002789 switch (Op) {
2790 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00002791 case AtomicExpr::AO__opencl_atomic_init:
Tim Northovere94a34c2014-03-11 10:49:14 +00002792 llvm_unreachable("There is no ordering argument for an init");
2793
2794 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00002795 case AtomicExpr::AO__opencl_atomic_load:
Tim Northovere94a34c2014-03-11 10:49:14 +00002796 case AtomicExpr::AO__atomic_load_n:
2797 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002798 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2799 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002800
2801 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00002802 case AtomicExpr::AO__opencl_atomic_store:
Tim Northovere94a34c2014-03-11 10:49:14 +00002803 case AtomicExpr::AO__atomic_store:
2804 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002805 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2806 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2807 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002808
2809 default:
2810 return true;
2811 }
2812}
2813
Richard Smithfeea8832012-04-12 05:08:17 +00002814ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2815 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002816 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2817 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002818
Yaxun Liu39195062017-08-04 18:16:31 +00002819 // All the non-OpenCL operations take one of the following forms.
2820 // The OpenCL operations take the __c11 forms with one extra argument for
2821 // synchronization scope.
Richard Smithfeea8832012-04-12 05:08:17 +00002822 enum {
2823 // C __c11_atomic_init(A *, C)
2824 Init,
2825 // C __c11_atomic_load(A *, int)
2826 Load,
2827 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002828 LoadCopy,
2829 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002830 Copy,
2831 // C __c11_atomic_add(A *, M, int)
2832 Arithmetic,
2833 // C __atomic_exchange_n(A *, CP, int)
2834 Xchg,
2835 // void __atomic_exchange(A *, C *, CP, int)
2836 GNUXchg,
2837 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2838 C11CmpXchg,
2839 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2840 GNUCmpXchg
2841 } Form = Init;
Yaxun Liu39195062017-08-04 18:16:31 +00002842 const unsigned NumForm = GNUCmpXchg + 1;
Eric Fiselier8d662442016-03-30 23:39:56 +00002843 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2844 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002845 // where:
2846 // C is an appropriate type,
2847 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2848 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2849 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2850 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002851
Yaxun Liu39195062017-08-04 18:16:31 +00002852 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
2853 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
2854 "need to update code for modified forms");
Gabor Horvath98bd0982015-03-16 09:59:54 +00002855 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2856 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2857 AtomicExpr::AO__atomic_load,
2858 "need to update code for modified C11 atomics");
Yaxun Liu39195062017-08-04 18:16:31 +00002859 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
2860 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
2861 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
2862 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
2863 IsOpenCL;
Richard Smithfeea8832012-04-12 05:08:17 +00002864 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2865 Op == AtomicExpr::AO__atomic_store_n ||
2866 Op == AtomicExpr::AO__atomic_exchange_n ||
2867 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2868 bool IsAddSub = false;
2869
2870 switch (Op) {
2871 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00002872 case AtomicExpr::AO__opencl_atomic_init:
Richard Smithfeea8832012-04-12 05:08:17 +00002873 Form = Init;
2874 break;
2875
2876 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00002877 case AtomicExpr::AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00002878 case AtomicExpr::AO__atomic_load_n:
2879 Form = Load;
2880 break;
2881
Richard Smithfeea8832012-04-12 05:08:17 +00002882 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002883 Form = LoadCopy;
2884 break;
2885
2886 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00002887 case AtomicExpr::AO__opencl_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002888 case AtomicExpr::AO__atomic_store:
2889 case AtomicExpr::AO__atomic_store_n:
2890 Form = Copy;
2891 break;
2892
2893 case AtomicExpr::AO__c11_atomic_fetch_add:
2894 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00002895 case AtomicExpr::AO__opencl_atomic_fetch_add:
2896 case AtomicExpr::AO__opencl_atomic_fetch_sub:
2897 case AtomicExpr::AO__opencl_atomic_fetch_min:
2898 case AtomicExpr::AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00002899 case AtomicExpr::AO__atomic_fetch_add:
2900 case AtomicExpr::AO__atomic_fetch_sub:
2901 case AtomicExpr::AO__atomic_add_fetch:
2902 case AtomicExpr::AO__atomic_sub_fetch:
2903 IsAddSub = true;
2904 // Fall through.
2905 case AtomicExpr::AO__c11_atomic_fetch_and:
2906 case AtomicExpr::AO__c11_atomic_fetch_or:
2907 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00002908 case AtomicExpr::AO__opencl_atomic_fetch_and:
2909 case AtomicExpr::AO__opencl_atomic_fetch_or:
2910 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Richard Smithfeea8832012-04-12 05:08:17 +00002911 case AtomicExpr::AO__atomic_fetch_and:
2912 case AtomicExpr::AO__atomic_fetch_or:
2913 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00002914 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00002915 case AtomicExpr::AO__atomic_and_fetch:
2916 case AtomicExpr::AO__atomic_or_fetch:
2917 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00002918 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00002919 Form = Arithmetic;
2920 break;
2921
2922 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00002923 case AtomicExpr::AO__opencl_atomic_exchange:
Richard Smithfeea8832012-04-12 05:08:17 +00002924 case AtomicExpr::AO__atomic_exchange_n:
2925 Form = Xchg;
2926 break;
2927
2928 case AtomicExpr::AO__atomic_exchange:
2929 Form = GNUXchg;
2930 break;
2931
2932 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2933 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +00002934 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
2935 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00002936 Form = C11CmpXchg;
2937 break;
2938
2939 case AtomicExpr::AO__atomic_compare_exchange:
2940 case AtomicExpr::AO__atomic_compare_exchange_n:
2941 Form = GNUCmpXchg;
2942 break;
2943 }
2944
Yaxun Liu39195062017-08-04 18:16:31 +00002945 unsigned AdjustedNumArgs = NumArgs[Form];
2946 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
2947 ++AdjustedNumArgs;
Richard Smithfeea8832012-04-12 05:08:17 +00002948 // Check we have the right number of arguments.
Yaxun Liu39195062017-08-04 18:16:31 +00002949 if (TheCall->getNumArgs() < AdjustedNumArgs) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002950 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Yaxun Liu39195062017-08-04 18:16:31 +00002951 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002952 << TheCall->getCallee()->getSourceRange();
2953 return ExprError();
Yaxun Liu39195062017-08-04 18:16:31 +00002954 } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
2955 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002956 diag::err_typecheck_call_too_many_args)
Yaxun Liu39195062017-08-04 18:16:31 +00002957 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002958 << TheCall->getCallee()->getSourceRange();
2959 return ExprError();
2960 }
2961
Richard Smithfeea8832012-04-12 05:08:17 +00002962 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002963 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00002964 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2965 if (ConvertedPtr.isInvalid())
2966 return ExprError();
2967
2968 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002969 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2970 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00002971 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002972 << Ptr->getType() << Ptr->getSourceRange();
2973 return ExprError();
2974 }
2975
Richard Smithfeea8832012-04-12 05:08:17 +00002976 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2977 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2978 QualType ValType = AtomTy; // 'C'
2979 if (IsC11) {
2980 if (!AtomTy->isAtomicType()) {
2981 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2982 << Ptr->getType() << Ptr->getSourceRange();
2983 return ExprError();
2984 }
Yaxun Liu39195062017-08-04 18:16:31 +00002985 if (AtomTy.isConstQualified() ||
2986 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
Richard Smithe00921a2012-09-15 06:09:58 +00002987 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
Yaxun Liu39195062017-08-04 18:16:31 +00002988 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
2989 << Ptr->getSourceRange();
Richard Smithe00921a2012-09-15 06:09:58 +00002990 return ExprError();
2991 }
Richard Smithfeea8832012-04-12 05:08:17 +00002992 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00002993 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002994 if (ValType.isConstQualified()) {
2995 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2996 << Ptr->getType() << Ptr->getSourceRange();
2997 return ExprError();
2998 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002999 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003000
Richard Smithfeea8832012-04-12 05:08:17 +00003001 // For an arithmetic operation, the implied arithmetic must be well-formed.
3002 if (Form == Arithmetic) {
3003 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
3004 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
3005 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3006 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3007 return ExprError();
3008 }
3009 if (!IsAddSub && !ValType->isIntegerType()) {
3010 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3011 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3012 return ExprError();
3013 }
David Majnemere85cff82015-01-28 05:48:06 +00003014 if (IsC11 && ValType->isPointerType() &&
3015 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3016 diag::err_incomplete_type)) {
3017 return ExprError();
3018 }
Richard Smithfeea8832012-04-12 05:08:17 +00003019 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3020 // For __atomic_*_n operations, the value type must be a scalar integral or
3021 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003022 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00003023 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3024 return ExprError();
3025 }
3026
Eli Friedmanaa769812013-09-11 03:49:34 +00003027 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3028 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003029 // For GNU atomics, require a trivially-copyable type. This is not part of
3030 // the GNU atomics specification, but we enforce it for sanity.
3031 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003032 << Ptr->getType() << Ptr->getSourceRange();
3033 return ExprError();
3034 }
3035
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003036 switch (ValType.getObjCLifetime()) {
3037 case Qualifiers::OCL_None:
3038 case Qualifiers::OCL_ExplicitNone:
3039 // okay
3040 break;
3041
3042 case Qualifiers::OCL_Weak:
3043 case Qualifiers::OCL_Strong:
3044 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00003045 // FIXME: Can this happen? By this point, ValType should be known
3046 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003047 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3048 << ValType << Ptr->getSourceRange();
3049 return ExprError();
3050 }
3051
David Majnemerc6eb6502015-06-03 00:26:35 +00003052 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
3053 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00003054 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00003055 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00003056 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003057 QualType ResultType = ValType;
Yaxun Liu39195062017-08-04 18:16:31 +00003058 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3059 Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003060 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00003061 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003062 ResultType = Context.BoolTy;
3063
Richard Smithfeea8832012-04-12 05:08:17 +00003064 // The type of a parameter passed 'by value'. In the GNU atomics, such
3065 // arguments are actually passed as pointers.
3066 QualType ByValType = ValType; // 'CP'
3067 if (!IsC11 && !IsN)
3068 ByValType = Ptr->getType();
3069
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003070 // The first argument --- the pointer --- has a fixed type; we
3071 // deduce the types of the rest of the arguments accordingly. Walk
3072 // the remaining arguments, converting them to the deduced value type.
Yaxun Liu39195062017-08-04 18:16:31 +00003073 for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003074 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00003075 if (i < NumVals[Form] + 1) {
3076 switch (i) {
3077 case 1:
3078 // The second argument is the non-atomic operand. For arithmetic, this
3079 // is always passed by value, and for a compare_exchange it is always
3080 // passed by address. For the rest, GNU uses by-address and C11 uses
3081 // by-value.
3082 assert(Form != Load);
3083 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3084 Ty = ValType;
3085 else if (Form == Copy || Form == Xchg)
3086 Ty = ByValType;
3087 else if (Form == Arithmetic)
3088 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003089 else {
3090 Expr *ValArg = TheCall->getArg(i);
Alex Lorenz67522152016-11-23 16:57:03 +00003091 // Treat this argument as _Nonnull as we want to show a warning if
3092 // NULL is passed into it.
3093 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003094 unsigned AS = 0;
3095 // Keep address space of non-atomic pointer type.
3096 if (const PointerType *PtrTy =
3097 ValArg->getType()->getAs<PointerType>()) {
3098 AS = PtrTy->getPointeeType().getAddressSpace();
3099 }
3100 Ty = Context.getPointerType(
3101 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3102 }
Richard Smithfeea8832012-04-12 05:08:17 +00003103 break;
3104 case 2:
3105 // The third argument to compare_exchange / GNU exchange is a
3106 // (pointer to a) desired value.
3107 Ty = ByValType;
3108 break;
3109 case 3:
3110 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3111 Ty = Context.BoolTy;
3112 break;
3113 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003114 } else {
Yaxun Liu39195062017-08-04 18:16:31 +00003115 // The order(s) and scope are always converted to int.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003116 Ty = Context.IntTy;
3117 }
Richard Smithfeea8832012-04-12 05:08:17 +00003118
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003119 InitializedEntity Entity =
3120 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00003121 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003122 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3123 if (Arg.isInvalid())
3124 return true;
3125 TheCall->setArg(i, Arg.get());
3126 }
3127
Yaxun Liu39195062017-08-04 18:16:31 +00003128 Expr *Scope;
3129 if (Form != Init) {
3130 if (IsOpenCL) {
3131 Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3132 llvm::APSInt Result(32);
3133 if (!Scope->isIntegerConstantExpr(Result, Context))
3134 Diag(Scope->getLocStart(),
3135 diag::err_atomic_op_has_non_constant_synch_scope)
3136 << Scope->getSourceRange();
3137 else if (!isValidSyncScopeValue(Result.getZExtValue()))
3138 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3139 << Scope->getSourceRange();
3140 } else {
3141 Scope = IntegerLiteral::Create(
3142 Context,
3143 llvm::APInt(Context.getTypeSize(Context.IntTy),
3144 static_cast<unsigned>(SyncScope::OpenCLAllSVMDevices)),
3145 Context.IntTy, SourceLocation());
3146 }
3147 }
3148
Richard Smithfeea8832012-04-12 05:08:17 +00003149 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003150 SmallVector<Expr*, 5> SubExprs;
3151 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00003152 switch (Form) {
3153 case Init:
3154 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00003155 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003156 break;
3157 case Load:
3158 SubExprs.push_back(TheCall->getArg(1)); // Order
Yaxun Liu39195062017-08-04 18:16:31 +00003159 SubExprs.push_back(Scope); // Scope
Richard Smithfeea8832012-04-12 05:08:17 +00003160 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00003161 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00003162 case Copy:
3163 case Arithmetic:
3164 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003165 SubExprs.push_back(TheCall->getArg(2)); // Order
Yaxun Liu39195062017-08-04 18:16:31 +00003166 SubExprs.push_back(Scope); // Scope
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003167 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003168 break;
3169 case GNUXchg:
3170 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3171 SubExprs.push_back(TheCall->getArg(3)); // Order
Yaxun Liu39195062017-08-04 18:16:31 +00003172 SubExprs.push_back(Scope); // Scope
Richard Smithfeea8832012-04-12 05:08:17 +00003173 SubExprs.push_back(TheCall->getArg(1)); // Val1
3174 SubExprs.push_back(TheCall->getArg(2)); // Val2
3175 break;
3176 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003177 SubExprs.push_back(TheCall->getArg(3)); // Order
Yaxun Liu39195062017-08-04 18:16:31 +00003178 SubExprs.push_back(Scope); // Scope
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003179 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003180 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00003181 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00003182 break;
3183 case GNUCmpXchg:
3184 SubExprs.push_back(TheCall->getArg(4)); // Order
Yaxun Liu39195062017-08-04 18:16:31 +00003185 SubExprs.push_back(Scope); // Scope
Richard Smithfeea8832012-04-12 05:08:17 +00003186 SubExprs.push_back(TheCall->getArg(1)); // Val1
3187 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3188 SubExprs.push_back(TheCall->getArg(2)); // Val2
3189 SubExprs.push_back(TheCall->getArg(3)); // Weak
3190 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003191 }
Tim Northovere94a34c2014-03-11 10:49:14 +00003192
3193 if (SubExprs.size() >= 2 && Form != Init) {
3194 llvm::APSInt Result(32);
3195 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3196 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00003197 Diag(SubExprs[1]->getLocStart(),
3198 diag::warn_atomic_op_has_invalid_memory_order)
3199 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00003200 }
3201
Fariborz Jahanian615de762013-05-28 17:37:39 +00003202 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3203 SubExprs, ResultType, Op,
3204 TheCall->getRParenLoc());
3205
3206 if ((Op == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00003207 Op == AtomicExpr::AO__c11_atomic_store ||
3208 Op == AtomicExpr::AO__opencl_atomic_load ||
3209 Op == AtomicExpr::AO__opencl_atomic_store ) &&
Fariborz Jahanian615de762013-05-28 17:37:39 +00003210 Context.AtomicUsesUnsupportedLibcall(AE))
Yaxun Liu39195062017-08-04 18:16:31 +00003211 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3212 << ((Op == AtomicExpr::AO__c11_atomic_load ||
3213 Op == AtomicExpr::AO__opencl_atomic_load)
3214 ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003215
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003216 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003217}
3218
John McCall29ad95b2011-08-27 01:09:30 +00003219/// checkBuiltinArgument - Given a call to a builtin function, perform
3220/// normal type-checking on the given argument, updating the call in
3221/// place. This is useful when a builtin function requires custom
3222/// type-checking for some of its arguments but not necessarily all of
3223/// them.
3224///
3225/// Returns true on error.
3226static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3227 FunctionDecl *Fn = E->getDirectCallee();
3228 assert(Fn && "builtin call without direct callee!");
3229
3230 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3231 InitializedEntity Entity =
3232 InitializedEntity::InitializeParameter(S.Context, Param);
3233
3234 ExprResult Arg = E->getArg(0);
3235 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3236 if (Arg.isInvalid())
3237 return true;
3238
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003239 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003240 return false;
3241}
3242
Chris Lattnerdc046542009-05-08 06:58:22 +00003243/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3244/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3245/// type of its first argument. The main ActOnCallExpr routines have already
3246/// promoted the types of arguments because all of these calls are prototyped as
3247/// void(...).
3248///
3249/// This function goes through and does final semantic checking for these
3250/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003251ExprResult
3252Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003253 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003254 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3255 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3256
3257 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003258 if (TheCall->getNumArgs() < 1) {
3259 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3260 << 0 << 1 << TheCall->getNumArgs()
3261 << TheCall->getCallee()->getSourceRange();
3262 return ExprError();
3263 }
Mike Stump11289f42009-09-09 15:08:12 +00003264
Chris Lattnerdc046542009-05-08 06:58:22 +00003265 // Inspect the first argument of the atomic builtin. This should always be
3266 // a pointer type, whose element is an integral scalar or pointer type.
3267 // Because it is a pointer type, we don't have to worry about any implicit
3268 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003269 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003270 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003271 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3272 if (FirstArgResult.isInvalid())
3273 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003274 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003275 TheCall->setArg(0, FirstArg);
3276
John McCall31168b02011-06-15 23:02:42 +00003277 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3278 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003279 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3280 << FirstArg->getType() << FirstArg->getSourceRange();
3281 return ExprError();
3282 }
Mike Stump11289f42009-09-09 15:08:12 +00003283
John McCall31168b02011-06-15 23:02:42 +00003284 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003285 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003286 !ValType->isBlockPointerType()) {
3287 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3288 << FirstArg->getType() << FirstArg->getSourceRange();
3289 return ExprError();
3290 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003291
John McCall31168b02011-06-15 23:02:42 +00003292 switch (ValType.getObjCLifetime()) {
3293 case Qualifiers::OCL_None:
3294 case Qualifiers::OCL_ExplicitNone:
3295 // okay
3296 break;
3297
3298 case Qualifiers::OCL_Weak:
3299 case Qualifiers::OCL_Strong:
3300 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003301 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003302 << ValType << FirstArg->getSourceRange();
3303 return ExprError();
3304 }
3305
John McCallb50451a2011-10-05 07:41:44 +00003306 // Strip any qualifiers off ValType.
3307 ValType = ValType.getUnqualifiedType();
3308
Chandler Carruth3973af72010-07-18 20:54:12 +00003309 // The majority of builtins return a value, but a few have special return
3310 // types, so allow them to override appropriately below.
3311 QualType ResultType = ValType;
3312
Chris Lattnerdc046542009-05-08 06:58:22 +00003313 // We need to figure out which concrete builtin this maps onto. For example,
3314 // __sync_fetch_and_add with a 2 byte object turns into
3315 // __sync_fetch_and_add_2.
3316#define BUILTIN_ROW(x) \
3317 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3318 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003319
Chris Lattnerdc046542009-05-08 06:58:22 +00003320 static const unsigned BuiltinIndices[][5] = {
3321 BUILTIN_ROW(__sync_fetch_and_add),
3322 BUILTIN_ROW(__sync_fetch_and_sub),
3323 BUILTIN_ROW(__sync_fetch_and_or),
3324 BUILTIN_ROW(__sync_fetch_and_and),
3325 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003326 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003327
Chris Lattnerdc046542009-05-08 06:58:22 +00003328 BUILTIN_ROW(__sync_add_and_fetch),
3329 BUILTIN_ROW(__sync_sub_and_fetch),
3330 BUILTIN_ROW(__sync_and_and_fetch),
3331 BUILTIN_ROW(__sync_or_and_fetch),
3332 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003333 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003334
Chris Lattnerdc046542009-05-08 06:58:22 +00003335 BUILTIN_ROW(__sync_val_compare_and_swap),
3336 BUILTIN_ROW(__sync_bool_compare_and_swap),
3337 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003338 BUILTIN_ROW(__sync_lock_release),
3339 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003340 };
Mike Stump11289f42009-09-09 15:08:12 +00003341#undef BUILTIN_ROW
3342
Chris Lattnerdc046542009-05-08 06:58:22 +00003343 // Determine the index of the size.
3344 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003345 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003346 case 1: SizeIndex = 0; break;
3347 case 2: SizeIndex = 1; break;
3348 case 4: SizeIndex = 2; break;
3349 case 8: SizeIndex = 3; break;
3350 case 16: SizeIndex = 4; break;
3351 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003352 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3353 << FirstArg->getType() << FirstArg->getSourceRange();
3354 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003355 }
Mike Stump11289f42009-09-09 15:08:12 +00003356
Chris Lattnerdc046542009-05-08 06:58:22 +00003357 // Each of these builtins has one pointer argument, followed by some number of
3358 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3359 // that we ignore. Find out which row of BuiltinIndices to read from as well
3360 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003361 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003362 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003363 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003364 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003365 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003366 case Builtin::BI__sync_fetch_and_add:
3367 case Builtin::BI__sync_fetch_and_add_1:
3368 case Builtin::BI__sync_fetch_and_add_2:
3369 case Builtin::BI__sync_fetch_and_add_4:
3370 case Builtin::BI__sync_fetch_and_add_8:
3371 case Builtin::BI__sync_fetch_and_add_16:
3372 BuiltinIndex = 0;
3373 break;
3374
3375 case Builtin::BI__sync_fetch_and_sub:
3376 case Builtin::BI__sync_fetch_and_sub_1:
3377 case Builtin::BI__sync_fetch_and_sub_2:
3378 case Builtin::BI__sync_fetch_and_sub_4:
3379 case Builtin::BI__sync_fetch_and_sub_8:
3380 case Builtin::BI__sync_fetch_and_sub_16:
3381 BuiltinIndex = 1;
3382 break;
3383
3384 case Builtin::BI__sync_fetch_and_or:
3385 case Builtin::BI__sync_fetch_and_or_1:
3386 case Builtin::BI__sync_fetch_and_or_2:
3387 case Builtin::BI__sync_fetch_and_or_4:
3388 case Builtin::BI__sync_fetch_and_or_8:
3389 case Builtin::BI__sync_fetch_and_or_16:
3390 BuiltinIndex = 2;
3391 break;
3392
3393 case Builtin::BI__sync_fetch_and_and:
3394 case Builtin::BI__sync_fetch_and_and_1:
3395 case Builtin::BI__sync_fetch_and_and_2:
3396 case Builtin::BI__sync_fetch_and_and_4:
3397 case Builtin::BI__sync_fetch_and_and_8:
3398 case Builtin::BI__sync_fetch_and_and_16:
3399 BuiltinIndex = 3;
3400 break;
Mike Stump11289f42009-09-09 15:08:12 +00003401
Douglas Gregor73722482011-11-28 16:30:08 +00003402 case Builtin::BI__sync_fetch_and_xor:
3403 case Builtin::BI__sync_fetch_and_xor_1:
3404 case Builtin::BI__sync_fetch_and_xor_2:
3405 case Builtin::BI__sync_fetch_and_xor_4:
3406 case Builtin::BI__sync_fetch_and_xor_8:
3407 case Builtin::BI__sync_fetch_and_xor_16:
3408 BuiltinIndex = 4;
3409 break;
3410
Hal Finkeld2208b52014-10-02 20:53:50 +00003411 case Builtin::BI__sync_fetch_and_nand:
3412 case Builtin::BI__sync_fetch_and_nand_1:
3413 case Builtin::BI__sync_fetch_and_nand_2:
3414 case Builtin::BI__sync_fetch_and_nand_4:
3415 case Builtin::BI__sync_fetch_and_nand_8:
3416 case Builtin::BI__sync_fetch_and_nand_16:
3417 BuiltinIndex = 5;
3418 WarnAboutSemanticsChange = true;
3419 break;
3420
Douglas Gregor73722482011-11-28 16:30:08 +00003421 case Builtin::BI__sync_add_and_fetch:
3422 case Builtin::BI__sync_add_and_fetch_1:
3423 case Builtin::BI__sync_add_and_fetch_2:
3424 case Builtin::BI__sync_add_and_fetch_4:
3425 case Builtin::BI__sync_add_and_fetch_8:
3426 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003427 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003428 break;
3429
3430 case Builtin::BI__sync_sub_and_fetch:
3431 case Builtin::BI__sync_sub_and_fetch_1:
3432 case Builtin::BI__sync_sub_and_fetch_2:
3433 case Builtin::BI__sync_sub_and_fetch_4:
3434 case Builtin::BI__sync_sub_and_fetch_8:
3435 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003436 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003437 break;
3438
3439 case Builtin::BI__sync_and_and_fetch:
3440 case Builtin::BI__sync_and_and_fetch_1:
3441 case Builtin::BI__sync_and_and_fetch_2:
3442 case Builtin::BI__sync_and_and_fetch_4:
3443 case Builtin::BI__sync_and_and_fetch_8:
3444 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003445 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003446 break;
3447
3448 case Builtin::BI__sync_or_and_fetch:
3449 case Builtin::BI__sync_or_and_fetch_1:
3450 case Builtin::BI__sync_or_and_fetch_2:
3451 case Builtin::BI__sync_or_and_fetch_4:
3452 case Builtin::BI__sync_or_and_fetch_8:
3453 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003454 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003455 break;
3456
3457 case Builtin::BI__sync_xor_and_fetch:
3458 case Builtin::BI__sync_xor_and_fetch_1:
3459 case Builtin::BI__sync_xor_and_fetch_2:
3460 case Builtin::BI__sync_xor_and_fetch_4:
3461 case Builtin::BI__sync_xor_and_fetch_8:
3462 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003463 BuiltinIndex = 10;
3464 break;
3465
3466 case Builtin::BI__sync_nand_and_fetch:
3467 case Builtin::BI__sync_nand_and_fetch_1:
3468 case Builtin::BI__sync_nand_and_fetch_2:
3469 case Builtin::BI__sync_nand_and_fetch_4:
3470 case Builtin::BI__sync_nand_and_fetch_8:
3471 case Builtin::BI__sync_nand_and_fetch_16:
3472 BuiltinIndex = 11;
3473 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003474 break;
Mike Stump11289f42009-09-09 15:08:12 +00003475
Chris Lattnerdc046542009-05-08 06:58:22 +00003476 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003477 case Builtin::BI__sync_val_compare_and_swap_1:
3478 case Builtin::BI__sync_val_compare_and_swap_2:
3479 case Builtin::BI__sync_val_compare_and_swap_4:
3480 case Builtin::BI__sync_val_compare_and_swap_8:
3481 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003482 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003483 NumFixed = 2;
3484 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003485
Chris Lattnerdc046542009-05-08 06:58:22 +00003486 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003487 case Builtin::BI__sync_bool_compare_and_swap_1:
3488 case Builtin::BI__sync_bool_compare_and_swap_2:
3489 case Builtin::BI__sync_bool_compare_and_swap_4:
3490 case Builtin::BI__sync_bool_compare_and_swap_8:
3491 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003492 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003493 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003494 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003495 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003496
3497 case Builtin::BI__sync_lock_test_and_set:
3498 case Builtin::BI__sync_lock_test_and_set_1:
3499 case Builtin::BI__sync_lock_test_and_set_2:
3500 case Builtin::BI__sync_lock_test_and_set_4:
3501 case Builtin::BI__sync_lock_test_and_set_8:
3502 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003503 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003504 break;
3505
Chris Lattnerdc046542009-05-08 06:58:22 +00003506 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003507 case Builtin::BI__sync_lock_release_1:
3508 case Builtin::BI__sync_lock_release_2:
3509 case Builtin::BI__sync_lock_release_4:
3510 case Builtin::BI__sync_lock_release_8:
3511 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003512 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003513 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003514 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003515 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003516
3517 case Builtin::BI__sync_swap:
3518 case Builtin::BI__sync_swap_1:
3519 case Builtin::BI__sync_swap_2:
3520 case Builtin::BI__sync_swap_4:
3521 case Builtin::BI__sync_swap_8:
3522 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003523 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003524 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003525 }
Mike Stump11289f42009-09-09 15:08:12 +00003526
Chris Lattnerdc046542009-05-08 06:58:22 +00003527 // Now that we know how many fixed arguments we expect, first check that we
3528 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003529 if (TheCall->getNumArgs() < 1+NumFixed) {
3530 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3531 << 0 << 1+NumFixed << TheCall->getNumArgs()
3532 << TheCall->getCallee()->getSourceRange();
3533 return ExprError();
3534 }
Mike Stump11289f42009-09-09 15:08:12 +00003535
Hal Finkeld2208b52014-10-02 20:53:50 +00003536 if (WarnAboutSemanticsChange) {
3537 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3538 << TheCall->getCallee()->getSourceRange();
3539 }
3540
Chris Lattner5b9241b2009-05-08 15:36:58 +00003541 // Get the decl for the concrete builtin from this, we can tell what the
3542 // concrete integer type we should convert to is.
3543 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003544 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003545 FunctionDecl *NewBuiltinDecl;
3546 if (NewBuiltinID == BuiltinID)
3547 NewBuiltinDecl = FDecl;
3548 else {
3549 // Perform builtin lookup to avoid redeclaring it.
3550 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3551 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3552 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3553 assert(Res.getFoundDecl());
3554 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003555 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003556 return ExprError();
3557 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003558
John McCallcf142162010-08-07 06:22:56 +00003559 // The first argument --- the pointer --- has a fixed type; we
3560 // deduce the types of the rest of the arguments accordingly. Walk
3561 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003562 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003563 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003564
Chris Lattnerdc046542009-05-08 06:58:22 +00003565 // GCC does an implicit conversion to the pointer or integer ValType. This
3566 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003567 // Initialize the argument.
3568 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3569 ValType, /*consume*/ false);
3570 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003571 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003572 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003573
Chris Lattnerdc046542009-05-08 06:58:22 +00003574 // Okay, we have something that *can* be converted to the right type. Check
3575 // to see if there is a potentially weird extension going on here. This can
3576 // happen when you do an atomic operation on something like an char* and
3577 // pass in 42. The 42 gets converted to char. This is even more strange
3578 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003579 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003580 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003581 }
Mike Stump11289f42009-09-09 15:08:12 +00003582
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003583 ASTContext& Context = this->getASTContext();
3584
3585 // Create a new DeclRefExpr to refer to the new decl.
3586 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3587 Context,
3588 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003589 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003590 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003591 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003592 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003593 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003594 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003595
Chris Lattnerdc046542009-05-08 06:58:22 +00003596 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003597 // FIXME: This loses syntactic information.
3598 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3599 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3600 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003601 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003602
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003603 // Change the result type of the call to match the original value type. This
3604 // is arbitrary, but the codegen for these builtins ins design to handle it
3605 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003606 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003607
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003608 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003609}
3610
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003611/// SemaBuiltinNontemporalOverloaded - We have a call to
3612/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3613/// overloaded function based on the pointer type of its last argument.
3614///
3615/// This function goes through and does final semantic checking for these
3616/// builtins.
3617ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3618 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3619 DeclRefExpr *DRE =
3620 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3621 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3622 unsigned BuiltinID = FDecl->getBuiltinID();
3623 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3624 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3625 "Unexpected nontemporal load/store builtin!");
3626 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3627 unsigned numArgs = isStore ? 2 : 1;
3628
3629 // Ensure that we have the proper number of arguments.
3630 if (checkArgCount(*this, TheCall, numArgs))
3631 return ExprError();
3632
3633 // Inspect the last argument of the nontemporal builtin. This should always
3634 // be a pointer type, from which we imply the type of the memory access.
3635 // Because it is a pointer type, we don't have to worry about any implicit
3636 // casts here.
3637 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3638 ExprResult PointerArgResult =
3639 DefaultFunctionArrayLvalueConversion(PointerArg);
3640
3641 if (PointerArgResult.isInvalid())
3642 return ExprError();
3643 PointerArg = PointerArgResult.get();
3644 TheCall->setArg(numArgs - 1, PointerArg);
3645
3646 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3647 if (!pointerType) {
3648 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3649 << PointerArg->getType() << PointerArg->getSourceRange();
3650 return ExprError();
3651 }
3652
3653 QualType ValType = pointerType->getPointeeType();
3654
3655 // Strip any qualifiers off ValType.
3656 ValType = ValType.getUnqualifiedType();
3657 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3658 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3659 !ValType->isVectorType()) {
3660 Diag(DRE->getLocStart(),
3661 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3662 << PointerArg->getType() << PointerArg->getSourceRange();
3663 return ExprError();
3664 }
3665
3666 if (!isStore) {
3667 TheCall->setType(ValType);
3668 return TheCallResult;
3669 }
3670
3671 ExprResult ValArg = TheCall->getArg(0);
3672 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3673 Context, ValType, /*consume*/ false);
3674 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3675 if (ValArg.isInvalid())
3676 return ExprError();
3677
3678 TheCall->setArg(0, ValArg.get());
3679 TheCall->setType(Context.VoidTy);
3680 return TheCallResult;
3681}
3682
Chris Lattner6436fb62009-02-18 06:01:06 +00003683/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003684/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003685/// Note: It might also make sense to do the UTF-16 conversion here (would
3686/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003687bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003688 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003689 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3690
Douglas Gregorfb65e592011-07-27 05:40:30 +00003691 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003692 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3693 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003694 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003695 }
Mike Stump11289f42009-09-09 15:08:12 +00003696
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003697 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003698 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003699 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00003700 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3701 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3702 llvm::UTF16 *ToPtr = &ToBuf[0];
3703
3704 llvm::ConversionResult Result =
3705 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3706 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003707 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00003708 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003709 Diag(Arg->getLocStart(),
3710 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3711 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003712 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003713}
3714
Mehdi Amini06d367c2016-10-24 20:39:34 +00003715/// CheckObjCString - Checks that the format string argument to the os_log()
3716/// and os_trace() functions is correct, and converts it to const char *.
3717ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3718 Arg = Arg->IgnoreParenCasts();
3719 auto *Literal = dyn_cast<StringLiteral>(Arg);
3720 if (!Literal) {
3721 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3722 Literal = ObjcLiteral->getString();
3723 }
3724 }
3725
3726 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3727 return ExprError(
3728 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3729 << Arg->getSourceRange());
3730 }
3731
3732 ExprResult Result(Literal);
3733 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3734 InitializedEntity Entity =
3735 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3736 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3737 return Result;
3738}
3739
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003740/// Check that the user is calling the appropriate va_start builtin for the
3741/// target and calling convention.
3742static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3743 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3744 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
Martin Storsjo022e7822017-07-17 20:49:45 +00003745 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003746 bool IsWindows = TT.isOSWindows();
Martin Storsjo022e7822017-07-17 20:49:45 +00003747 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
3748 if (IsX64 || IsAArch64) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003749 clang::CallingConv CC = CC_C;
3750 if (const FunctionDecl *FD = S.getCurFunctionDecl())
3751 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3752 if (IsMSVAStart) {
3753 // Don't allow this in System V ABI functions.
Martin Storsjo022e7822017-07-17 20:49:45 +00003754 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003755 return S.Diag(Fn->getLocStart(),
3756 diag::err_ms_va_start_used_in_sysv_function);
3757 } else {
Martin Storsjo022e7822017-07-17 20:49:45 +00003758 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003759 // On x64 Windows, don't allow this in System V ABI functions.
3760 // (Yes, that means there's no corresponding way to support variadic
3761 // System V ABI functions on Windows.)
3762 if ((IsWindows && CC == CC_X86_64SysV) ||
Martin Storsjo022e7822017-07-17 20:49:45 +00003763 (!IsWindows && CC == CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003764 return S.Diag(Fn->getLocStart(),
3765 diag::err_va_start_used_in_wrong_abi_function)
3766 << !IsWindows;
3767 }
3768 return false;
3769 }
3770
3771 if (IsMSVAStart)
Martin Storsjo022e7822017-07-17 20:49:45 +00003772 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003773 return false;
3774}
3775
3776static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3777 ParmVarDecl **LastParam = nullptr) {
3778 // Determine whether the current function, block, or obj-c method is variadic
3779 // and get its parameter list.
3780 bool IsVariadic = false;
3781 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00003782 DeclContext *Caller = S.CurContext;
3783 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3784 IsVariadic = Block->isVariadic();
3785 Params = Block->parameters();
3786 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003787 IsVariadic = FD->isVariadic();
3788 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003789 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003790 IsVariadic = MD->isVariadic();
3791 // FIXME: This isn't correct for methods (results in bogus warning).
3792 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003793 } else if (isa<CapturedDecl>(Caller)) {
3794 // We don't support va_start in a CapturedDecl.
3795 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3796 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003797 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003798 // This must be some other declcontext that parses exprs.
3799 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3800 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003801 }
3802
3803 if (!IsVariadic) {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003804 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003805 return true;
3806 }
3807
3808 if (LastParam)
3809 *LastParam = Params.empty() ? nullptr : Params.back();
3810
3811 return false;
3812}
3813
Charles Davisc7d5c942015-09-17 20:55:33 +00003814/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3815/// for validity. Emit an error and return true on failure; return false
3816/// on success.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003817bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003818 Expr *Fn = TheCall->getCallee();
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003819
3820 if (checkVAStartABI(*this, BuiltinID, Fn))
3821 return true;
3822
Chris Lattner08464942007-12-28 05:29:59 +00003823 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003824 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003825 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003826 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3827 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003828 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003829 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003830 return true;
3831 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003832
3833 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003834 return Diag(TheCall->getLocEnd(),
3835 diag::err_typecheck_call_too_few_args_at_least)
3836 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003837 }
3838
John McCall29ad95b2011-08-27 01:09:30 +00003839 // Type-check the first argument normally.
3840 if (checkBuiltinArgument(*this, TheCall, 0))
3841 return true;
3842
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003843 // Check that the current function is variadic, and get its last parameter.
3844 ParmVarDecl *LastParam;
3845 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
Chris Lattner43be2e62007-12-19 23:59:04 +00003846 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003847
Chris Lattner43be2e62007-12-19 23:59:04 +00003848 // Verify that the second argument to the builtin is the last argument of the
3849 // current function or method.
3850 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003851 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003852
Nico Weber9eea7642013-05-24 23:31:57 +00003853 // These are valid if SecondArgIsLastNamedArgument is false after the next
3854 // block.
3855 QualType Type;
3856 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003857 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003858
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003859 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3860 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003861 SecondArgIsLastNamedArgument = PV == LastParam;
Nico Weber9eea7642013-05-24 23:31:57 +00003862
3863 Type = PV->getType();
3864 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003865 IsCRegister =
3866 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003867 }
3868 }
Mike Stump11289f42009-09-09 15:08:12 +00003869
Chris Lattner43be2e62007-12-19 23:59:04 +00003870 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003871 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003872 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003873 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00003874 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3875 // Promotable integers are UB, but enumerations need a bit of
3876 // extra checking to see what their promotable type actually is.
3877 if (!Type->isPromotableIntegerType())
3878 return false;
3879 if (!Type->isEnumeralType())
3880 return true;
3881 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3882 return !(ED &&
3883 Context.typesAreCompatible(ED->getPromotionType(), Type));
3884 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00003885 unsigned Reason = 0;
3886 if (Type->isReferenceType()) Reason = 1;
3887 else if (IsCRegister) Reason = 2;
3888 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003889 Diag(ParamLoc, diag::note_parameter_type) << Type;
3890 }
3891
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003892 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003893 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003894}
Chris Lattner43be2e62007-12-19 23:59:04 +00003895
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003896bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3897 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3898 // const char *named_addr);
3899
3900 Expr *Func = Call->getCallee();
3901
3902 if (Call->getNumArgs() < 3)
3903 return Diag(Call->getLocEnd(),
3904 diag::err_typecheck_call_too_few_args_at_least)
3905 << 0 /*function call*/ << 3 << Call->getNumArgs();
3906
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003907 // Type-check the first argument normally.
3908 if (checkBuiltinArgument(*this, Call, 0))
3909 return true;
3910
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003911 // Check that the current function is variadic.
3912 if (checkVAStartIsInVariadicFunction(*this, Func))
3913 return true;
3914
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003915 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003916 unsigned ArgNo;
3917 QualType Type;
3918 } ArgumentTypes[] = {
3919 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3920 { 2, Context.getSizeType() },
3921 };
3922
3923 for (const auto &AT : ArgumentTypes) {
3924 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3925 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3926 continue;
3927 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3928 << Arg->getType() << AT.Type << 1 /* different class */
3929 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3930 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3931 }
3932
3933 return false;
3934}
3935
Chris Lattner2da14fb2007-12-20 00:26:33 +00003936/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3937/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003938bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3939 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003940 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003941 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003942 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003943 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003944 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003945 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003946 << SourceRange(TheCall->getArg(2)->getLocStart(),
3947 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003948
John Wiegley01296292011-04-08 18:41:53 +00003949 ExprResult OrigArg0 = TheCall->getArg(0);
3950 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003951
Chris Lattner2da14fb2007-12-20 00:26:33 +00003952 // Do standard promotions between the two arguments, returning their common
3953 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003954 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003955 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3956 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003957
3958 // Make sure any conversions are pushed back into the call; this is
3959 // type safe since unordered compare builtins are declared as "_Bool
3960 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003961 TheCall->setArg(0, OrigArg0.get());
3962 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003963
John Wiegley01296292011-04-08 18:41:53 +00003964 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003965 return false;
3966
Chris Lattner2da14fb2007-12-20 00:26:33 +00003967 // If the common type isn't a real floating type, then the arguments were
3968 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003969 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00003970 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003971 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00003972 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3973 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003974
Chris Lattner2da14fb2007-12-20 00:26:33 +00003975 return false;
3976}
3977
Benjamin Kramer634fc102010-02-15 22:42:31 +00003978/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3979/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00003980/// to check everything. We expect the last argument to be a floating point
3981/// value.
3982bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3983 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00003984 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003985 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00003986 if (TheCall->getNumArgs() > NumArgs)
3987 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003988 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003989 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00003990 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003991 (*(TheCall->arg_end()-1))->getLocEnd());
3992
Benjamin Kramer64aae502010-02-16 10:07:31 +00003993 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00003994
Eli Friedman7e4faac2009-08-31 20:06:00 +00003995 if (OrigArg->isTypeDependent())
3996 return false;
3997
Chris Lattner68784ef2010-05-06 05:50:07 +00003998 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00003999 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00004000 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004001 diag::err_typecheck_call_invalid_unary_fp)
4002 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004003
Neil Hickey88c0fac2016-12-13 16:22:50 +00004004 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00004005 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00004006 // Only remove standard FloatCasts, leaving other casts inplace
4007 if (Cast->getCastKind() == CK_FloatingCast) {
4008 Expr *CastArg = Cast->getSubExpr();
4009 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4010 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4011 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4012 "promotion from float to either float or double is the only expected cast here");
4013 Cast->setSubExpr(nullptr);
4014 TheCall->setArg(NumArgs-1, CastArg);
4015 }
Chris Lattner68784ef2010-05-06 05:50:07 +00004016 }
4017 }
4018
Eli Friedman7e4faac2009-08-31 20:06:00 +00004019 return false;
4020}
4021
Tony Jiangbbc48e92017-05-24 15:13:32 +00004022// Customized Sema Checking for VSX builtins that have the following signature:
4023// vector [...] builtinName(vector [...], vector [...], const int);
4024// Which takes the same type of vectors (any legal vector type) for the first
4025// two arguments and takes compile time constant for the third argument.
4026// Example builtins are :
4027// vector double vec_xxpermdi(vector double, vector double, int);
4028// vector short vec_xxsldwi(vector short, vector short, int);
4029bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4030 unsigned ExpectedNumArgs = 3;
4031 if (TheCall->getNumArgs() < ExpectedNumArgs)
4032 return Diag(TheCall->getLocEnd(),
4033 diag::err_typecheck_call_too_few_args_at_least)
4034 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4035 << TheCall->getSourceRange();
4036
4037 if (TheCall->getNumArgs() > ExpectedNumArgs)
4038 return Diag(TheCall->getLocEnd(),
4039 diag::err_typecheck_call_too_many_args_at_most)
4040 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4041 << TheCall->getSourceRange();
4042
4043 // Check the third argument is a compile time constant
4044 llvm::APSInt Value;
4045 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4046 return Diag(TheCall->getLocStart(),
4047 diag::err_vsx_builtin_nonconstant_argument)
4048 << 3 /* argument index */ << TheCall->getDirectCallee()
4049 << SourceRange(TheCall->getArg(2)->getLocStart(),
4050 TheCall->getArg(2)->getLocEnd());
4051
4052 QualType Arg1Ty = TheCall->getArg(0)->getType();
4053 QualType Arg2Ty = TheCall->getArg(1)->getType();
4054
4055 // Check the type of argument 1 and argument 2 are vectors.
4056 SourceLocation BuiltinLoc = TheCall->getLocStart();
4057 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4058 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4059 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4060 << TheCall->getDirectCallee()
4061 << SourceRange(TheCall->getArg(0)->getLocStart(),
4062 TheCall->getArg(1)->getLocEnd());
4063 }
4064
4065 // Check the first two arguments are the same type.
4066 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4067 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4068 << TheCall->getDirectCallee()
4069 << SourceRange(TheCall->getArg(0)->getLocStart(),
4070 TheCall->getArg(1)->getLocEnd());
4071 }
4072
4073 // When default clang type checking is turned off and the customized type
4074 // checking is used, the returning type of the function must be explicitly
4075 // set. Otherwise it is _Bool by default.
4076 TheCall->setType(Arg1Ty);
4077
4078 return false;
4079}
4080
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004081/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4082// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00004083ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00004084 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004085 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00004086 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00004087 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4088 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004089
Nate Begemana0110022010-06-08 00:16:34 +00004090 // Determine which of the following types of shufflevector we're checking:
4091 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00004092 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00004093 QualType resType = TheCall->getArg(0)->getType();
4094 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00004095
Douglas Gregorc25f7662009-05-19 22:10:17 +00004096 if (!TheCall->getArg(0)->isTypeDependent() &&
4097 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00004098 QualType LHSType = TheCall->getArg(0)->getType();
4099 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00004100
Craig Topperbaca3892013-07-29 06:47:04 +00004101 if (!LHSType->isVectorType() || !RHSType->isVectorType())
4102 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004103 diag::err_vec_builtin_non_vector)
4104 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004105 << SourceRange(TheCall->getArg(0)->getLocStart(),
4106 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004107
Nate Begemana0110022010-06-08 00:16:34 +00004108 numElements = LHSType->getAs<VectorType>()->getNumElements();
4109 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00004110
Nate Begemana0110022010-06-08 00:16:34 +00004111 // Check to see if we have a call with 2 vector arguments, the unary shuffle
4112 // with mask. If so, verify that RHS is an integer vector type with the
4113 // same number of elts as lhs.
4114 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00004115 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00004116 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00004117 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004118 diag::err_vec_builtin_incompatible_vector)
4119 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004120 << SourceRange(TheCall->getArg(1)->getLocStart(),
4121 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004122 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00004123 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004124 diag::err_vec_builtin_incompatible_vector)
4125 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004126 << SourceRange(TheCall->getArg(0)->getLocStart(),
4127 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00004128 } else if (numElements != numResElements) {
4129 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00004130 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00004131 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004132 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004133 }
4134
4135 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00004136 if (TheCall->getArg(i)->isTypeDependent() ||
4137 TheCall->getArg(i)->isValueDependent())
4138 continue;
4139
Nate Begemana0110022010-06-08 00:16:34 +00004140 llvm::APSInt Result(32);
4141 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4142 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004143 diag::err_shufflevector_nonconstant_argument)
4144 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004145
Craig Topper50ad5b72013-08-03 17:40:38 +00004146 // Allow -1 which will be translated to undef in the IR.
4147 if (Result.isSigned() && Result.isAllOnesValue())
4148 continue;
4149
Chris Lattner7ab824e2008-08-10 02:05:13 +00004150 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004151 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004152 diag::err_shufflevector_argument_too_large)
4153 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004154 }
4155
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004156 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004157
Chris Lattner7ab824e2008-08-10 02:05:13 +00004158 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004159 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00004160 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004161 }
4162
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004163 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4164 TheCall->getCallee()->getLocStart(),
4165 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004166}
Chris Lattner43be2e62007-12-19 23:59:04 +00004167
Hal Finkelc4d7c822013-09-18 03:29:45 +00004168/// SemaConvertVectorExpr - Handle __builtin_convertvector
4169ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4170 SourceLocation BuiltinLoc,
4171 SourceLocation RParenLoc) {
4172 ExprValueKind VK = VK_RValue;
4173 ExprObjectKind OK = OK_Ordinary;
4174 QualType DstTy = TInfo->getType();
4175 QualType SrcTy = E->getType();
4176
4177 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4178 return ExprError(Diag(BuiltinLoc,
4179 diag::err_convertvector_non_vector)
4180 << E->getSourceRange());
4181 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4182 return ExprError(Diag(BuiltinLoc,
4183 diag::err_convertvector_non_vector_type));
4184
4185 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4186 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4187 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4188 if (SrcElts != DstElts)
4189 return ExprError(Diag(BuiltinLoc,
4190 diag::err_convertvector_incompatible_vector)
4191 << E->getSourceRange());
4192 }
4193
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004194 return new (Context)
4195 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00004196}
4197
Daniel Dunbarb7257262008-07-21 22:59:13 +00004198/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4199// This is declared to take (const void*, ...) and can take two
4200// optional constant int args.
4201bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00004202 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004203
Chris Lattner3b054132008-11-19 05:08:23 +00004204 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004205 return Diag(TheCall->getLocEnd(),
4206 diag::err_typecheck_call_too_many_args_at_most)
4207 << 0 /*function call*/ << 3 << NumArgs
4208 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004209
4210 // Argument 0 is checked for us and the remaining arguments must be
4211 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00004212 for (unsigned i = 1; i != NumArgs; ++i)
4213 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004214 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004215
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004216 return false;
4217}
4218
Hal Finkelf0417332014-07-17 14:25:55 +00004219/// SemaBuiltinAssume - Handle __assume (MS Extension).
4220// __assume does not evaluate its arguments, and should warn if its argument
4221// has side effects.
4222bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4223 Expr *Arg = TheCall->getArg(0);
4224 if (Arg->isInstantiationDependent()) return false;
4225
4226 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00004227 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00004228 << Arg->getSourceRange()
4229 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4230
4231 return false;
4232}
4233
David Majnemer86b1bfa2016-10-31 18:07:57 +00004234/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00004235/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4236/// than 8.
4237bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4238 // The alignment must be a constant integer.
4239 Expr *Arg = TheCall->getArg(1);
4240
4241 // We can't check the value of a dependent argument.
4242 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00004243 if (const auto *UE =
4244 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4245 if (UE->getKind() == UETT_AlignOf)
4246 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4247 << Arg->getSourceRange();
4248
David Majnemer51169932016-10-31 05:37:48 +00004249 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4250
4251 if (!Result.isPowerOf2())
4252 return Diag(TheCall->getLocStart(),
4253 diag::err_alignment_not_power_of_two)
4254 << Arg->getSourceRange();
4255
4256 if (Result < Context.getCharWidth())
4257 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4258 << (unsigned)Context.getCharWidth()
4259 << Arg->getSourceRange();
4260
4261 if (Result > INT32_MAX)
4262 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4263 << INT32_MAX
4264 << Arg->getSourceRange();
4265 }
4266
4267 return false;
4268}
4269
4270/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00004271/// as (const void*, size_t, ...) and can take one optional constant int arg.
4272bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4273 unsigned NumArgs = TheCall->getNumArgs();
4274
4275 if (NumArgs > 3)
4276 return Diag(TheCall->getLocEnd(),
4277 diag::err_typecheck_call_too_many_args_at_most)
4278 << 0 /*function call*/ << 3 << NumArgs
4279 << TheCall->getSourceRange();
4280
4281 // The alignment must be a constant integer.
4282 Expr *Arg = TheCall->getArg(1);
4283
4284 // We can't check the value of a dependent argument.
4285 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4286 llvm::APSInt Result;
4287 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4288 return true;
4289
4290 if (!Result.isPowerOf2())
4291 return Diag(TheCall->getLocStart(),
4292 diag::err_alignment_not_power_of_two)
4293 << Arg->getSourceRange();
4294 }
4295
4296 if (NumArgs > 2) {
4297 ExprResult Arg(TheCall->getArg(2));
4298 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4299 Context.getSizeType(), false);
4300 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4301 if (Arg.isInvalid()) return true;
4302 TheCall->setArg(2, Arg.get());
4303 }
Hal Finkelf0417332014-07-17 14:25:55 +00004304
4305 return false;
4306}
4307
Mehdi Amini06d367c2016-10-24 20:39:34 +00004308bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4309 unsigned BuiltinID =
4310 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4311 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4312
4313 unsigned NumArgs = TheCall->getNumArgs();
4314 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4315 if (NumArgs < NumRequiredArgs) {
4316 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4317 << 0 /* function call */ << NumRequiredArgs << NumArgs
4318 << TheCall->getSourceRange();
4319 }
4320 if (NumArgs >= NumRequiredArgs + 0x100) {
4321 return Diag(TheCall->getLocEnd(),
4322 diag::err_typecheck_call_too_many_args_at_most)
4323 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4324 << TheCall->getSourceRange();
4325 }
4326 unsigned i = 0;
4327
4328 // For formatting call, check buffer arg.
4329 if (!IsSizeCall) {
4330 ExprResult Arg(TheCall->getArg(i));
4331 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4332 Context, Context.VoidPtrTy, false);
4333 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4334 if (Arg.isInvalid())
4335 return true;
4336 TheCall->setArg(i, Arg.get());
4337 i++;
4338 }
4339
4340 // Check string literal arg.
4341 unsigned FormatIdx = i;
4342 {
4343 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4344 if (Arg.isInvalid())
4345 return true;
4346 TheCall->setArg(i, Arg.get());
4347 i++;
4348 }
4349
4350 // Make sure variadic args are scalar.
4351 unsigned FirstDataArg = i;
4352 while (i < NumArgs) {
4353 ExprResult Arg = DefaultVariadicArgumentPromotion(
4354 TheCall->getArg(i), VariadicFunction, nullptr);
4355 if (Arg.isInvalid())
4356 return true;
4357 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4358 if (ArgSize.getQuantity() >= 0x100) {
4359 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4360 << i << (int)ArgSize.getQuantity() << 0xff
4361 << TheCall->getSourceRange();
4362 }
4363 TheCall->setArg(i, Arg.get());
4364 i++;
4365 }
4366
4367 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4368 // call to avoid duplicate diagnostics.
4369 if (!IsSizeCall) {
4370 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4371 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4372 bool Success = CheckFormatArguments(
4373 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4374 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4375 CheckedVarArgs);
4376 if (!Success)
4377 return true;
4378 }
4379
4380 if (IsSizeCall) {
4381 TheCall->setType(Context.getSizeType());
4382 } else {
4383 TheCall->setType(Context.VoidPtrTy);
4384 }
4385 return false;
4386}
4387
Eric Christopher8d0c6212010-04-17 02:26:23 +00004388/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4389/// TheCall is a constant expression.
4390bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4391 llvm::APSInt &Result) {
4392 Expr *Arg = TheCall->getArg(ArgNum);
4393 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4394 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4395
4396 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4397
4398 if (!Arg->isIntegerConstantExpr(Result, Context))
4399 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004400 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004401
Chris Lattnerd545ad12009-09-23 06:06:36 +00004402 return false;
4403}
4404
Richard Sandiford28940af2014-04-16 08:47:51 +00004405/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4406/// TheCall is a constant expression in the range [Low, High].
4407bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4408 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004409 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004410
4411 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004412 Expr *Arg = TheCall->getArg(ArgNum);
4413 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004414 return false;
4415
Eric Christopher8d0c6212010-04-17 02:26:23 +00004416 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004417 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004418 return true;
4419
Richard Sandiford28940af2014-04-16 08:47:51 +00004420 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004421 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004422 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004423
4424 return false;
4425}
4426
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004427/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4428/// TheCall is a constant expression is a multiple of Num..
4429bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4430 unsigned Num) {
4431 llvm::APSInt Result;
4432
4433 // We can't check the value of a dependent argument.
4434 Expr *Arg = TheCall->getArg(ArgNum);
4435 if (Arg->isTypeDependent() || Arg->isValueDependent())
4436 return false;
4437
4438 // Check constant-ness first.
4439 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4440 return true;
4441
4442 if (Result.getSExtValue() % Num != 0)
4443 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4444 << Num << Arg->getSourceRange();
4445
4446 return false;
4447}
4448
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004449/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4450/// TheCall is an ARM/AArch64 special register string literal.
4451bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4452 int ArgNum, unsigned ExpectedFieldNum,
4453 bool AllowName) {
4454 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4455 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4456 BuiltinID == ARM::BI__builtin_arm_rsr ||
4457 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4458 BuiltinID == ARM::BI__builtin_arm_wsr ||
4459 BuiltinID == ARM::BI__builtin_arm_wsrp;
4460 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4461 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4462 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4463 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4464 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4465 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4466 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4467
4468 // We can't check the value of a dependent argument.
4469 Expr *Arg = TheCall->getArg(ArgNum);
4470 if (Arg->isTypeDependent() || Arg->isValueDependent())
4471 return false;
4472
4473 // Check if the argument is a string literal.
4474 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4475 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4476 << Arg->getSourceRange();
4477
4478 // Check the type of special register given.
4479 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4480 SmallVector<StringRef, 6> Fields;
4481 Reg.split(Fields, ":");
4482
4483 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4484 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4485 << Arg->getSourceRange();
4486
4487 // If the string is the name of a register then we cannot check that it is
4488 // valid here but if the string is of one the forms described in ACLE then we
4489 // can check that the supplied fields are integers and within the valid
4490 // ranges.
4491 if (Fields.size() > 1) {
4492 bool FiveFields = Fields.size() == 5;
4493
4494 bool ValidString = true;
4495 if (IsARMBuiltin) {
4496 ValidString &= Fields[0].startswith_lower("cp") ||
4497 Fields[0].startswith_lower("p");
4498 if (ValidString)
4499 Fields[0] =
4500 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4501
4502 ValidString &= Fields[2].startswith_lower("c");
4503 if (ValidString)
4504 Fields[2] = Fields[2].drop_front(1);
4505
4506 if (FiveFields) {
4507 ValidString &= Fields[3].startswith_lower("c");
4508 if (ValidString)
4509 Fields[3] = Fields[3].drop_front(1);
4510 }
4511 }
4512
4513 SmallVector<int, 5> Ranges;
4514 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00004515 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004516 else
4517 Ranges.append({15, 7, 15});
4518
4519 for (unsigned i=0; i<Fields.size(); ++i) {
4520 int IntField;
4521 ValidString &= !Fields[i].getAsInteger(10, IntField);
4522 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4523 }
4524
4525 if (!ValidString)
4526 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4527 << Arg->getSourceRange();
4528
4529 } else if (IsAArch64Builtin && Fields.size() == 1) {
4530 // If the register name is one of those that appear in the condition below
4531 // and the special register builtin being used is one of the write builtins,
4532 // then we require that the argument provided for writing to the register
4533 // is an integer constant expression. This is because it will be lowered to
4534 // an MSR (immediate) instruction, so we need to know the immediate at
4535 // compile time.
4536 if (TheCall->getNumArgs() != 2)
4537 return false;
4538
4539 std::string RegLower = Reg.lower();
4540 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4541 RegLower != "pan" && RegLower != "uao")
4542 return false;
4543
4544 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4545 }
4546
4547 return false;
4548}
4549
Eli Friedmanc97d0142009-05-03 06:04:26 +00004550/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004551/// This checks that the target supports __builtin_longjmp and
4552/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004553bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004554 if (!Context.getTargetInfo().hasSjLjLowering())
4555 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4556 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4557
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004558 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004559 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004560
Eric Christopher8d0c6212010-04-17 02:26:23 +00004561 // TODO: This is less than ideal. Overload this to take a value.
4562 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4563 return true;
4564
4565 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004566 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4567 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4568
4569 return false;
4570}
4571
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004572/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4573/// This checks that the target supports __builtin_setjmp.
4574bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4575 if (!Context.getTargetInfo().hasSjLjLowering())
4576 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4577 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4578 return false;
4579}
4580
Richard Smithd7293d72013-08-05 18:49:43 +00004581namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004582class UncoveredArgHandler {
4583 enum { Unknown = -1, AllCovered = -2 };
4584 signed FirstUncoveredArg;
4585 SmallVector<const Expr *, 4> DiagnosticExprs;
4586
4587public:
4588 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4589
4590 bool hasUncoveredArg() const {
4591 return (FirstUncoveredArg >= 0);
4592 }
4593
4594 unsigned getUncoveredArg() const {
4595 assert(hasUncoveredArg() && "no uncovered argument");
4596 return FirstUncoveredArg;
4597 }
4598
4599 void setAllCovered() {
4600 // A string has been found with all arguments covered, so clear out
4601 // the diagnostics.
4602 DiagnosticExprs.clear();
4603 FirstUncoveredArg = AllCovered;
4604 }
4605
4606 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4607 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4608
4609 // Don't update if a previous string covers all arguments.
4610 if (FirstUncoveredArg == AllCovered)
4611 return;
4612
4613 // UncoveredArgHandler tracks the highest uncovered argument index
4614 // and with it all the strings that match this index.
4615 if (NewFirstUncoveredArg == FirstUncoveredArg)
4616 DiagnosticExprs.push_back(StrExpr);
4617 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4618 DiagnosticExprs.clear();
4619 DiagnosticExprs.push_back(StrExpr);
4620 FirstUncoveredArg = NewFirstUncoveredArg;
4621 }
4622 }
4623
4624 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4625};
4626
Richard Smithd7293d72013-08-05 18:49:43 +00004627enum StringLiteralCheckType {
4628 SLCT_NotALiteral,
4629 SLCT_UncheckedLiteral,
4630 SLCT_CheckedLiteral
4631};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004632} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00004633
Stephen Hines648c3692016-09-16 01:07:04 +00004634static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4635 BinaryOperatorKind BinOpKind,
4636 bool AddendIsRight) {
4637 unsigned BitWidth = Offset.getBitWidth();
4638 unsigned AddendBitWidth = Addend.getBitWidth();
4639 // There might be negative interim results.
4640 if (Addend.isUnsigned()) {
4641 Addend = Addend.zext(++AddendBitWidth);
4642 Addend.setIsSigned(true);
4643 }
4644 // Adjust the bit width of the APSInts.
4645 if (AddendBitWidth > BitWidth) {
4646 Offset = Offset.sext(AddendBitWidth);
4647 BitWidth = AddendBitWidth;
4648 } else if (BitWidth > AddendBitWidth) {
4649 Addend = Addend.sext(BitWidth);
4650 }
4651
4652 bool Ov = false;
4653 llvm::APSInt ResOffset = Offset;
4654 if (BinOpKind == BO_Add)
4655 ResOffset = Offset.sadd_ov(Addend, Ov);
4656 else {
4657 assert(AddendIsRight && BinOpKind == BO_Sub &&
4658 "operator must be add or sub with addend on the right");
4659 ResOffset = Offset.ssub_ov(Addend, Ov);
4660 }
4661
4662 // We add an offset to a pointer here so we should support an offset as big as
4663 // possible.
4664 if (Ov) {
4665 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00004666 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00004667 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4668 return;
4669 }
4670
4671 Offset = ResOffset;
4672}
4673
4674namespace {
4675// This is a wrapper class around StringLiteral to support offsetted string
4676// literals as format strings. It takes the offset into account when returning
4677// the string and its length or the source locations to display notes correctly.
4678class FormatStringLiteral {
4679 const StringLiteral *FExpr;
4680 int64_t Offset;
4681
4682 public:
4683 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4684 : FExpr(fexpr), Offset(Offset) {}
4685
4686 StringRef getString() const {
4687 return FExpr->getString().drop_front(Offset);
4688 }
4689
4690 unsigned getByteLength() const {
4691 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4692 }
4693 unsigned getLength() const { return FExpr->getLength() - Offset; }
4694 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4695
4696 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4697
4698 QualType getType() const { return FExpr->getType(); }
4699
4700 bool isAscii() const { return FExpr->isAscii(); }
4701 bool isWide() const { return FExpr->isWide(); }
4702 bool isUTF8() const { return FExpr->isUTF8(); }
4703 bool isUTF16() const { return FExpr->isUTF16(); }
4704 bool isUTF32() const { return FExpr->isUTF32(); }
4705 bool isPascal() const { return FExpr->isPascal(); }
4706
4707 SourceLocation getLocationOfByte(
4708 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4709 const TargetInfo &Target, unsigned *StartToken = nullptr,
4710 unsigned *StartTokenByteOffset = nullptr) const {
4711 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4712 StartToken, StartTokenByteOffset);
4713 }
4714
4715 SourceLocation getLocStart() const LLVM_READONLY {
4716 return FExpr->getLocStart().getLocWithOffset(Offset);
4717 }
4718 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4719};
4720} // end anonymous namespace
4721
4722static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004723 const Expr *OrigFormatExpr,
4724 ArrayRef<const Expr *> Args,
4725 bool HasVAListArg, unsigned format_idx,
4726 unsigned firstDataArg,
4727 Sema::FormatStringType Type,
4728 bool inFunctionCall,
4729 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004730 llvm::SmallBitVector &CheckedVarArgs,
4731 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004732
Richard Smith55ce3522012-06-25 20:30:08 +00004733// Determine if an expression is a string literal or constant string.
4734// If this function returns false on the arguments to a function expecting a
4735// format string, we will usually need to emit a warning.
4736// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00004737static StringLiteralCheckType
4738checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4739 bool HasVAListArg, unsigned format_idx,
4740 unsigned firstDataArg, Sema::FormatStringType Type,
4741 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004742 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004743 UncoveredArgHandler &UncoveredArg,
4744 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00004745 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00004746 assert(Offset.isSigned() && "invalid offset");
4747
Douglas Gregorc25f7662009-05-19 22:10:17 +00004748 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00004749 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004750
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004751 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00004752
Richard Smithd7293d72013-08-05 18:49:43 +00004753 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00004754 // Technically -Wformat-nonliteral does not warn about this case.
4755 // The behavior of printf and friends in this case is implementation
4756 // dependent. Ideally if the format string cannot be null then
4757 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00004758 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00004759
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004760 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00004761 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004762 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00004763 // The expression is a literal if both sub-expressions were, and it was
4764 // completely checked only if both sub-expressions were checked.
4765 const AbstractConditionalOperator *C =
4766 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004767
4768 // Determine whether it is necessary to check both sub-expressions, for
4769 // example, because the condition expression is a constant that can be
4770 // evaluated at compile time.
4771 bool CheckLeft = true, CheckRight = true;
4772
4773 bool Cond;
4774 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4775 if (Cond)
4776 CheckRight = false;
4777 else
4778 CheckLeft = false;
4779 }
4780
Stephen Hines648c3692016-09-16 01:07:04 +00004781 // We need to maintain the offsets for the right and the left hand side
4782 // separately to check if every possible indexed expression is a valid
4783 // string literal. They might have different offsets for different string
4784 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004785 StringLiteralCheckType Left;
4786 if (!CheckLeft)
4787 Left = SLCT_UncheckedLiteral;
4788 else {
4789 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4790 HasVAListArg, format_idx, firstDataArg,
4791 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004792 CheckedVarArgs, UncoveredArg, Offset);
4793 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004794 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004795 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004796 }
4797
Richard Smith55ce3522012-06-25 20:30:08 +00004798 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004799 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004800 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004801 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004802 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004803
4804 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004805 }
4806
4807 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00004808 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4809 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004810 }
4811
John McCallc07a0c72011-02-17 10:25:35 +00004812 case Stmt::OpaqueValueExprClass:
4813 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4814 E = src;
4815 goto tryAgain;
4816 }
Richard Smith55ce3522012-06-25 20:30:08 +00004817 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004818
Ted Kremeneka8890832011-02-24 23:03:04 +00004819 case Stmt::PredefinedExprClass:
4820 // While __func__, etc., are technically not string literals, they
4821 // cannot contain format specifiers and thus are not a security
4822 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004823 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004824
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004825 case Stmt::DeclRefExprClass: {
4826 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004827
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004828 // As an exception, do not flag errors for variables binding to
4829 // const string literals.
4830 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4831 bool isConstant = false;
4832 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004833
Richard Smithd7293d72013-08-05 18:49:43 +00004834 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4835 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004836 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004837 isConstant = T.isConstant(S.Context) &&
4838 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004839 } else if (T->isObjCObjectPointerType()) {
4840 // In ObjC, there is usually no "const ObjectPointer" type,
4841 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004842 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004843 }
Mike Stump11289f42009-09-09 15:08:12 +00004844
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004845 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004846 if (const Expr *Init = VD->getAnyInitializer()) {
4847 // Look through initializers like const char c[] = { "foo" }
4848 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4849 if (InitList->isStringLiteralInit())
4850 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4851 }
Richard Smithd7293d72013-08-05 18:49:43 +00004852 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004853 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004854 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004855 /*InFunctionCall*/ false, CheckedVarArgs,
4856 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004857 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004858 }
Mike Stump11289f42009-09-09 15:08:12 +00004859
Anders Carlssonb012ca92009-06-28 19:55:58 +00004860 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4861 // special check to see if the format string is a function parameter
4862 // of the function calling the printf function. If the function
4863 // has an attribute indicating it is a printf-like function, then we
4864 // should suppress warnings concerning non-literals being used in a call
4865 // to a vprintf function. For example:
4866 //
4867 // void
4868 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4869 // va_list ap;
4870 // va_start(ap, fmt);
4871 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4872 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00004873 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004874 if (HasVAListArg) {
4875 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4876 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4877 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004878 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004879 // adjust for implicit parameter
4880 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4881 if (MD->isInstance())
4882 ++PVIndex;
4883 // We also check if the formats are compatible.
4884 // We can't pass a 'scanf' string to a 'printf' function.
4885 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00004886 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00004887 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004888 }
4889 }
4890 }
4891 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004892 }
Mike Stump11289f42009-09-09 15:08:12 +00004893
Richard Smith55ce3522012-06-25 20:30:08 +00004894 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004895 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004896
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004897 case Stmt::CallExprClass:
4898 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004899 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004900 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4901 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4902 unsigned ArgIndex = FA->getFormatIdx();
4903 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4904 if (MD->isInstance())
4905 --ArgIndex;
4906 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00004907
Richard Smithd7293d72013-08-05 18:49:43 +00004908 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004909 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00004910 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004911 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004912 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4913 unsigned BuiltinID = FD->getBuiltinID();
4914 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4915 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4916 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00004917 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004918 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004919 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004920 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004921 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004922 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004923 }
4924 }
Mike Stump11289f42009-09-09 15:08:12 +00004925
Richard Smith55ce3522012-06-25 20:30:08 +00004926 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004927 }
Alex Lorenzd9007142016-10-24 09:42:34 +00004928 case Stmt::ObjCMessageExprClass: {
4929 const auto *ME = cast<ObjCMessageExpr>(E);
4930 if (const auto *ND = ME->getMethodDecl()) {
4931 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4932 unsigned ArgIndex = FA->getFormatIdx();
4933 const Expr *Arg = ME->getArg(ArgIndex - 1);
4934 return checkFormatStringExpr(
4935 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4936 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4937 }
4938 }
4939
4940 return SLCT_NotALiteral;
4941 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004942 case Stmt::ObjCStringLiteralClass:
4943 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00004944 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004945
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004946 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004947 StrE = ObjCFExpr->getString();
4948 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004949 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004950
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004951 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00004952 if (Offset.isNegative() || Offset > StrE->getLength()) {
4953 // TODO: It would be better to have an explicit warning for out of
4954 // bounds literals.
4955 return SLCT_NotALiteral;
4956 }
4957 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4958 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004959 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004960 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00004961 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004962 }
Mike Stump11289f42009-09-09 15:08:12 +00004963
Richard Smith55ce3522012-06-25 20:30:08 +00004964 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004965 }
Stephen Hines648c3692016-09-16 01:07:04 +00004966 case Stmt::BinaryOperatorClass: {
4967 llvm::APSInt LResult;
4968 llvm::APSInt RResult;
4969
4970 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4971
4972 // A string literal + an int offset is still a string literal.
4973 if (BinOp->isAdditiveOp()) {
4974 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4975 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4976
4977 if (LIsInt != RIsInt) {
4978 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4979
4980 if (LIsInt) {
4981 if (BinOpKind == BO_Add) {
4982 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4983 E = BinOp->getRHS();
4984 goto tryAgain;
4985 }
4986 } else {
4987 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4988 E = BinOp->getLHS();
4989 goto tryAgain;
4990 }
4991 }
Stephen Hines648c3692016-09-16 01:07:04 +00004992 }
George Burgess IVd273aab2016-09-22 00:00:26 +00004993
4994 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00004995 }
4996 case Stmt::UnaryOperatorClass: {
4997 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4998 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4999 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
5000 llvm::APSInt IndexResult;
5001 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5002 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5003 E = ASE->getBase();
5004 goto tryAgain;
5005 }
5006 }
5007
5008 return SLCT_NotALiteral;
5009 }
Mike Stump11289f42009-09-09 15:08:12 +00005010
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005011 default:
Richard Smith55ce3522012-06-25 20:30:08 +00005012 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005013 }
5014}
5015
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005016Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00005017 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00005018 .Case("scanf", FST_Scanf)
5019 .Cases("printf", "printf0", FST_Printf)
5020 .Cases("NSString", "CFString", FST_NSString)
5021 .Case("strftime", FST_Strftime)
5022 .Case("strfmon", FST_Strfmon)
5023 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5024 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5025 .Case("os_trace", FST_OSLog)
5026 .Case("os_log", FST_OSLog)
5027 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005028}
5029
Jordan Rose3e0ec582012-07-19 18:10:23 +00005030/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00005031/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00005032/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005033bool Sema::CheckFormatArguments(const FormatAttr *Format,
5034 ArrayRef<const Expr *> Args,
5035 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005036 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005037 SourceLocation Loc, SourceRange Range,
5038 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00005039 FormatStringInfo FSI;
5040 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005041 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00005042 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00005043 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00005044 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005045}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00005046
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005047bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005048 bool HasVAListArg, unsigned format_idx,
5049 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005050 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005051 SourceLocation Loc, SourceRange Range,
5052 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00005053 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005054 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005055 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00005056 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005057 }
Mike Stump11289f42009-09-09 15:08:12 +00005058
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005059 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005060
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005061 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00005062 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005063 // Dynamically generated format strings are difficult to
5064 // automatically vet at compile time. Requiring that format strings
5065 // are string literals: (1) permits the checking of format strings by
5066 // the compiler and thereby (2) can practically remove the source of
5067 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00005068
Mike Stump11289f42009-09-09 15:08:12 +00005069 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00005070 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00005071 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00005072 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005073 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00005074 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00005075 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5076 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005077 /*IsFunctionCall*/ true, CheckedVarArgs,
5078 UncoveredArg,
5079 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005080
5081 // Generate a diagnostic where an uncovered argument is detected.
5082 if (UncoveredArg.hasUncoveredArg()) {
5083 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5084 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5085 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5086 }
5087
Richard Smith55ce3522012-06-25 20:30:08 +00005088 if (CT != SLCT_NotALiteral)
5089 // Literal format string found, check done!
5090 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00005091
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005092 // Strftime is particular as it always uses a single 'time' argument,
5093 // so it is safe to pass a non-literal string.
5094 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00005095 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005096
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005097 // Do not emit diag when the string param is a macro expansion and the
5098 // format is either NSString or CFString. This is a hack to prevent
5099 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5100 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005101 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5102 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00005103 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005104
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005105 // If there are no arguments specified, warn with -Wformat-security, otherwise
5106 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005107 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00005108 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5109 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005110 switch (Type) {
5111 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005112 break;
5113 case FST_Kprintf:
5114 case FST_FreeBSDKPrintf:
5115 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00005116 Diag(FormatLoc, diag::note_format_security_fixit)
5117 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005118 break;
5119 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00005120 Diag(FormatLoc, diag::note_format_security_fixit)
5121 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005122 break;
5123 }
5124 } else {
5125 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005126 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005127 }
Richard Smith55ce3522012-06-25 20:30:08 +00005128 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005129}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005130
Ted Kremenekab278de2010-01-28 23:39:18 +00005131namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00005132class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5133protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00005134 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00005135 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00005136 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005137 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00005138 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00005139 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00005140 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00005141 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005142 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00005143 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00005144 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00005145 bool usesPositionalArgs;
5146 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005147 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00005148 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00005149 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005150 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005151
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005152public:
Stephen Hines648c3692016-09-16 01:07:04 +00005153 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005154 const Expr *origFormatExpr,
5155 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005156 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005157 ArrayRef<const Expr *> Args, unsigned formatIdx,
5158 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005159 llvm::SmallBitVector &CheckedVarArgs,
5160 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005161 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5162 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5163 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5164 usesPositionalArgs(false), atFirstArg(true),
5165 inFunctionCall(inFunctionCall), CallType(callType),
5166 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00005167 CoveredArgs.resize(numDataArgs);
5168 CoveredArgs.reset();
5169 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005170
Ted Kremenek019d2242010-01-29 01:50:07 +00005171 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005172
Ted Kremenek02087932010-07-16 02:11:22 +00005173 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005174 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005175
Jordan Rose92303592012-09-08 04:00:03 +00005176 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005177 const analyze_format_string::FormatSpecifier &FS,
5178 const analyze_format_string::ConversionSpecifier &CS,
5179 const char *startSpecifier, unsigned specifierLen,
5180 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00005181
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005182 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005183 const analyze_format_string::FormatSpecifier &FS,
5184 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005185
5186 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005187 const analyze_format_string::ConversionSpecifier &CS,
5188 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005189
Craig Toppere14c0f82014-03-12 04:55:44 +00005190 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005191
Craig Toppere14c0f82014-03-12 04:55:44 +00005192 void HandleInvalidPosition(const char *startSpecifier,
5193 unsigned specifierLen,
5194 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005195
Craig Toppere14c0f82014-03-12 04:55:44 +00005196 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005197
Craig Toppere14c0f82014-03-12 04:55:44 +00005198 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005199
Richard Trieu03cf7b72011-10-28 00:41:25 +00005200 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00005201 static void
5202 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5203 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5204 bool IsStringLocation, Range StringRange,
5205 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005206
Ted Kremenek02087932010-07-16 02:11:22 +00005207protected:
Ted Kremenekce815422010-07-19 21:25:57 +00005208 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5209 const char *startSpec,
5210 unsigned specifierLen,
5211 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005212
5213 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5214 const char *startSpec,
5215 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00005216
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005217 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00005218 CharSourceRange getSpecifierRange(const char *startSpecifier,
5219 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00005220 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005221
Ted Kremenek5739de72010-01-29 01:06:55 +00005222 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005223
5224 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5225 const analyze_format_string::ConversionSpecifier &CS,
5226 const char *startSpecifier, unsigned specifierLen,
5227 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005228
5229 template <typename Range>
5230 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5231 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005232 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00005233};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005234} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005235
Ted Kremenek02087932010-07-16 02:11:22 +00005236SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00005237 return OrigFormatExpr->getSourceRange();
5238}
5239
Ted Kremenek02087932010-07-16 02:11:22 +00005240CharSourceRange CheckFormatHandler::
5241getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00005242 SourceLocation Start = getLocationOfByte(startSpecifier);
5243 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5244
5245 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00005246 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00005247
5248 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005249}
5250
Ted Kremenek02087932010-07-16 02:11:22 +00005251SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00005252 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5253 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00005254}
5255
Ted Kremenek02087932010-07-16 02:11:22 +00005256void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5257 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00005258 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5259 getLocationOfByte(startSpecifier),
5260 /*IsStringLocation*/true,
5261 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00005262}
5263
Jordan Rose92303592012-09-08 04:00:03 +00005264void CheckFormatHandler::HandleInvalidLengthModifier(
5265 const analyze_format_string::FormatSpecifier &FS,
5266 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00005267 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00005268 using namespace analyze_format_string;
5269
5270 const LengthModifier &LM = FS.getLengthModifier();
5271 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5272
5273 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005274 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00005275 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005276 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005277 getLocationOfByte(LM.getStart()),
5278 /*IsStringLocation*/true,
5279 getSpecifierRange(startSpecifier, specifierLen));
5280
5281 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5282 << FixedLM->toString()
5283 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5284
5285 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005286 FixItHint Hint;
5287 if (DiagID == diag::warn_format_nonsensical_length)
5288 Hint = FixItHint::CreateRemoval(LMRange);
5289
5290 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005291 getLocationOfByte(LM.getStart()),
5292 /*IsStringLocation*/true,
5293 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00005294 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00005295 }
5296}
5297
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005298void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005299 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005300 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005301 using namespace analyze_format_string;
5302
5303 const LengthModifier &LM = FS.getLengthModifier();
5304 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5305
5306 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005307 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005308 if (FixedLM) {
5309 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5310 << LM.toString() << 0,
5311 getLocationOfByte(LM.getStart()),
5312 /*IsStringLocation*/true,
5313 getSpecifierRange(startSpecifier, specifierLen));
5314
5315 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5316 << FixedLM->toString()
5317 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5318
5319 } else {
5320 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5321 << LM.toString() << 0,
5322 getLocationOfByte(LM.getStart()),
5323 /*IsStringLocation*/true,
5324 getSpecifierRange(startSpecifier, specifierLen));
5325 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005326}
5327
5328void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5329 const analyze_format_string::ConversionSpecifier &CS,
5330 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005331 using namespace analyze_format_string;
5332
5333 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005334 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005335 if (FixedCS) {
5336 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5337 << CS.toString() << /*conversion specifier*/1,
5338 getLocationOfByte(CS.getStart()),
5339 /*IsStringLocation*/true,
5340 getSpecifierRange(startSpecifier, specifierLen));
5341
5342 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5343 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5344 << FixedCS->toString()
5345 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5346 } else {
5347 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5348 << CS.toString() << /*conversion specifier*/1,
5349 getLocationOfByte(CS.getStart()),
5350 /*IsStringLocation*/true,
5351 getSpecifierRange(startSpecifier, specifierLen));
5352 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005353}
5354
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005355void CheckFormatHandler::HandlePosition(const char *startPos,
5356 unsigned posLen) {
5357 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5358 getLocationOfByte(startPos),
5359 /*IsStringLocation*/true,
5360 getSpecifierRange(startPos, posLen));
5361}
5362
Ted Kremenekd1668192010-02-27 01:41:03 +00005363void
Ted Kremenek02087932010-07-16 02:11:22 +00005364CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5365 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005366 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5367 << (unsigned) p,
5368 getLocationOfByte(startPos), /*IsStringLocation*/true,
5369 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005370}
5371
Ted Kremenek02087932010-07-16 02:11:22 +00005372void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005373 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005374 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5375 getLocationOfByte(startPos),
5376 /*IsStringLocation*/true,
5377 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005378}
5379
Ted Kremenek02087932010-07-16 02:11:22 +00005380void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005381 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005382 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005383 EmitFormatDiagnostic(
5384 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5385 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5386 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005387 }
Ted Kremenek02087932010-07-16 02:11:22 +00005388}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005389
Jordan Rose58bbe422012-07-19 18:10:08 +00005390// Note that this may return NULL if there was an error parsing or building
5391// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005392const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005393 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005394}
5395
5396void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005397 // Does the number of data arguments exceed the number of
5398 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005399 if (!HasVAListArg) {
5400 // Find any arguments that weren't covered.
5401 CoveredArgs.flip();
5402 signed notCoveredArg = CoveredArgs.find_first();
5403 if (notCoveredArg >= 0) {
5404 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005405 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5406 } else {
5407 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005408 }
5409 }
5410}
5411
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005412void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5413 const Expr *ArgExpr) {
5414 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5415 "Invalid state");
5416
5417 if (!ArgExpr)
5418 return;
5419
5420 SourceLocation Loc = ArgExpr->getLocStart();
5421
5422 if (S.getSourceManager().isInSystemMacro(Loc))
5423 return;
5424
5425 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5426 for (auto E : DiagnosticExprs)
5427 PDiag << E->getSourceRange();
5428
5429 CheckFormatHandler::EmitFormatDiagnostic(
5430 S, IsFunctionCall, DiagnosticExprs[0],
5431 PDiag, Loc, /*IsStringLocation*/false,
5432 DiagnosticExprs[0]->getSourceRange());
5433}
5434
Ted Kremenekce815422010-07-19 21:25:57 +00005435bool
5436CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5437 SourceLocation Loc,
5438 const char *startSpec,
5439 unsigned specifierLen,
5440 const char *csStart,
5441 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005442 bool keepGoing = true;
5443 if (argIndex < NumDataArgs) {
5444 // Consider the argument coverered, even though the specifier doesn't
5445 // make sense.
5446 CoveredArgs.set(argIndex);
5447 }
5448 else {
5449 // If argIndex exceeds the number of data arguments we
5450 // don't issue a warning because that is just a cascade of warnings (and
5451 // they may have intended '%%' anyway). We don't want to continue processing
5452 // the format string after this point, however, as we will like just get
5453 // gibberish when trying to match arguments.
5454 keepGoing = false;
5455 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005456
5457 StringRef Specifier(csStart, csLen);
5458
5459 // If the specifier in non-printable, it could be the first byte of a UTF-8
5460 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5461 // hex value.
5462 std::string CodePointStr;
5463 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005464 llvm::UTF32 CodePoint;
5465 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5466 const llvm::UTF8 *E =
5467 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5468 llvm::ConversionResult Result =
5469 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005470
Justin Lebar90910552016-09-30 00:38:45 +00005471 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005472 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005473 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005474 }
5475
5476 llvm::raw_string_ostream OS(CodePointStr);
5477 if (CodePoint < 256)
5478 OS << "\\x" << llvm::format("%02x", CodePoint);
5479 else if (CodePoint <= 0xFFFF)
5480 OS << "\\u" << llvm::format("%04x", CodePoint);
5481 else
5482 OS << "\\U" << llvm::format("%08x", CodePoint);
5483 OS.flush();
5484 Specifier = CodePointStr;
5485 }
5486
5487 EmitFormatDiagnostic(
5488 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5489 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5490
Ted Kremenekce815422010-07-19 21:25:57 +00005491 return keepGoing;
5492}
5493
Richard Trieu03cf7b72011-10-28 00:41:25 +00005494void
5495CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5496 const char *startSpec,
5497 unsigned specifierLen) {
5498 EmitFormatDiagnostic(
5499 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5500 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5501}
5502
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005503bool
5504CheckFormatHandler::CheckNumArgs(
5505 const analyze_format_string::FormatSpecifier &FS,
5506 const analyze_format_string::ConversionSpecifier &CS,
5507 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5508
5509 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005510 PartialDiagnostic PDiag = FS.usesPositionalArg()
5511 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5512 << (argIndex+1) << NumDataArgs)
5513 : S.PDiag(diag::warn_printf_insufficient_data_args);
5514 EmitFormatDiagnostic(
5515 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5516 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005517
5518 // Since more arguments than conversion tokens are given, by extension
5519 // all arguments are covered, so mark this as so.
5520 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005521 return false;
5522 }
5523 return true;
5524}
5525
Richard Trieu03cf7b72011-10-28 00:41:25 +00005526template<typename Range>
5527void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5528 SourceLocation Loc,
5529 bool IsStringLocation,
5530 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005531 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005532 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005533 Loc, IsStringLocation, StringRange, FixIt);
5534}
5535
5536/// \brief If the format string is not within the funcion call, emit a note
5537/// so that the function call and string are in diagnostic messages.
5538///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005539/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005540/// call and only one diagnostic message will be produced. Otherwise, an
5541/// extra note will be emitted pointing to location of the format string.
5542///
5543/// \param ArgumentExpr the expression that is passed as the format string
5544/// argument in the function call. Used for getting locations when two
5545/// diagnostics are emitted.
5546///
5547/// \param PDiag the callee should already have provided any strings for the
5548/// diagnostic message. This function only adds locations and fixits
5549/// to diagnostics.
5550///
5551/// \param Loc primary location for diagnostic. If two diagnostics are
5552/// required, one will be at Loc and a new SourceLocation will be created for
5553/// the other one.
5554///
5555/// \param IsStringLocation if true, Loc points to the format string should be
5556/// used for the note. Otherwise, Loc points to the argument list and will
5557/// be used with PDiag.
5558///
5559/// \param StringRange some or all of the string to highlight. This is
5560/// templated so it can accept either a CharSourceRange or a SourceRange.
5561///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005562/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005563template <typename Range>
5564void CheckFormatHandler::EmitFormatDiagnostic(
5565 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5566 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5567 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005568 if (InFunctionCall) {
5569 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5570 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005571 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00005572 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005573 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5574 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00005575
5576 const Sema::SemaDiagnosticBuilder &Note =
5577 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5578 diag::note_format_string_defined);
5579
5580 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005581 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005582 }
5583}
5584
Ted Kremenek02087932010-07-16 02:11:22 +00005585//===--- CHECK: Printf format string checking ------------------------------===//
5586
5587namespace {
5588class CheckPrintfHandler : public CheckFormatHandler {
5589public:
Stephen Hines648c3692016-09-16 01:07:04 +00005590 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005591 const Expr *origFormatExpr,
5592 const Sema::FormatStringType type, unsigned firstDataArg,
5593 unsigned numDataArgs, bool isObjC, const char *beg,
5594 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005595 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005596 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005597 llvm::SmallBitVector &CheckedVarArgs,
5598 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005599 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5600 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5601 inFunctionCall, CallType, CheckedVarArgs,
5602 UncoveredArg) {}
5603
5604 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5605
5606 /// Returns true if '%@' specifiers are allowed in the format string.
5607 bool allowsObjCArg() const {
5608 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5609 FSType == Sema::FST_OSTrace;
5610 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00005611
Ted Kremenek02087932010-07-16 02:11:22 +00005612 bool HandleInvalidPrintfConversionSpecifier(
5613 const analyze_printf::PrintfSpecifier &FS,
5614 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005615 unsigned specifierLen) override;
5616
Ted Kremenek02087932010-07-16 02:11:22 +00005617 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5618 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005619 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005620 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5621 const char *StartSpecifier,
5622 unsigned SpecifierLen,
5623 const Expr *E);
5624
Ted Kremenek02087932010-07-16 02:11:22 +00005625 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5626 const char *startSpecifier, unsigned specifierLen);
5627 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5628 const analyze_printf::OptionalAmount &Amt,
5629 unsigned type,
5630 const char *startSpecifier, unsigned specifierLen);
5631 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5632 const analyze_printf::OptionalFlag &flag,
5633 const char *startSpecifier, unsigned specifierLen);
5634 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5635 const analyze_printf::OptionalFlag &ignoredFlag,
5636 const analyze_printf::OptionalFlag &flag,
5637 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005638 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00005639 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00005640
5641 void HandleEmptyObjCModifierFlag(const char *startFlag,
5642 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005643
Ted Kremenek2b417712015-07-02 05:39:16 +00005644 void HandleInvalidObjCModifierFlag(const char *startFlag,
5645 unsigned flagLen) override;
5646
5647 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5648 const char *flagsEnd,
5649 const char *conversionPosition)
5650 override;
5651};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005652} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00005653
5654bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5655 const analyze_printf::PrintfSpecifier &FS,
5656 const char *startSpecifier,
5657 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005658 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005659 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005660
Ted Kremenekce815422010-07-19 21:25:57 +00005661 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5662 getLocationOfByte(CS.getStart()),
5663 startSpecifier, specifierLen,
5664 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00005665}
5666
Ted Kremenek02087932010-07-16 02:11:22 +00005667bool CheckPrintfHandler::HandleAmount(
5668 const analyze_format_string::OptionalAmount &Amt,
5669 unsigned k, const char *startSpecifier,
5670 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005671 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005672 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00005673 unsigned argIndex = Amt.getArgIndex();
5674 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005675 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5676 << k,
5677 getLocationOfByte(Amt.getStart()),
5678 /*IsStringLocation*/true,
5679 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005680 // Don't do any more checking. We will just emit
5681 // spurious errors.
5682 return false;
5683 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005684
Ted Kremenek5739de72010-01-29 01:06:55 +00005685 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00005686 // Although not in conformance with C99, we also allow the argument to be
5687 // an 'unsigned int' as that is a reasonably safe case. GCC also
5688 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00005689 CoveredArgs.set(argIndex);
5690 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005691 if (!Arg)
5692 return false;
5693
Ted Kremenek5739de72010-01-29 01:06:55 +00005694 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005695
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005696 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5697 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005698
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005699 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005700 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005701 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00005702 << T << Arg->getSourceRange(),
5703 getLocationOfByte(Amt.getStart()),
5704 /*IsStringLocation*/true,
5705 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005706 // Don't do any more checking. We will just emit
5707 // spurious errors.
5708 return false;
5709 }
5710 }
5711 }
5712 return true;
5713}
Ted Kremenek5739de72010-01-29 01:06:55 +00005714
Tom Careb49ec692010-06-17 19:00:27 +00005715void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00005716 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005717 const analyze_printf::OptionalAmount &Amt,
5718 unsigned type,
5719 const char *startSpecifier,
5720 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005721 const analyze_printf::PrintfConversionSpecifier &CS =
5722 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00005723
Richard Trieu03cf7b72011-10-28 00:41:25 +00005724 FixItHint fixit =
5725 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5726 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5727 Amt.getConstantLength()))
5728 : FixItHint();
5729
5730 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5731 << type << CS.toString(),
5732 getLocationOfByte(Amt.getStart()),
5733 /*IsStringLocation*/true,
5734 getSpecifierRange(startSpecifier, specifierLen),
5735 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00005736}
5737
Ted Kremenek02087932010-07-16 02:11:22 +00005738void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005739 const analyze_printf::OptionalFlag &flag,
5740 const char *startSpecifier,
5741 unsigned specifierLen) {
5742 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005743 const analyze_printf::PrintfConversionSpecifier &CS =
5744 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00005745 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5746 << flag.toString() << CS.toString(),
5747 getLocationOfByte(flag.getPosition()),
5748 /*IsStringLocation*/true,
5749 getSpecifierRange(startSpecifier, specifierLen),
5750 FixItHint::CreateRemoval(
5751 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005752}
5753
5754void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00005755 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005756 const analyze_printf::OptionalFlag &ignoredFlag,
5757 const analyze_printf::OptionalFlag &flag,
5758 const char *startSpecifier,
5759 unsigned specifierLen) {
5760 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005761 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5762 << ignoredFlag.toString() << flag.toString(),
5763 getLocationOfByte(ignoredFlag.getPosition()),
5764 /*IsStringLocation*/true,
5765 getSpecifierRange(startSpecifier, specifierLen),
5766 FixItHint::CreateRemoval(
5767 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005768}
5769
Ted Kremenek2b417712015-07-02 05:39:16 +00005770// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5771// bool IsStringLocation, Range StringRange,
5772// ArrayRef<FixItHint> Fixit = None);
5773
5774void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5775 unsigned flagLen) {
5776 // Warn about an empty flag.
5777 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5778 getLocationOfByte(startFlag),
5779 /*IsStringLocation*/true,
5780 getSpecifierRange(startFlag, flagLen));
5781}
5782
5783void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5784 unsigned flagLen) {
5785 // Warn about an invalid flag.
5786 auto Range = getSpecifierRange(startFlag, flagLen);
5787 StringRef flag(startFlag, flagLen);
5788 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5789 getLocationOfByte(startFlag),
5790 /*IsStringLocation*/true,
5791 Range, FixItHint::CreateRemoval(Range));
5792}
5793
5794void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5795 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5796 // Warn about using '[...]' without a '@' conversion.
5797 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5798 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5799 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5800 getLocationOfByte(conversionPosition),
5801 /*IsStringLocation*/true,
5802 Range, FixItHint::CreateRemoval(Range));
5803}
5804
Richard Smith55ce3522012-06-25 20:30:08 +00005805// Determines if the specified is a C++ class or struct containing
5806// a member with the specified name and kind (e.g. a CXXMethodDecl named
5807// "c_str()").
5808template<typename MemberKind>
5809static llvm::SmallPtrSet<MemberKind*, 1>
5810CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5811 const RecordType *RT = Ty->getAs<RecordType>();
5812 llvm::SmallPtrSet<MemberKind*, 1> Results;
5813
5814 if (!RT)
5815 return Results;
5816 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005817 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005818 return Results;
5819
Alp Tokerb6cc5922014-05-03 03:45:55 +00005820 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005821 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005822 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005823
5824 // We just need to include all members of the right kind turned up by the
5825 // filter, at this point.
5826 if (S.LookupQualifiedName(R, RT->getDecl()))
5827 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5828 NamedDecl *decl = (*I)->getUnderlyingDecl();
5829 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5830 Results.insert(FK);
5831 }
5832 return Results;
5833}
5834
Richard Smith2868a732014-02-28 01:36:39 +00005835/// Check if we could call '.c_str()' on an object.
5836///
5837/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5838/// allow the call, or if it would be ambiguous).
5839bool Sema::hasCStrMethod(const Expr *E) {
5840 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5841 MethodSet Results =
5842 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5843 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5844 MI != ME; ++MI)
5845 if ((*MI)->getMinRequiredArguments() == 0)
5846 return true;
5847 return false;
5848}
5849
Richard Smith55ce3522012-06-25 20:30:08 +00005850// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005851// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00005852// Returns true when a c_str() conversion method is found.
5853bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00005854 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00005855 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5856
5857 MethodSet Results =
5858 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5859
5860 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5861 MI != ME; ++MI) {
5862 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00005863 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00005864 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00005865 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00005866 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00005867 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5868 << "c_str()"
5869 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5870 return true;
5871 }
5872 }
5873
5874 return false;
5875}
5876
Ted Kremenekab278de2010-01-28 23:39:18 +00005877bool
Ted Kremenek02087932010-07-16 02:11:22 +00005878CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00005879 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00005880 const char *startSpecifier,
5881 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005882 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00005883 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005884 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00005885
Ted Kremenek6cd69422010-07-19 22:01:06 +00005886 if (FS.consumesDataArgument()) {
5887 if (atFirstArg) {
5888 atFirstArg = false;
5889 usesPositionalArgs = FS.usesPositionalArg();
5890 }
5891 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005892 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5893 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005894 return false;
5895 }
Ted Kremenek5739de72010-01-29 01:06:55 +00005896 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005897
Ted Kremenekd1668192010-02-27 01:41:03 +00005898 // First check if the field width, precision, and conversion specifier
5899 // have matching data arguments.
5900 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5901 startSpecifier, specifierLen)) {
5902 return false;
5903 }
5904
5905 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5906 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005907 return false;
5908 }
5909
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005910 if (!CS.consumesDataArgument()) {
5911 // FIXME: Technically specifying a precision or field width here
5912 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00005913 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005914 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005915
Ted Kremenek4a49d982010-02-26 19:18:41 +00005916 // Consume the argument.
5917 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00005918 if (argIndex < NumDataArgs) {
5919 // The check to see if the argIndex is valid will come later.
5920 // We set the bit here because we may exit early from this
5921 // function if we encounter some other error.
5922 CoveredArgs.set(argIndex);
5923 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00005924
Dimitry Andric6b5ed342015-02-19 22:32:33 +00005925 // FreeBSD kernel extensions.
5926 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5927 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5928 // We need at least two arguments.
5929 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5930 return false;
5931
5932 // Claim the second argument.
5933 CoveredArgs.set(argIndex + 1);
5934
5935 // Type check the first argument (int for %b, pointer for %D)
5936 const Expr *Ex = getDataArg(argIndex);
5937 const analyze_printf::ArgType &AT =
5938 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5939 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5940 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5941 EmitFormatDiagnostic(
5942 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5943 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5944 << false << Ex->getSourceRange(),
5945 Ex->getLocStart(), /*IsStringLocation*/false,
5946 getSpecifierRange(startSpecifier, specifierLen));
5947
5948 // Type check the second argument (char * for both %b and %D)
5949 Ex = getDataArg(argIndex + 1);
5950 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5951 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5952 EmitFormatDiagnostic(
5953 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5954 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5955 << false << Ex->getSourceRange(),
5956 Ex->getLocStart(), /*IsStringLocation*/false,
5957 getSpecifierRange(startSpecifier, specifierLen));
5958
5959 return true;
5960 }
5961
Ted Kremenek4a49d982010-02-26 19:18:41 +00005962 // Check for using an Objective-C specific conversion specifier
5963 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00005964 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00005965 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5966 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00005967 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005968
Mehdi Amini06d367c2016-10-24 20:39:34 +00005969 // %P can only be used with os_log.
5970 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
5971 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5972 specifierLen);
5973 }
5974
5975 // %n is not allowed with os_log.
5976 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
5977 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
5978 getLocationOfByte(CS.getStart()),
5979 /*IsStringLocation*/ false,
5980 getSpecifierRange(startSpecifier, specifierLen));
5981
5982 return true;
5983 }
5984
5985 // Only scalars are allowed for os_trace.
5986 if (FSType == Sema::FST_OSTrace &&
5987 (CS.getKind() == ConversionSpecifier::PArg ||
5988 CS.getKind() == ConversionSpecifier::sArg ||
5989 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
5990 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5991 specifierLen);
5992 }
5993
5994 // Check for use of public/private annotation outside of os_log().
5995 if (FSType != Sema::FST_OSLog) {
5996 if (FS.isPublic().isSet()) {
5997 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5998 << "public",
5999 getLocationOfByte(FS.isPublic().getPosition()),
6000 /*IsStringLocation*/ false,
6001 getSpecifierRange(startSpecifier, specifierLen));
6002 }
6003 if (FS.isPrivate().isSet()) {
6004 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6005 << "private",
6006 getLocationOfByte(FS.isPrivate().getPosition()),
6007 /*IsStringLocation*/ false,
6008 getSpecifierRange(startSpecifier, specifierLen));
6009 }
6010 }
6011
Tom Careb49ec692010-06-17 19:00:27 +00006012 // Check for invalid use of field width
6013 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00006014 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00006015 startSpecifier, specifierLen);
6016 }
6017
6018 // Check for invalid use of precision
6019 if (!FS.hasValidPrecision()) {
6020 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6021 startSpecifier, specifierLen);
6022 }
6023
Mehdi Amini06d367c2016-10-24 20:39:34 +00006024 // Precision is mandatory for %P specifier.
6025 if (CS.getKind() == ConversionSpecifier::PArg &&
6026 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6027 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6028 getLocationOfByte(startSpecifier),
6029 /*IsStringLocation*/ false,
6030 getSpecifierRange(startSpecifier, specifierLen));
6031 }
6032
Tom Careb49ec692010-06-17 19:00:27 +00006033 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00006034 if (!FS.hasValidThousandsGroupingPrefix())
6035 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006036 if (!FS.hasValidLeadingZeros())
6037 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6038 if (!FS.hasValidPlusPrefix())
6039 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00006040 if (!FS.hasValidSpacePrefix())
6041 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006042 if (!FS.hasValidAlternativeForm())
6043 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6044 if (!FS.hasValidLeftJustified())
6045 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6046
6047 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00006048 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6049 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6050 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006051 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6052 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6053 startSpecifier, specifierLen);
6054
6055 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006056 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006057 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6058 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006059 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006060 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006061 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006062 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6063 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00006064
Jordan Rose92303592012-09-08 04:00:03 +00006065 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6066 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6067
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006068 // The remaining checks depend on the data arguments.
6069 if (HasVAListArg)
6070 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006071
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006072 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006073 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006074
Jordan Rose58bbe422012-07-19 18:10:08 +00006075 const Expr *Arg = getDataArg(argIndex);
6076 if (!Arg)
6077 return true;
6078
6079 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00006080}
6081
Jordan Roseaee34382012-09-05 22:56:26 +00006082static bool requiresParensToAddCast(const Expr *E) {
6083 // FIXME: We should have a general way to reason about operator
6084 // precedence and whether parens are actually needed here.
6085 // Take care of a few common cases where they aren't.
6086 const Expr *Inside = E->IgnoreImpCasts();
6087 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6088 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6089
6090 switch (Inside->getStmtClass()) {
6091 case Stmt::ArraySubscriptExprClass:
6092 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006093 case Stmt::CharacterLiteralClass:
6094 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006095 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006096 case Stmt::FloatingLiteralClass:
6097 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006098 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006099 case Stmt::ObjCArrayLiteralClass:
6100 case Stmt::ObjCBoolLiteralExprClass:
6101 case Stmt::ObjCBoxedExprClass:
6102 case Stmt::ObjCDictionaryLiteralClass:
6103 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006104 case Stmt::ObjCIvarRefExprClass:
6105 case Stmt::ObjCMessageExprClass:
6106 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006107 case Stmt::ObjCStringLiteralClass:
6108 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006109 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006110 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006111 case Stmt::UnaryOperatorClass:
6112 return false;
6113 default:
6114 return true;
6115 }
6116}
6117
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006118static std::pair<QualType, StringRef>
6119shouldNotPrintDirectly(const ASTContext &Context,
6120 QualType IntendedTy,
6121 const Expr *E) {
6122 // Use a 'while' to peel off layers of typedefs.
6123 QualType TyTy = IntendedTy;
6124 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6125 StringRef Name = UserTy->getDecl()->getName();
6126 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Alexander Shaposhnikov62351372017-06-26 23:02:27 +00006127 .Case("CFIndex", Context.LongTy)
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006128 .Case("NSInteger", Context.LongTy)
6129 .Case("NSUInteger", Context.UnsignedLongTy)
6130 .Case("SInt32", Context.IntTy)
6131 .Case("UInt32", Context.UnsignedIntTy)
6132 .Default(QualType());
6133
6134 if (!CastTy.isNull())
6135 return std::make_pair(CastTy, Name);
6136
6137 TyTy = UserTy->desugar();
6138 }
6139
6140 // Strip parens if necessary.
6141 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6142 return shouldNotPrintDirectly(Context,
6143 PE->getSubExpr()->getType(),
6144 PE->getSubExpr());
6145
6146 // If this is a conditional expression, then its result type is constructed
6147 // via usual arithmetic conversions and thus there might be no necessary
6148 // typedef sugar there. Recurse to operands to check for NSInteger &
6149 // Co. usage condition.
6150 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6151 QualType TrueTy, FalseTy;
6152 StringRef TrueName, FalseName;
6153
6154 std::tie(TrueTy, TrueName) =
6155 shouldNotPrintDirectly(Context,
6156 CO->getTrueExpr()->getType(),
6157 CO->getTrueExpr());
6158 std::tie(FalseTy, FalseName) =
6159 shouldNotPrintDirectly(Context,
6160 CO->getFalseExpr()->getType(),
6161 CO->getFalseExpr());
6162
6163 if (TrueTy == FalseTy)
6164 return std::make_pair(TrueTy, TrueName);
6165 else if (TrueTy.isNull())
6166 return std::make_pair(FalseTy, FalseName);
6167 else if (FalseTy.isNull())
6168 return std::make_pair(TrueTy, TrueName);
6169 }
6170
6171 return std::make_pair(QualType(), StringRef());
6172}
6173
Richard Smith55ce3522012-06-25 20:30:08 +00006174bool
6175CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6176 const char *StartSpecifier,
6177 unsigned SpecifierLen,
6178 const Expr *E) {
6179 using namespace analyze_format_string;
6180 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006181 // Now type check the data expression that matches the
6182 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006183 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00006184 if (!AT.isValid())
6185 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00006186
Jordan Rose598ec092012-12-05 18:44:40 +00006187 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00006188 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6189 ExprTy = TET->getUnderlyingExpr()->getType();
6190 }
6191
Seth Cantrellb4802962015-03-04 03:12:10 +00006192 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6193
6194 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00006195 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006196 }
Jordan Rose98709982012-06-04 22:48:57 +00006197
Jordan Rose22b74712012-09-05 22:56:19 +00006198 // Look through argument promotions for our error message's reported type.
6199 // This includes the integral and floating promotions, but excludes array
6200 // and function pointer decay; seeing that an argument intended to be a
6201 // string has type 'char [6]' is probably more confusing than 'char *'.
6202 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6203 if (ICE->getCastKind() == CK_IntegralCast ||
6204 ICE->getCastKind() == CK_FloatingCast) {
6205 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006206 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006207
6208 // Check if we didn't match because of an implicit cast from a 'char'
6209 // or 'short' to an 'int'. This is done because printf is a varargs
6210 // function.
6211 if (ICE->getType() == S.Context.IntTy ||
6212 ICE->getType() == S.Context.UnsignedIntTy) {
6213 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006214 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006215 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006216 }
Jordan Rose98709982012-06-04 22:48:57 +00006217 }
Jordan Rose598ec092012-12-05 18:44:40 +00006218 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6219 // Special case for 'a', which has type 'int' in C.
6220 // Note, however, that we do /not/ want to treat multibyte constants like
6221 // 'MooV' as characters! This form is deprecated but still exists.
6222 if (ExprTy == S.Context.IntTy)
6223 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6224 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006225 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006226
Jordan Rosebc53ed12014-05-31 04:12:14 +00006227 // Look through enums to their underlying type.
6228 bool IsEnum = false;
6229 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6230 ExprTy = EnumTy->getDecl()->getIntegerType();
6231 IsEnum = true;
6232 }
6233
Jordan Rose0e5badd2012-12-05 18:44:49 +00006234 // %C in an Objective-C context prints a unichar, not a wchar_t.
6235 // If the argument is an integer of some kind, believe the %C and suggest
6236 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006237 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006238 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006239 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6240 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6241 !ExprTy->isCharType()) {
6242 // 'unichar' is defined as a typedef of unsigned short, but we should
6243 // prefer using the typedef if it is visible.
6244 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006245
6246 // While we are here, check if the value is an IntegerLiteral that happens
6247 // to be within the valid range.
6248 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6249 const llvm::APInt &V = IL->getValue();
6250 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6251 return true;
6252 }
6253
Jordan Rose0e5badd2012-12-05 18:44:49 +00006254 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6255 Sema::LookupOrdinaryName);
6256 if (S.LookupName(Result, S.getCurScope())) {
6257 NamedDecl *ND = Result.getFoundDecl();
6258 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6259 if (TD->getUnderlyingType() == IntendedTy)
6260 IntendedTy = S.Context.getTypedefType(TD);
6261 }
6262 }
6263 }
6264
6265 // Special-case some of Darwin's platform-independence types by suggesting
6266 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006267 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006268 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006269 QualType CastTy;
6270 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6271 if (!CastTy.isNull()) {
6272 IntendedTy = CastTy;
6273 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006274 }
6275 }
6276
Jordan Rose22b74712012-09-05 22:56:19 +00006277 // We may be able to offer a FixItHint if it is a supported type.
6278 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006279 bool success =
6280 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006281
Jordan Rose22b74712012-09-05 22:56:19 +00006282 if (success) {
6283 // Get the fix string from the fixed format specifier
6284 SmallString<16> buf;
6285 llvm::raw_svector_ostream os(buf);
6286 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006287
Jordan Roseaee34382012-09-05 22:56:26 +00006288 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6289
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006290 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00006291 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6292 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6293 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6294 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00006295 // In this case, the specifier is wrong and should be changed to match
6296 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006297 EmitFormatDiagnostic(S.PDiag(diag)
6298 << AT.getRepresentativeTypeName(S.Context)
6299 << IntendedTy << IsEnum << E->getSourceRange(),
6300 E->getLocStart(),
6301 /*IsStringLocation*/ false, SpecRange,
6302 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006303 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006304 // The canonical type for formatting this value is different from the
6305 // actual type of the expression. (This occurs, for example, with Darwin's
6306 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6307 // should be printed as 'long' for 64-bit compatibility.)
6308 // Rather than emitting a normal format/argument mismatch, we want to
6309 // add a cast to the recommended type (and correct the format string
6310 // if necessary).
6311 SmallString<16> CastBuf;
6312 llvm::raw_svector_ostream CastFix(CastBuf);
6313 CastFix << "(";
6314 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6315 CastFix << ")";
6316
6317 SmallVector<FixItHint,4> Hints;
6318 if (!AT.matchesType(S.Context, IntendedTy))
6319 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6320
6321 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6322 // If there's already a cast present, just replace it.
6323 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6324 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6325
6326 } else if (!requiresParensToAddCast(E)) {
6327 // If the expression has high enough precedence,
6328 // just write the C-style cast.
6329 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6330 CastFix.str()));
6331 } else {
6332 // Otherwise, add parens around the expression as well as the cast.
6333 CastFix << "(";
6334 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6335 CastFix.str()));
6336
Alp Tokerb6cc5922014-05-03 03:45:55 +00006337 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006338 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6339 }
6340
Jordan Rose0e5badd2012-12-05 18:44:49 +00006341 if (ShouldNotPrintDirectly) {
6342 // The expression has a type that should not be printed directly.
6343 // We extract the name from the typedef because we don't want to show
6344 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006345 StringRef Name;
6346 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6347 Name = TypedefTy->getDecl()->getName();
6348 else
6349 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006350 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006351 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006352 << E->getSourceRange(),
6353 E->getLocStart(), /*IsStringLocation=*/false,
6354 SpecRange, Hints);
6355 } else {
6356 // In this case, the expression could be printed using a different
6357 // specifier, but we've decided that the specifier is probably correct
6358 // and we should cast instead. Just use the normal warning message.
6359 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006360 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6361 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006362 << E->getSourceRange(),
6363 E->getLocStart(), /*IsStringLocation*/false,
6364 SpecRange, Hints);
6365 }
Jordan Roseaee34382012-09-05 22:56:26 +00006366 }
Jordan Rose22b74712012-09-05 22:56:19 +00006367 } else {
6368 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6369 SpecifierLen);
6370 // Since the warning for passing non-POD types to variadic functions
6371 // was deferred until now, we emit a warning for non-POD
6372 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006373 switch (S.isValidVarArgType(ExprTy)) {
6374 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006375 case Sema::VAK_ValidInCXX11: {
6376 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6377 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6378 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6379 }
Richard Smithd7293d72013-08-05 18:49:43 +00006380
Seth Cantrellb4802962015-03-04 03:12:10 +00006381 EmitFormatDiagnostic(
6382 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6383 << IsEnum << CSR << E->getSourceRange(),
6384 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6385 break;
6386 }
Richard Smithd7293d72013-08-05 18:49:43 +00006387 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006388 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006389 EmitFormatDiagnostic(
6390 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006391 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006392 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006393 << CallType
6394 << AT.getRepresentativeTypeName(S.Context)
6395 << CSR
6396 << E->getSourceRange(),
6397 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006398 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006399 break;
6400
6401 case Sema::VAK_Invalid:
6402 if (ExprTy->isObjCObjectType())
6403 EmitFormatDiagnostic(
6404 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6405 << S.getLangOpts().CPlusPlus11
6406 << ExprTy
6407 << CallType
6408 << AT.getRepresentativeTypeName(S.Context)
6409 << CSR
6410 << E->getSourceRange(),
6411 E->getLocStart(), /*IsStringLocation*/false, CSR);
6412 else
6413 // FIXME: If this is an initializer list, suggest removing the braces
6414 // or inserting a cast to the target type.
6415 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6416 << isa<InitListExpr>(E) << ExprTy << CallType
6417 << AT.getRepresentativeTypeName(S.Context)
6418 << E->getSourceRange();
6419 break;
6420 }
6421
6422 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6423 "format string specifier index out of range");
6424 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006425 }
6426
Ted Kremenekab278de2010-01-28 23:39:18 +00006427 return true;
6428}
6429
Ted Kremenek02087932010-07-16 02:11:22 +00006430//===--- CHECK: Scanf format string checking ------------------------------===//
6431
6432namespace {
6433class CheckScanfHandler : public CheckFormatHandler {
6434public:
Stephen Hines648c3692016-09-16 01:07:04 +00006435 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006436 const Expr *origFormatExpr, Sema::FormatStringType type,
6437 unsigned firstDataArg, unsigned numDataArgs,
6438 const char *beg, bool hasVAListArg,
6439 ArrayRef<const Expr *> Args, unsigned formatIdx,
6440 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006441 llvm::SmallBitVector &CheckedVarArgs,
6442 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006443 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6444 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6445 inFunctionCall, CallType, CheckedVarArgs,
6446 UncoveredArg) {}
6447
Ted Kremenek02087932010-07-16 02:11:22 +00006448 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6449 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006450 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006451
6452 bool HandleInvalidScanfConversionSpecifier(
6453 const analyze_scanf::ScanfSpecifier &FS,
6454 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006455 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006456
Craig Toppere14c0f82014-03-12 04:55:44 +00006457 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006458};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006459} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006460
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006461void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6462 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006463 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6464 getLocationOfByte(end), /*IsStringLocation*/true,
6465 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006466}
6467
Ted Kremenekce815422010-07-19 21:25:57 +00006468bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6469 const analyze_scanf::ScanfSpecifier &FS,
6470 const char *startSpecifier,
6471 unsigned specifierLen) {
6472
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006473 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006474 FS.getConversionSpecifier();
6475
6476 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6477 getLocationOfByte(CS.getStart()),
6478 startSpecifier, specifierLen,
6479 CS.getStart(), CS.getLength());
6480}
6481
Ted Kremenek02087932010-07-16 02:11:22 +00006482bool CheckScanfHandler::HandleScanfSpecifier(
6483 const analyze_scanf::ScanfSpecifier &FS,
6484 const char *startSpecifier,
6485 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006486 using namespace analyze_scanf;
6487 using namespace analyze_format_string;
6488
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006489 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006490
Ted Kremenek6cd69422010-07-19 22:01:06 +00006491 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6492 // be used to decide if we are using positional arguments consistently.
6493 if (FS.consumesDataArgument()) {
6494 if (atFirstArg) {
6495 atFirstArg = false;
6496 usesPositionalArgs = FS.usesPositionalArg();
6497 }
6498 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006499 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6500 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006501 return false;
6502 }
Ted Kremenek02087932010-07-16 02:11:22 +00006503 }
6504
6505 // Check if the field with is non-zero.
6506 const OptionalAmount &Amt = FS.getFieldWidth();
6507 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6508 if (Amt.getConstantAmount() == 0) {
6509 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6510 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006511 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6512 getLocationOfByte(Amt.getStart()),
6513 /*IsStringLocation*/true, R,
6514 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006515 }
6516 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006517
Ted Kremenek02087932010-07-16 02:11:22 +00006518 if (!FS.consumesDataArgument()) {
6519 // FIXME: Technically specifying a precision or field width here
6520 // makes no sense. Worth issuing a warning at some point.
6521 return true;
6522 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006523
Ted Kremenek02087932010-07-16 02:11:22 +00006524 // Consume the argument.
6525 unsigned argIndex = FS.getArgIndex();
6526 if (argIndex < NumDataArgs) {
6527 // The check to see if the argIndex is valid will come later.
6528 // We set the bit here because we may exit early from this
6529 // function if we encounter some other error.
6530 CoveredArgs.set(argIndex);
6531 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006532
Ted Kremenek4407ea42010-07-20 20:04:47 +00006533 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006534 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006535 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6536 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006537 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006538 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006539 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006540 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6541 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006542
Jordan Rose92303592012-09-08 04:00:03 +00006543 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6544 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6545
Ted Kremenek02087932010-07-16 02:11:22 +00006546 // The remaining checks depend on the data arguments.
6547 if (HasVAListArg)
6548 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006549
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006550 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006551 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006552
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006553 // Check that the argument type matches the format specifier.
6554 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006555 if (!Ex)
6556 return true;
6557
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006558 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006559
6560 if (!AT.isValid()) {
6561 return true;
6562 }
6563
Seth Cantrellb4802962015-03-04 03:12:10 +00006564 analyze_format_string::ArgType::MatchKind match =
6565 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006566 if (match == analyze_format_string::ArgType::Match) {
6567 return true;
6568 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006569
Seth Cantrell79340072015-03-04 05:58:08 +00006570 ScanfSpecifier fixedFS = FS;
6571 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6572 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006573
Seth Cantrell79340072015-03-04 05:58:08 +00006574 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6575 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6576 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6577 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006578
Seth Cantrell79340072015-03-04 05:58:08 +00006579 if (success) {
6580 // Get the fix string from the fixed format specifier.
6581 SmallString<128> buf;
6582 llvm::raw_svector_ostream os(buf);
6583 fixedFS.toString(os);
6584
6585 EmitFormatDiagnostic(
6586 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6587 << Ex->getType() << false << Ex->getSourceRange(),
6588 Ex->getLocStart(),
6589 /*IsStringLocation*/ false,
6590 getSpecifierRange(startSpecifier, specifierLen),
6591 FixItHint::CreateReplacement(
6592 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6593 } else {
6594 EmitFormatDiagnostic(S.PDiag(diag)
6595 << AT.getRepresentativeTypeName(S.Context)
6596 << Ex->getType() << false << Ex->getSourceRange(),
6597 Ex->getLocStart(),
6598 /*IsStringLocation*/ false,
6599 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006600 }
6601
Ted Kremenek02087932010-07-16 02:11:22 +00006602 return true;
6603}
6604
Stephen Hines648c3692016-09-16 01:07:04 +00006605static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006606 const Expr *OrigFormatExpr,
6607 ArrayRef<const Expr *> Args,
6608 bool HasVAListArg, unsigned format_idx,
6609 unsigned firstDataArg,
6610 Sema::FormatStringType Type,
6611 bool inFunctionCall,
6612 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006613 llvm::SmallBitVector &CheckedVarArgs,
6614 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00006615 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00006616 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006617 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006618 S, inFunctionCall, Args[format_idx],
6619 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006620 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006621 return;
6622 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006623
Ted Kremenekab278de2010-01-28 23:39:18 +00006624 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006625 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00006626 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006627 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006628 const ConstantArrayType *T =
6629 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006630 assert(T && "String literal not of constant array type!");
6631 size_t TypeSize = T->getSize().getZExtValue();
6632 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006633 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006634
6635 // Emit a warning if the string literal is truncated and does not contain an
6636 // embedded null character.
6637 if (TypeSize <= StrRef.size() &&
6638 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6639 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006640 S, inFunctionCall, Args[format_idx],
6641 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006642 FExpr->getLocStart(),
6643 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6644 return;
6645 }
6646
Ted Kremenekab278de2010-01-28 23:39:18 +00006647 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006648 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006649 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006650 S, inFunctionCall, Args[format_idx],
6651 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006652 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006653 return;
6654 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006655
6656 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00006657 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6658 Type == Sema::FST_OSTrace) {
6659 CheckPrintfHandler H(
6660 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6661 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6662 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6663 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006664
Hans Wennborg23926bd2011-12-15 10:25:47 +00006665 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006666 S.getLangOpts(),
6667 S.Context.getTargetInfo(),
6668 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006669 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006670 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00006671 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6672 numDataArgs, Str, HasVAListArg, Args, format_idx,
6673 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006674
Hans Wennborg23926bd2011-12-15 10:25:47 +00006675 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006676 S.getLangOpts(),
6677 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006678 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006679 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006680}
6681
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006682bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6683 // Str - The format string. NOTE: this is NOT null-terminated!
6684 StringRef StrRef = FExpr->getString();
6685 const char *Str = StrRef.data();
6686 // Account for cases where the string literal is truncated in a declaration.
6687 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6688 assert(T && "String literal not of constant array type!");
6689 size_t TypeSize = T->getSize().getZExtValue();
6690 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6691 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6692 getLangOpts(),
6693 Context.getTargetInfo());
6694}
6695
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006696//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6697
6698// Returns the related absolute value function that is larger, of 0 if one
6699// does not exist.
6700static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6701 switch (AbsFunction) {
6702 default:
6703 return 0;
6704
6705 case Builtin::BI__builtin_abs:
6706 return Builtin::BI__builtin_labs;
6707 case Builtin::BI__builtin_labs:
6708 return Builtin::BI__builtin_llabs;
6709 case Builtin::BI__builtin_llabs:
6710 return 0;
6711
6712 case Builtin::BI__builtin_fabsf:
6713 return Builtin::BI__builtin_fabs;
6714 case Builtin::BI__builtin_fabs:
6715 return Builtin::BI__builtin_fabsl;
6716 case Builtin::BI__builtin_fabsl:
6717 return 0;
6718
6719 case Builtin::BI__builtin_cabsf:
6720 return Builtin::BI__builtin_cabs;
6721 case Builtin::BI__builtin_cabs:
6722 return Builtin::BI__builtin_cabsl;
6723 case Builtin::BI__builtin_cabsl:
6724 return 0;
6725
6726 case Builtin::BIabs:
6727 return Builtin::BIlabs;
6728 case Builtin::BIlabs:
6729 return Builtin::BIllabs;
6730 case Builtin::BIllabs:
6731 return 0;
6732
6733 case Builtin::BIfabsf:
6734 return Builtin::BIfabs;
6735 case Builtin::BIfabs:
6736 return Builtin::BIfabsl;
6737 case Builtin::BIfabsl:
6738 return 0;
6739
6740 case Builtin::BIcabsf:
6741 return Builtin::BIcabs;
6742 case Builtin::BIcabs:
6743 return Builtin::BIcabsl;
6744 case Builtin::BIcabsl:
6745 return 0;
6746 }
6747}
6748
6749// Returns the argument type of the absolute value function.
6750static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6751 unsigned AbsType) {
6752 if (AbsType == 0)
6753 return QualType();
6754
6755 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6756 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6757 if (Error != ASTContext::GE_None)
6758 return QualType();
6759
6760 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6761 if (!FT)
6762 return QualType();
6763
6764 if (FT->getNumParams() != 1)
6765 return QualType();
6766
6767 return FT->getParamType(0);
6768}
6769
6770// Returns the best absolute value function, or zero, based on type and
6771// current absolute value function.
6772static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6773 unsigned AbsFunctionKind) {
6774 unsigned BestKind = 0;
6775 uint64_t ArgSize = Context.getTypeSize(ArgType);
6776 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6777 Kind = getLargerAbsoluteValueFunction(Kind)) {
6778 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6779 if (Context.getTypeSize(ParamType) >= ArgSize) {
6780 if (BestKind == 0)
6781 BestKind = Kind;
6782 else if (Context.hasSameType(ParamType, ArgType)) {
6783 BestKind = Kind;
6784 break;
6785 }
6786 }
6787 }
6788 return BestKind;
6789}
6790
6791enum AbsoluteValueKind {
6792 AVK_Integer,
6793 AVK_Floating,
6794 AVK_Complex
6795};
6796
6797static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6798 if (T->isIntegralOrEnumerationType())
6799 return AVK_Integer;
6800 if (T->isRealFloatingType())
6801 return AVK_Floating;
6802 if (T->isAnyComplexType())
6803 return AVK_Complex;
6804
6805 llvm_unreachable("Type not integer, floating, or complex");
6806}
6807
6808// Changes the absolute value function to a different type. Preserves whether
6809// the function is a builtin.
6810static unsigned changeAbsFunction(unsigned AbsKind,
6811 AbsoluteValueKind ValueKind) {
6812 switch (ValueKind) {
6813 case AVK_Integer:
6814 switch (AbsKind) {
6815 default:
6816 return 0;
6817 case Builtin::BI__builtin_fabsf:
6818 case Builtin::BI__builtin_fabs:
6819 case Builtin::BI__builtin_fabsl:
6820 case Builtin::BI__builtin_cabsf:
6821 case Builtin::BI__builtin_cabs:
6822 case Builtin::BI__builtin_cabsl:
6823 return Builtin::BI__builtin_abs;
6824 case Builtin::BIfabsf:
6825 case Builtin::BIfabs:
6826 case Builtin::BIfabsl:
6827 case Builtin::BIcabsf:
6828 case Builtin::BIcabs:
6829 case Builtin::BIcabsl:
6830 return Builtin::BIabs;
6831 }
6832 case AVK_Floating:
6833 switch (AbsKind) {
6834 default:
6835 return 0;
6836 case Builtin::BI__builtin_abs:
6837 case Builtin::BI__builtin_labs:
6838 case Builtin::BI__builtin_llabs:
6839 case Builtin::BI__builtin_cabsf:
6840 case Builtin::BI__builtin_cabs:
6841 case Builtin::BI__builtin_cabsl:
6842 return Builtin::BI__builtin_fabsf;
6843 case Builtin::BIabs:
6844 case Builtin::BIlabs:
6845 case Builtin::BIllabs:
6846 case Builtin::BIcabsf:
6847 case Builtin::BIcabs:
6848 case Builtin::BIcabsl:
6849 return Builtin::BIfabsf;
6850 }
6851 case AVK_Complex:
6852 switch (AbsKind) {
6853 default:
6854 return 0;
6855 case Builtin::BI__builtin_abs:
6856 case Builtin::BI__builtin_labs:
6857 case Builtin::BI__builtin_llabs:
6858 case Builtin::BI__builtin_fabsf:
6859 case Builtin::BI__builtin_fabs:
6860 case Builtin::BI__builtin_fabsl:
6861 return Builtin::BI__builtin_cabsf;
6862 case Builtin::BIabs:
6863 case Builtin::BIlabs:
6864 case Builtin::BIllabs:
6865 case Builtin::BIfabsf:
6866 case Builtin::BIfabs:
6867 case Builtin::BIfabsl:
6868 return Builtin::BIcabsf;
6869 }
6870 }
6871 llvm_unreachable("Unable to convert function");
6872}
6873
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006874static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006875 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6876 if (!FnInfo)
6877 return 0;
6878
6879 switch (FDecl->getBuiltinID()) {
6880 default:
6881 return 0;
6882 case Builtin::BI__builtin_abs:
6883 case Builtin::BI__builtin_fabs:
6884 case Builtin::BI__builtin_fabsf:
6885 case Builtin::BI__builtin_fabsl:
6886 case Builtin::BI__builtin_labs:
6887 case Builtin::BI__builtin_llabs:
6888 case Builtin::BI__builtin_cabs:
6889 case Builtin::BI__builtin_cabsf:
6890 case Builtin::BI__builtin_cabsl:
6891 case Builtin::BIabs:
6892 case Builtin::BIlabs:
6893 case Builtin::BIllabs:
6894 case Builtin::BIfabs:
6895 case Builtin::BIfabsf:
6896 case Builtin::BIfabsl:
6897 case Builtin::BIcabs:
6898 case Builtin::BIcabsf:
6899 case Builtin::BIcabsl:
6900 return FDecl->getBuiltinID();
6901 }
6902 llvm_unreachable("Unknown Builtin type");
6903}
6904
6905// If the replacement is valid, emit a note with replacement function.
6906// Additionally, suggest including the proper header if not already included.
6907static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00006908 unsigned AbsKind, QualType ArgType) {
6909 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006910 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00006911 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006912 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6913 FunctionName = "std::abs";
6914 if (ArgType->isIntegralOrEnumerationType()) {
6915 HeaderName = "cstdlib";
6916 } else if (ArgType->isRealFloatingType()) {
6917 HeaderName = "cmath";
6918 } else {
6919 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006920 }
Richard Trieubeffb832014-04-15 23:47:53 +00006921
6922 // Lookup all std::abs
6923 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00006924 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00006925 R.suppressDiagnostics();
6926 S.LookupQualifiedName(R, Std);
6927
6928 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006929 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006930 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6931 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6932 } else {
6933 FDecl = dyn_cast<FunctionDecl>(I);
6934 }
6935 if (!FDecl)
6936 continue;
6937
6938 // Found std::abs(), check that they are the right ones.
6939 if (FDecl->getNumParams() != 1)
6940 continue;
6941
6942 // Check that the parameter type can handle the argument.
6943 QualType ParamType = FDecl->getParamDecl(0)->getType();
6944 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6945 S.Context.getTypeSize(ArgType) <=
6946 S.Context.getTypeSize(ParamType)) {
6947 // Found a function, don't need the header hint.
6948 EmitHeaderHint = false;
6949 break;
6950 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006951 }
Richard Trieubeffb832014-04-15 23:47:53 +00006952 }
6953 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00006954 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00006955 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6956
6957 if (HeaderName) {
6958 DeclarationName DN(&S.Context.Idents.get(FunctionName));
6959 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6960 R.suppressDiagnostics();
6961 S.LookupName(R, S.getCurScope());
6962
6963 if (R.isSingleResult()) {
6964 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6965 if (FD && FD->getBuiltinID() == AbsKind) {
6966 EmitHeaderHint = false;
6967 } else {
6968 return;
6969 }
6970 } else if (!R.empty()) {
6971 return;
6972 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006973 }
6974 }
6975
6976 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00006977 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006978
Richard Trieubeffb832014-04-15 23:47:53 +00006979 if (!HeaderName)
6980 return;
6981
6982 if (!EmitHeaderHint)
6983 return;
6984
Alp Toker5d96e0a2014-07-11 20:53:51 +00006985 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6986 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00006987}
6988
Richard Trieua7f30b12016-12-06 01:42:28 +00006989template <std::size_t StrLen>
6990static bool IsStdFunction(const FunctionDecl *FDecl,
6991 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00006992 if (!FDecl)
6993 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00006994 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00006995 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00006996 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00006997 return false;
6998
6999 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007000}
7001
7002// Warn when using the wrong abs() function.
7003void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00007004 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007005 if (Call->getNumArgs() != 1)
7006 return;
7007
7008 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00007009 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00007010 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007011 return;
7012
7013 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7014 QualType ParamType = Call->getArg(0)->getType();
7015
Alp Toker5d96e0a2014-07-11 20:53:51 +00007016 // Unsigned types cannot be negative. Suggest removing the absolute value
7017 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007018 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00007019 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00007020 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007021 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7022 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00007023 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007024 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7025 return;
7026 }
7027
David Majnemer7f77eb92015-11-15 03:04:34 +00007028 // Taking the absolute value of a pointer is very suspicious, they probably
7029 // wanted to index into an array, dereference a pointer, call a function, etc.
7030 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7031 unsigned DiagType = 0;
7032 if (ArgType->isFunctionType())
7033 DiagType = 1;
7034 else if (ArgType->isArrayType())
7035 DiagType = 2;
7036
7037 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7038 return;
7039 }
7040
Richard Trieubeffb832014-04-15 23:47:53 +00007041 // std::abs has overloads which prevent most of the absolute value problems
7042 // from occurring.
7043 if (IsStdAbs)
7044 return;
7045
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007046 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7047 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7048
7049 // The argument and parameter are the same kind. Check if they are the right
7050 // size.
7051 if (ArgValueKind == ParamValueKind) {
7052 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7053 return;
7054
7055 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7056 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7057 << FDecl << ArgType << ParamType;
7058
7059 if (NewAbsKind == 0)
7060 return;
7061
7062 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007063 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007064 return;
7065 }
7066
7067 // ArgValueKind != ParamValueKind
7068 // The wrong type of absolute value function was used. Attempt to find the
7069 // proper one.
7070 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7071 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7072 if (NewAbsKind == 0)
7073 return;
7074
7075 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7076 << FDecl << ParamValueKind << ArgValueKind;
7077
7078 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007079 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007080}
7081
Richard Trieu67c00712016-12-05 23:41:46 +00007082//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00007083void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7084 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00007085 if (!Call || !FDecl) return;
7086
7087 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00007088 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007089 if (Call->getExprLoc().isMacroID()) return;
7090
7091 // Only care about the one template argument, two function parameter std::max
7092 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00007093 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007094 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7095 if (!ArgList) return;
7096 if (ArgList->size() != 1) return;
7097
7098 // Check that template type argument is unsigned integer.
7099 const auto& TA = ArgList->get(0);
7100 if (TA.getKind() != TemplateArgument::Type) return;
7101 QualType ArgType = TA.getAsType();
7102 if (!ArgType->isUnsignedIntegerType()) return;
7103
7104 // See if either argument is a literal zero.
7105 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7106 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7107 if (!MTE) return false;
7108 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7109 if (!Num) return false;
7110 if (Num->getValue() != 0) return false;
7111 return true;
7112 };
7113
7114 const Expr *FirstArg = Call->getArg(0);
7115 const Expr *SecondArg = Call->getArg(1);
7116 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7117 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7118
7119 // Only warn when exactly one argument is zero.
7120 if (IsFirstArgZero == IsSecondArgZero) return;
7121
7122 SourceRange FirstRange = FirstArg->getSourceRange();
7123 SourceRange SecondRange = SecondArg->getSourceRange();
7124
7125 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7126
7127 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7128 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7129
7130 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7131 SourceRange RemovalRange;
7132 if (IsFirstArgZero) {
7133 RemovalRange = SourceRange(FirstRange.getBegin(),
7134 SecondRange.getBegin().getLocWithOffset(-1));
7135 } else {
7136 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7137 SecondRange.getEnd());
7138 }
7139
7140 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7141 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7142 << FixItHint::CreateRemoval(RemovalRange);
7143}
7144
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007145//===--- CHECK: Standard memory functions ---------------------------------===//
7146
Nico Weber0e6daef2013-12-26 23:38:39 +00007147/// \brief Takes the expression passed to the size_t parameter of functions
7148/// such as memcmp, strncat, etc and warns if it's a comparison.
7149///
7150/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7151static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7152 IdentifierInfo *FnName,
7153 SourceLocation FnLoc,
7154 SourceLocation RParenLoc) {
7155 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7156 if (!Size)
7157 return false;
7158
7159 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
7160 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
7161 return false;
7162
Nico Weber0e6daef2013-12-26 23:38:39 +00007163 SourceRange SizeRange = Size->getSourceRange();
7164 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7165 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00007166 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007167 << FnName << FixItHint::CreateInsertion(
7168 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00007169 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00007170 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00007171 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00007172 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7173 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00007174
7175 return true;
7176}
7177
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007178/// \brief Determine whether the given type is or contains a dynamic class type
7179/// (e.g., whether it has a vtable).
7180static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7181 bool &IsContained) {
7182 // Look through array types while ignoring qualifiers.
7183 const Type *Ty = T->getBaseElementTypeUnsafe();
7184 IsContained = false;
7185
7186 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7187 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00007188 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007189 return nullptr;
7190
7191 if (RD->isDynamicClass())
7192 return RD;
7193
7194 // Check all the fields. If any bases were dynamic, the class is dynamic.
7195 // It's impossible for a class to transitively contain itself by value, so
7196 // infinite recursion is impossible.
7197 for (auto *FD : RD->fields()) {
7198 bool SubContained;
7199 if (const CXXRecordDecl *ContainedRD =
7200 getContainedDynamicClass(FD->getType(), SubContained)) {
7201 IsContained = true;
7202 return ContainedRD;
7203 }
7204 }
7205
7206 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007207}
7208
Chandler Carruth889ed862011-06-21 23:04:20 +00007209/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007210/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007211static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007212 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007213 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7214 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
7215 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007216
Craig Topperc3ec1492014-05-26 06:22:03 +00007217 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007218}
7219
Chandler Carruth889ed862011-06-21 23:04:20 +00007220/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007221static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007222 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7223 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7224 if (SizeOf->getKind() == clang::UETT_SizeOf)
7225 return SizeOf->getTypeOfArgument();
7226
7227 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007228}
7229
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007230/// \brief Check for dangerous or invalid arguments to memset().
7231///
Chandler Carruthac687262011-06-03 06:23:57 +00007232/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007233/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7234/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007235///
7236/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007237void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007238 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007239 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007240 assert(BId != 0);
7241
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007242 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007243 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007244 unsigned ExpectedNumArgs =
7245 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007246 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007247 return;
7248
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007249 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007250 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007251 unsigned LenArg =
7252 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007253 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007254
Nico Weber0e6daef2013-12-26 23:38:39 +00007255 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7256 Call->getLocStart(), Call->getRParenLoc()))
7257 return;
7258
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007259 // We have special checking when the length is a sizeof expression.
7260 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7261 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7262 llvm::FoldingSetNodeID SizeOfArgID;
7263
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007264 // Although widely used, 'bzero' is not a standard function. Be more strict
7265 // with the argument types before allowing diagnostics and only allow the
7266 // form bzero(ptr, sizeof(...)).
7267 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7268 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7269 return;
7270
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007271 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7272 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007273 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007274
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007275 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007276 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007277 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007278 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007279
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007280 // Never warn about void type pointers. This can be used to suppress
7281 // false positives.
7282 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007283 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007284
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007285 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7286 // actually comparing the expressions for equality. Because computing the
7287 // expression IDs can be expensive, we only do this if the diagnostic is
7288 // enabled.
7289 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007290 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7291 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007292 // We only compute IDs for expressions if the warning is enabled, and
7293 // cache the sizeof arg's ID.
7294 if (SizeOfArgID == llvm::FoldingSetNodeID())
7295 SizeOfArg->Profile(SizeOfArgID, Context, true);
7296 llvm::FoldingSetNodeID DestID;
7297 Dest->Profile(DestID, Context, true);
7298 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007299 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7300 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007301 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007302 StringRef ReadableName = FnName->getName();
7303
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007304 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007305 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007306 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007307 if (!PointeeTy->isIncompleteType() &&
7308 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007309 ActionIdx = 2; // If the pointee's size is sizeof(char),
7310 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007311
7312 // If the function is defined as a builtin macro, do not show macro
7313 // expansion.
7314 SourceLocation SL = SizeOfArg->getExprLoc();
7315 SourceRange DSR = Dest->getSourceRange();
7316 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007317 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007318
7319 if (SM.isMacroArgExpansion(SL)) {
7320 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7321 SL = SM.getSpellingLoc(SL);
7322 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7323 SM.getSpellingLoc(DSR.getEnd()));
7324 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7325 SM.getSpellingLoc(SSR.getEnd()));
7326 }
7327
Anna Zaksd08d9152012-05-30 23:14:52 +00007328 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007329 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007330 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007331 << PointeeTy
7332 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007333 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007334 << SSR);
7335 DiagRuntimeBehavior(SL, SizeOfArg,
7336 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7337 << ActionIdx
7338 << SSR);
7339
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007340 break;
7341 }
7342 }
7343
7344 // Also check for cases where the sizeof argument is the exact same
7345 // type as the memory argument, and where it points to a user-defined
7346 // record type.
7347 if (SizeOfArgTy != QualType()) {
7348 if (PointeeTy->isRecordType() &&
7349 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7350 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7351 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7352 << FnName << SizeOfArgTy << ArgIdx
7353 << PointeeTy << Dest->getSourceRange()
7354 << LenExpr->getSourceRange());
7355 break;
7356 }
Nico Weberc5e73862011-06-14 16:14:58 +00007357 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00007358 } else if (DestTy->isArrayType()) {
7359 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00007360 }
Nico Weberc5e73862011-06-14 16:14:58 +00007361
Nico Weberc44b35e2015-03-21 17:37:46 +00007362 if (PointeeTy == QualType())
7363 continue;
Anna Zaks22122702012-01-17 00:37:07 +00007364
Nico Weberc44b35e2015-03-21 17:37:46 +00007365 // Always complain about dynamic classes.
7366 bool IsContained;
7367 if (const CXXRecordDecl *ContainedRD =
7368 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00007369
Nico Weberc44b35e2015-03-21 17:37:46 +00007370 unsigned OperationType = 0;
7371 // "overwritten" if we're warning about the destination for any call
7372 // but memcmp; otherwise a verb appropriate to the call.
7373 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7374 if (BId == Builtin::BImemcpy)
7375 OperationType = 1;
7376 else if(BId == Builtin::BImemmove)
7377 OperationType = 2;
7378 else if (BId == Builtin::BImemcmp)
7379 OperationType = 3;
7380 }
7381
John McCall31168b02011-06-15 23:02:42 +00007382 DiagRuntimeBehavior(
7383 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007384 PDiag(diag::warn_dyn_class_memaccess)
7385 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7386 << FnName << IsContained << ContainedRD << OperationType
7387 << Call->getCallee()->getSourceRange());
7388 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7389 BId != Builtin::BImemset)
7390 DiagRuntimeBehavior(
7391 Dest->getExprLoc(), Dest,
7392 PDiag(diag::warn_arc_object_memaccess)
7393 << ArgIdx << FnName << PointeeTy
7394 << Call->getCallee()->getSourceRange());
7395 else
7396 continue;
7397
7398 DiagRuntimeBehavior(
7399 Dest->getExprLoc(), Dest,
7400 PDiag(diag::note_bad_memaccess_silence)
7401 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7402 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007403 }
7404}
7405
Ted Kremenek6865f772011-08-18 20:55:45 +00007406// A little helper routine: ignore addition and subtraction of integer literals.
7407// This intentionally does not ignore all integer constant expressions because
7408// we don't want to remove sizeof().
7409static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7410 Ex = Ex->IgnoreParenCasts();
7411
7412 for (;;) {
7413 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7414 if (!BO || !BO->isAdditiveOp())
7415 break;
7416
7417 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7418 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7419
7420 if (isa<IntegerLiteral>(RHS))
7421 Ex = LHS;
7422 else if (isa<IntegerLiteral>(LHS))
7423 Ex = RHS;
7424 else
7425 break;
7426 }
7427
7428 return Ex;
7429}
7430
Anna Zaks13b08572012-08-08 21:42:23 +00007431static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7432 ASTContext &Context) {
7433 // Only handle constant-sized or VLAs, but not flexible members.
7434 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7435 // Only issue the FIXIT for arrays of size > 1.
7436 if (CAT->getSize().getSExtValue() <= 1)
7437 return false;
7438 } else if (!Ty->isVariableArrayType()) {
7439 return false;
7440 }
7441 return true;
7442}
7443
Ted Kremenek6865f772011-08-18 20:55:45 +00007444// Warn if the user has made the 'size' argument to strlcpy or strlcat
7445// be the size of the source, instead of the destination.
7446void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7447 IdentifierInfo *FnName) {
7448
7449 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007450 unsigned NumArgs = Call->getNumArgs();
7451 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007452 return;
7453
7454 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7455 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007456 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007457
7458 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7459 Call->getLocStart(), Call->getRParenLoc()))
7460 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00007461
7462 // Look for 'strlcpy(dst, x, sizeof(x))'
7463 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7464 CompareWithSrc = Ex;
7465 else {
7466 // Look for 'strlcpy(dst, x, strlen(x))'
7467 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00007468 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7469 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00007470 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7471 }
7472 }
7473
7474 if (!CompareWithSrc)
7475 return;
7476
7477 // Determine if the argument to sizeof/strlen is equal to the source
7478 // argument. In principle there's all kinds of things you could do
7479 // here, for instance creating an == expression and evaluating it with
7480 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7481 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7482 if (!SrcArgDRE)
7483 return;
7484
7485 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7486 if (!CompareWithSrcDRE ||
7487 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7488 return;
7489
7490 const Expr *OriginalSizeArg = Call->getArg(2);
7491 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7492 << OriginalSizeArg->getSourceRange() << FnName;
7493
7494 // Output a FIXIT hint if the destination is an array (rather than a
7495 // pointer to an array). This could be enhanced to handle some
7496 // pointers if we know the actual size, like if DstArg is 'array+2'
7497 // we could say 'sizeof(array)-2'.
7498 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00007499 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00007500 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007501
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007502 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007503 llvm::raw_svector_ostream OS(sizeString);
7504 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007505 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00007506 OS << ")";
7507
7508 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7509 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7510 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00007511}
7512
Anna Zaks314cd092012-02-01 19:08:57 +00007513/// Check if two expressions refer to the same declaration.
7514static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7515 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7516 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7517 return D1->getDecl() == D2->getDecl();
7518 return false;
7519}
7520
7521static const Expr *getStrlenExprArg(const Expr *E) {
7522 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7523 const FunctionDecl *FD = CE->getDirectCallee();
7524 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00007525 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007526 return CE->getArg(0)->IgnoreParenCasts();
7527 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007528 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007529}
7530
7531// Warn on anti-patterns as the 'size' argument to strncat.
7532// The correct size argument should look like following:
7533// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7534void Sema::CheckStrncatArguments(const CallExpr *CE,
7535 IdentifierInfo *FnName) {
7536 // Don't crash if the user has the wrong number of arguments.
7537 if (CE->getNumArgs() < 3)
7538 return;
7539 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7540 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7541 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7542
Nico Weber0e6daef2013-12-26 23:38:39 +00007543 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7544 CE->getRParenLoc()))
7545 return;
7546
Anna Zaks314cd092012-02-01 19:08:57 +00007547 // Identify common expressions, which are wrongly used as the size argument
7548 // to strncat and may lead to buffer overflows.
7549 unsigned PatternType = 0;
7550 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7551 // - sizeof(dst)
7552 if (referToTheSameDecl(SizeOfArg, DstArg))
7553 PatternType = 1;
7554 // - sizeof(src)
7555 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7556 PatternType = 2;
7557 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7558 if (BE->getOpcode() == BO_Sub) {
7559 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7560 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7561 // - sizeof(dst) - strlen(dst)
7562 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7563 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7564 PatternType = 1;
7565 // - sizeof(src) - (anything)
7566 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7567 PatternType = 2;
7568 }
7569 }
7570
7571 if (PatternType == 0)
7572 return;
7573
Anna Zaks5069aa32012-02-03 01:27:37 +00007574 // Generate the diagnostic.
7575 SourceLocation SL = LenArg->getLocStart();
7576 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007577 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00007578
7579 // If the function is defined as a builtin macro, do not show macro expansion.
7580 if (SM.isMacroArgExpansion(SL)) {
7581 SL = SM.getSpellingLoc(SL);
7582 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7583 SM.getSpellingLoc(SR.getEnd()));
7584 }
7585
Anna Zaks13b08572012-08-08 21:42:23 +00007586 // Check if the destination is an array (rather than a pointer to an array).
7587 QualType DstTy = DstArg->getType();
7588 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7589 Context);
7590 if (!isKnownSizeArray) {
7591 if (PatternType == 1)
7592 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7593 else
7594 Diag(SL, diag::warn_strncat_src_size) << SR;
7595 return;
7596 }
7597
Anna Zaks314cd092012-02-01 19:08:57 +00007598 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00007599 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007600 else
Anna Zaks5069aa32012-02-03 01:27:37 +00007601 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007602
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007603 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00007604 llvm::raw_svector_ostream OS(sizeString);
7605 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007606 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007607 OS << ") - ";
7608 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007609 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007610 OS << ") - 1";
7611
Anna Zaks5069aa32012-02-03 01:27:37 +00007612 Diag(SL, diag::note_strncat_wrong_size)
7613 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00007614}
7615
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007616//===--- CHECK: Return Address of Stack Variable --------------------------===//
7617
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007618static const Expr *EvalVal(const Expr *E,
7619 SmallVectorImpl<const DeclRefExpr *> &refVars,
7620 const Decl *ParentDecl);
7621static const Expr *EvalAddr(const Expr *E,
7622 SmallVectorImpl<const DeclRefExpr *> &refVars,
7623 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007624
7625/// CheckReturnStackAddr - Check if a return statement returns the address
7626/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007627static void
7628CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7629 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00007630
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007631 const Expr *stackE = nullptr;
7632 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007633
7634 // Perform checking for returned stack addresses, local blocks,
7635 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00007636 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007637 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007638 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00007639 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007640 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007641 }
7642
Craig Topperc3ec1492014-05-26 06:22:03 +00007643 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007644 return; // Nothing suspicious was found.
7645
Simon Pilgrim750bde62017-03-31 11:00:53 +00007646 // Parameters are initialized in the calling scope, so taking the address
Richard Trieu81b6c562016-08-05 23:24:47 +00007647 // of a parameter reference doesn't need a warning.
7648 for (auto *DRE : refVars)
7649 if (isa<ParmVarDecl>(DRE->getDecl()))
7650 return;
7651
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007652 SourceLocation diagLoc;
7653 SourceRange diagRange;
7654 if (refVars.empty()) {
7655 diagLoc = stackE->getLocStart();
7656 diagRange = stackE->getSourceRange();
7657 } else {
7658 // We followed through a reference variable. 'stackE' contains the
7659 // problematic expression but we will warn at the return statement pointing
7660 // at the reference variable. We will later display the "trail" of
7661 // reference variables using notes.
7662 diagLoc = refVars[0]->getLocStart();
7663 diagRange = refVars[0]->getSourceRange();
7664 }
7665
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007666 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7667 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00007668 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007669 << DR->getDecl()->getDeclName() << diagRange;
7670 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007671 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007672 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007673 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007674 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00007675 // If there is an LValue->RValue conversion, then the value of the
7676 // reference type is used, not the reference.
7677 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7678 if (ICE->getCastKind() == CK_LValueToRValue) {
7679 return;
7680 }
7681 }
Craig Topperda7b27f2015-11-17 05:40:09 +00007682 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7683 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007684 }
7685
7686 // Display the "trail" of reference variables that we followed until we
7687 // found the problematic expression using notes.
7688 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007689 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007690 // If this var binds to another reference var, show the range of the next
7691 // var, otherwise the var binds to the problematic expression, in which case
7692 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007693 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7694 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007695 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7696 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007697 }
7698}
7699
7700/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7701/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007702/// to a location on the stack, a local block, an address of a label, or a
7703/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007704/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007705/// encounter a subexpression that (1) clearly does not lead to one of the
7706/// above problematic expressions (2) is something we cannot determine leads to
7707/// a problematic expression based on such local checking.
7708///
7709/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7710/// the expression that they point to. Such variables are added to the
7711/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007712///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007713/// EvalAddr processes expressions that are pointers that are used as
7714/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007715/// At the base case of the recursion is a check for the above problematic
7716/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007717///
7718/// This implementation handles:
7719///
7720/// * pointer-to-pointer casts
7721/// * implicit conversions from array references to pointers
7722/// * taking the address of fields
7723/// * arbitrary interplay between "&" and "*" operators
7724/// * pointer arithmetic from an address of a stack variable
7725/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007726static const Expr *EvalAddr(const Expr *E,
7727 SmallVectorImpl<const DeclRefExpr *> &refVars,
7728 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007729 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00007730 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007731
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007732 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00007733 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00007734 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007735 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00007736 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00007737
Peter Collingbourne91147592011-04-15 00:35:48 +00007738 E = E->IgnoreParens();
7739
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007740 // Our "symbolic interpreter" is just a dispatch off the currently
7741 // viewed AST node. We then recursively traverse the AST by calling
7742 // EvalAddr and EvalVal appropriately.
7743 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007744 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007745 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007746
Richard Smith40f08eb2014-01-30 22:05:38 +00007747 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00007748 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00007749 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00007750
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007751 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007752 // If this is a reference variable, follow through to the expression that
7753 // it points to.
7754 if (V->hasLocalStorage() &&
7755 V->getType()->isReferenceType() && V->hasInit()) {
7756 // Add the reference variable to the "trail".
7757 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007758 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007759 }
7760
Craig Topperc3ec1492014-05-26 06:22:03 +00007761 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007762 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007763
Chris Lattner934edb22007-12-28 05:31:15 +00007764 case Stmt::UnaryOperatorClass: {
7765 // The only unary operator that make sense to handle here
7766 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007767 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007768
John McCalle3027922010-08-25 11:45:40 +00007769 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007770 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007771 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007772 }
Mike Stump11289f42009-09-09 15:08:12 +00007773
Chris Lattner934edb22007-12-28 05:31:15 +00007774 case Stmt::BinaryOperatorClass: {
7775 // Handle pointer arithmetic. All other binary operators are not valid
7776 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007777 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00007778 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00007779
John McCalle3027922010-08-25 11:45:40 +00007780 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00007781 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007782
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007783 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00007784
7785 // Determine which argument is the real pointer base. It could be
7786 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007787 if (!Base->getType()->isPointerType())
7788 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00007789
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007790 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007791 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007792 }
Steve Naroff2752a172008-09-10 19:17:48 +00007793
Chris Lattner934edb22007-12-28 05:31:15 +00007794 // For conditional operators we need to see if either the LHS or RHS are
7795 // valid DeclRefExpr*s. If one of them is valid, we return it.
7796 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007797 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007798
Chris Lattner934edb22007-12-28 05:31:15 +00007799 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007800 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007801 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007802 // In C++, we can have a throw-expression, which has 'void' type.
7803 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007804 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007805 return LHS;
7806 }
Chris Lattner934edb22007-12-28 05:31:15 +00007807
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007808 // In C++, we can have a throw-expression, which has 'void' type.
7809 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00007810 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007811
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007812 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007813 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007814
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007815 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00007816 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007817 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00007818 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007819
7820 case Stmt::AddrLabelExprClass:
7821 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00007822
John McCall28fc7092011-11-10 05:35:25 +00007823 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007824 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7825 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00007826
Ted Kremenekc3b4c522008-08-07 00:49:01 +00007827 // For casts, we need to handle conversions from arrays to
7828 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00007829 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00007830 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007831 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00007832 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00007833 case Stmt::CXXStaticCastExprClass:
7834 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00007835 case Stmt::CXXConstCastExprClass:
7836 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007837 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00007838 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00007839 case CK_LValueToRValue:
7840 case CK_NoOp:
7841 case CK_BaseToDerived:
7842 case CK_DerivedToBase:
7843 case CK_UncheckedDerivedToBase:
7844 case CK_Dynamic:
7845 case CK_CPointerToObjCPointerCast:
7846 case CK_BlockPointerToObjCPointerCast:
7847 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007848 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007849
7850 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007851 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007852
Richard Trieudadefde2014-07-02 04:39:38 +00007853 case CK_BitCast:
7854 if (SubExpr->getType()->isAnyPointerType() ||
7855 SubExpr->getType()->isBlockPointerType() ||
7856 SubExpr->getType()->isObjCQualifiedIdType())
7857 return EvalAddr(SubExpr, refVars, ParentDecl);
7858 else
7859 return nullptr;
7860
Eli Friedman8195ad72012-02-23 23:04:32 +00007861 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007862 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00007863 }
Chris Lattner934edb22007-12-28 05:31:15 +00007864 }
Mike Stump11289f42009-09-09 15:08:12 +00007865
Douglas Gregorfe314812011-06-21 17:03:29 +00007866 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007867 if (const Expr *Result =
7868 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7869 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00007870 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00007871 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007872
Chris Lattner934edb22007-12-28 05:31:15 +00007873 // Everything else: we simply don't reason about them.
7874 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007875 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00007876 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007877}
Mike Stump11289f42009-09-09 15:08:12 +00007878
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007879/// EvalVal - This function is complements EvalAddr in the mutual recursion.
7880/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007881static const Expr *EvalVal(const Expr *E,
7882 SmallVectorImpl<const DeclRefExpr *> &refVars,
7883 const Decl *ParentDecl) {
7884 do {
7885 // We should only be called for evaluating non-pointer expressions, or
7886 // expressions with a pointer type that are not used as references but
7887 // instead
7888 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00007889
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007890 // Our "symbolic interpreter" is just a dispatch off the currently
7891 // viewed AST node. We then recursively traverse the AST by calling
7892 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00007893
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007894 E = E->IgnoreParens();
7895 switch (E->getStmtClass()) {
7896 case Stmt::ImplicitCastExprClass: {
7897 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7898 if (IE->getValueKind() == VK_LValue) {
7899 E = IE->getSubExpr();
7900 continue;
7901 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007902 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007903 }
Richard Smith40f08eb2014-01-30 22:05:38 +00007904
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007905 case Stmt::ExprWithCleanupsClass:
7906 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7907 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007908
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007909 case Stmt::DeclRefExprClass: {
7910 // When we hit a DeclRefExpr we are looking at code that refers to a
7911 // variable's name. If it's not a reference variable we check if it has
7912 // local storage within the function, and if so, return the expression.
7913 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7914
7915 // If we leave the immediate function, the lifetime isn't about to end.
7916 if (DR->refersToEnclosingVariableOrCapture())
7917 return nullptr;
7918
7919 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7920 // Check if it refers to itself, e.g. "int& i = i;".
7921 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007922 return DR;
7923
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007924 if (V->hasLocalStorage()) {
7925 if (!V->getType()->isReferenceType())
7926 return DR;
7927
7928 // Reference variable, follow through to the expression that
7929 // it points to.
7930 if (V->hasInit()) {
7931 // Add the reference variable to the "trail".
7932 refVars.push_back(DR);
7933 return EvalVal(V->getInit(), refVars, V);
7934 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007935 }
7936 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007937
7938 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007939 }
Mike Stump11289f42009-09-09 15:08:12 +00007940
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007941 case Stmt::UnaryOperatorClass: {
7942 // The only unary operator that make sense to handle here
7943 // is Deref. All others don't resolve to a "name." This includes
7944 // handling all sorts of rvalues passed to a unary operator.
7945 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007946
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007947 if (U->getOpcode() == UO_Deref)
7948 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007949
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007950 return nullptr;
7951 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007952
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007953 case Stmt::ArraySubscriptExprClass: {
7954 // Array subscripts are potential references to data on the stack. We
7955 // retrieve the DeclRefExpr* for the array variable if it indeed
7956 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00007957 const auto *ASE = cast<ArraySubscriptExpr>(E);
7958 if (ASE->isTypeDependent())
7959 return nullptr;
7960 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007961 }
Mike Stump11289f42009-09-09 15:08:12 +00007962
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007963 case Stmt::OMPArraySectionExprClass: {
7964 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7965 ParentDecl);
7966 }
Mike Stump11289f42009-09-09 15:08:12 +00007967
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007968 case Stmt::ConditionalOperatorClass: {
7969 // For conditional operators we need to see if either the LHS or RHS are
7970 // non-NULL Expr's. If one is non-NULL, we return it.
7971 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007972
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007973 // Handle the GNU extension for missing LHS.
7974 if (const Expr *LHSExpr = C->getLHS()) {
7975 // In C++, we can have a throw-expression, which has 'void' type.
7976 if (!LHSExpr->getType()->isVoidType())
7977 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7978 return LHS;
7979 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007980
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007981 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007982 if (C->getRHS()->getType()->isVoidType())
7983 return nullptr;
7984
7985 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007986 }
7987
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007988 // Accesses to members are potential references to data on the stack.
7989 case Stmt::MemberExprClass: {
7990 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00007991
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007992 // Check for indirect access. We only want direct field accesses.
7993 if (M->isArrow())
7994 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007995
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007996 // Check whether the member type is itself a reference, in which case
7997 // we're not going to refer to the member, but to what the member refers
7998 // to.
7999 if (M->getMemberDecl()->getType()->isReferenceType())
8000 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008001
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008002 return EvalVal(M->getBase(), refVars, ParentDecl);
8003 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00008004
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008005 case Stmt::MaterializeTemporaryExprClass:
8006 if (const Expr *Result =
8007 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8008 refVars, ParentDecl))
8009 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008010 return E;
8011
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008012 default:
8013 // Check that we don't return or take the address of a reference to a
8014 // temporary. This is only useful in C++.
8015 if (!E->isTypeDependent() && E->isRValue())
8016 return E;
8017
8018 // Everything else: we simply don't reason about them.
8019 return nullptr;
8020 }
8021 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008022}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008023
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008024void
8025Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8026 SourceLocation ReturnLoc,
8027 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00008028 const AttrVec *Attrs,
8029 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008030 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8031
8032 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00008033 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8034 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00008035 CheckNonNullExpr(*this, RetValExp))
8036 Diag(ReturnLoc, diag::warn_null_ret)
8037 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00008038
8039 // C++11 [basic.stc.dynamic.allocation]p4:
8040 // If an allocation function declared with a non-throwing
8041 // exception-specification fails to allocate storage, it shall return
8042 // a null pointer. Any other allocation function that fails to allocate
8043 // storage shall indicate failure only by throwing an exception [...]
8044 if (FD) {
8045 OverloadedOperatorKind Op = FD->getOverloadedOperator();
8046 if (Op == OO_New || Op == OO_Array_New) {
8047 const FunctionProtoType *Proto
8048 = FD->getType()->castAs<FunctionProtoType>();
8049 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
8050 CheckNonNullExpr(*this, RetValExp))
8051 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8052 << FD << getLangOpts().CPlusPlus11;
8053 }
8054 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008055}
8056
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008057//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8058
8059/// Check for comparisons of floating point operands using != and ==.
8060/// Issue a warning if these are no self-comparisons, as they are not likely
8061/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00008062void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00008063 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8064 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008065
8066 // Special case: check for x == x (which is OK).
8067 // Do not emit warnings for such cases.
8068 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8069 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8070 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00008071 return;
Mike Stump11289f42009-09-09 15:08:12 +00008072
Ted Kremenekeda40e22007-11-29 00:59:04 +00008073 // Special case: check for comparisons against literals that can be exactly
8074 // represented by APFloat. In such cases, do not emit a warning. This
8075 // is a heuristic: often comparison against such literals are used to
8076 // detect if a value in a variable has not changed. This clearly can
8077 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00008078 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8079 if (FLL->isExact())
8080 return;
8081 } else
8082 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8083 if (FLR->isExact())
8084 return;
Mike Stump11289f42009-09-09 15:08:12 +00008085
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008086 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00008087 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008088 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008089 return;
Mike Stump11289f42009-09-09 15:08:12 +00008090
David Blaikie1f4ff152012-07-16 20:47:22 +00008091 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008092 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008093 return;
Mike Stump11289f42009-09-09 15:08:12 +00008094
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008095 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00008096 Diag(Loc, diag::warn_floatingpoint_eq)
8097 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008098}
John McCallca01b222010-01-04 23:21:16 +00008099
John McCall70aa5392010-01-06 05:24:50 +00008100//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8101//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00008102
John McCall70aa5392010-01-06 05:24:50 +00008103namespace {
John McCallca01b222010-01-04 23:21:16 +00008104
John McCall70aa5392010-01-06 05:24:50 +00008105/// Structure recording the 'active' range of an integer-valued
8106/// expression.
8107struct IntRange {
8108 /// The number of bits active in the int.
8109 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00008110
John McCall70aa5392010-01-06 05:24:50 +00008111 /// True if the int is known not to have negative values.
8112 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00008113
John McCall70aa5392010-01-06 05:24:50 +00008114 IntRange(unsigned Width, bool NonNegative)
8115 : Width(Width), NonNegative(NonNegative)
8116 {}
John McCallca01b222010-01-04 23:21:16 +00008117
John McCall817d4af2010-11-10 23:38:19 +00008118 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00008119 static IntRange forBoolType() {
8120 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00008121 }
8122
John McCall817d4af2010-11-10 23:38:19 +00008123 /// Returns the range of an opaque value of the given integral type.
8124 static IntRange forValueOfType(ASTContext &C, QualType T) {
8125 return forValueOfCanonicalType(C,
8126 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00008127 }
8128
John McCall817d4af2010-11-10 23:38:19 +00008129 /// Returns the range of an opaque value of a canonical integral type.
8130 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00008131 assert(T->isCanonicalUnqualified());
8132
8133 if (const VectorType *VT = dyn_cast<VectorType>(T))
8134 T = VT->getElementType().getTypePtr();
8135 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8136 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008137 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8138 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00008139
David Majnemer6a426652013-06-07 22:07:20 +00008140 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00008141 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00008142 EnumDecl *Enum = ET->getDecl();
8143 if (!Enum->isCompleteDefinition())
8144 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00008145
David Majnemer6a426652013-06-07 22:07:20 +00008146 unsigned NumPositive = Enum->getNumPositiveBits();
8147 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00008148
David Majnemer6a426652013-06-07 22:07:20 +00008149 if (NumNegative == 0)
8150 return IntRange(NumPositive, true/*NonNegative*/);
8151 else
8152 return IntRange(std::max(NumPositive + 1, NumNegative),
8153 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00008154 }
John McCall70aa5392010-01-06 05:24:50 +00008155
8156 const BuiltinType *BT = cast<BuiltinType>(T);
8157 assert(BT->isInteger());
8158
8159 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8160 }
8161
John McCall817d4af2010-11-10 23:38:19 +00008162 /// Returns the "target" range of a canonical integral type, i.e.
8163 /// the range of values expressible in the type.
8164 ///
8165 /// This matches forValueOfCanonicalType except that enums have the
8166 /// full range of their type, not the range of their enumerators.
8167 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8168 assert(T->isCanonicalUnqualified());
8169
8170 if (const VectorType *VT = dyn_cast<VectorType>(T))
8171 T = VT->getElementType().getTypePtr();
8172 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8173 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008174 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8175 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008176 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00008177 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008178
8179 const BuiltinType *BT = cast<BuiltinType>(T);
8180 assert(BT->isInteger());
8181
8182 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8183 }
8184
8185 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00008186 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00008187 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00008188 L.NonNegative && R.NonNegative);
8189 }
8190
John McCall817d4af2010-11-10 23:38:19 +00008191 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008192 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008193 return IntRange(std::min(L.Width, R.Width),
8194 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008195 }
8196};
8197
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008198IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008199 if (value.isSigned() && value.isNegative())
8200 return IntRange(value.getMinSignedBits(), false);
8201
8202 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008203 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008204
8205 // isNonNegative() just checks the sign bit without considering
8206 // signedness.
8207 return IntRange(value.getActiveBits(), true);
8208}
8209
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008210IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8211 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008212 if (result.isInt())
8213 return GetValueRange(C, result.getInt(), MaxWidth);
8214
8215 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008216 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8217 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8218 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8219 R = IntRange::join(R, El);
8220 }
John McCall70aa5392010-01-06 05:24:50 +00008221 return R;
8222 }
8223
8224 if (result.isComplexInt()) {
8225 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8226 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8227 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008228 }
8229
8230 // This can happen with lossless casts to intptr_t of "based" lvalues.
8231 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008232 // FIXME: The only reason we need to pass the type in here is to get
8233 // the sign right on this one case. It would be nice if APValue
8234 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008235 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008236 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008237}
John McCall70aa5392010-01-06 05:24:50 +00008238
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008239QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008240 QualType Ty = E->getType();
8241 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8242 Ty = AtomicRHS->getValueType();
8243 return Ty;
8244}
8245
John McCall70aa5392010-01-06 05:24:50 +00008246/// Pseudo-evaluate the given integer expression, estimating the
8247/// range of values it might take.
8248///
8249/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008250IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008251 E = E->IgnoreParens();
8252
8253 // Try a full evaluation first.
8254 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008255 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008256 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008257
8258 // I think we only want to look through implicit casts here; if the
8259 // user has an explicit widening cast, we should treat the value as
8260 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008261 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00008262 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00008263 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8264
Eli Friedmane6d33952013-07-08 20:20:06 +00008265 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00008266
George Burgess IVdf1ed002016-01-13 01:52:39 +00008267 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8268 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00008269
John McCall70aa5392010-01-06 05:24:50 +00008270 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00008271 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00008272 return OutputTypeRange;
8273
8274 IntRange SubRange
8275 = GetExprRange(C, CE->getSubExpr(),
8276 std::min(MaxWidth, OutputTypeRange.Width));
8277
8278 // Bail out if the subexpr's range is as wide as the cast type.
8279 if (SubRange.Width >= OutputTypeRange.Width)
8280 return OutputTypeRange;
8281
8282 // Otherwise, we take the smaller width, and we're non-negative if
8283 // either the output type or the subexpr is.
8284 return IntRange(SubRange.Width,
8285 SubRange.NonNegative || OutputTypeRange.NonNegative);
8286 }
8287
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008288 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008289 // If we can fold the condition, just take that operand.
8290 bool CondResult;
8291 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8292 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8293 : CO->getFalseExpr(),
8294 MaxWidth);
8295
8296 // Otherwise, conservatively merge.
8297 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8298 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8299 return IntRange::join(L, R);
8300 }
8301
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008302 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008303 switch (BO->getOpcode()) {
8304
8305 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00008306 case BO_LAnd:
8307 case BO_LOr:
8308 case BO_LT:
8309 case BO_GT:
8310 case BO_LE:
8311 case BO_GE:
8312 case BO_EQ:
8313 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00008314 return IntRange::forBoolType();
8315
John McCallc3688382011-07-13 06:35:24 +00008316 // The type of the assignments is the type of the LHS, so the RHS
8317 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00008318 case BO_MulAssign:
8319 case BO_DivAssign:
8320 case BO_RemAssign:
8321 case BO_AddAssign:
8322 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00008323 case BO_XorAssign:
8324 case BO_OrAssign:
8325 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00008326 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00008327
John McCallc3688382011-07-13 06:35:24 +00008328 // Simple assignments just pass through the RHS, which will have
8329 // been coerced to the LHS type.
8330 case BO_Assign:
8331 // TODO: bitfields?
8332 return GetExprRange(C, BO->getRHS(), MaxWidth);
8333
John McCall70aa5392010-01-06 05:24:50 +00008334 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008335 case BO_PtrMemD:
8336 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00008337 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008338
John McCall2ce81ad2010-01-06 22:07:33 +00008339 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00008340 case BO_And:
8341 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00008342 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8343 GetExprRange(C, BO->getRHS(), MaxWidth));
8344
John McCall70aa5392010-01-06 05:24:50 +00008345 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00008346 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00008347 // ...except that we want to treat '1 << (blah)' as logically
8348 // positive. It's an important idiom.
8349 if (IntegerLiteral *I
8350 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8351 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008352 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00008353 return IntRange(R.Width, /*NonNegative*/ true);
8354 }
8355 }
8356 // fallthrough
8357
John McCalle3027922010-08-25 11:45:40 +00008358 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00008359 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008360
John McCall2ce81ad2010-01-06 22:07:33 +00008361 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00008362 case BO_Shr:
8363 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00008364 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8365
8366 // If the shift amount is a positive constant, drop the width by
8367 // that much.
8368 llvm::APSInt shift;
8369 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8370 shift.isNonNegative()) {
8371 unsigned zext = shift.getZExtValue();
8372 if (zext >= L.Width)
8373 L.Width = (L.NonNegative ? 0 : 1);
8374 else
8375 L.Width -= zext;
8376 }
8377
8378 return L;
8379 }
8380
8381 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008382 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008383 return GetExprRange(C, BO->getRHS(), MaxWidth);
8384
John McCall2ce81ad2010-01-06 22:07:33 +00008385 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008386 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008387 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008388 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008389 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008390
John McCall51431812011-07-14 22:39:48 +00008391 // The width of a division result is mostly determined by the size
8392 // of the LHS.
8393 case BO_Div: {
8394 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008395 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008396 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8397
8398 // If the divisor is constant, use that.
8399 llvm::APSInt divisor;
8400 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8401 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8402 if (log2 >= L.Width)
8403 L.Width = (L.NonNegative ? 0 : 1);
8404 else
8405 L.Width = std::min(L.Width - log2, MaxWidth);
8406 return L;
8407 }
8408
8409 // Otherwise, just use the LHS's width.
8410 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8411 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8412 }
8413
8414 // The result of a remainder can't be larger than the result of
8415 // either side.
8416 case BO_Rem: {
8417 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008418 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008419 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8420 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8421
8422 IntRange meet = IntRange::meet(L, R);
8423 meet.Width = std::min(meet.Width, MaxWidth);
8424 return meet;
8425 }
8426
8427 // The default behavior is okay for these.
8428 case BO_Mul:
8429 case BO_Add:
8430 case BO_Xor:
8431 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008432 break;
8433 }
8434
John McCall51431812011-07-14 22:39:48 +00008435 // The default case is to treat the operation as if it were closed
8436 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008437 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8438 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8439 return IntRange::join(L, R);
8440 }
8441
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008442 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008443 switch (UO->getOpcode()) {
8444 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008445 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008446 return IntRange::forBoolType();
8447
8448 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008449 case UO_Deref:
8450 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00008451 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008452
8453 default:
8454 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8455 }
8456 }
8457
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008458 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00008459 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8460
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008461 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00008462 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00008463 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00008464
Eli Friedmane6d33952013-07-08 20:20:06 +00008465 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008466}
John McCall263a48b2010-01-04 23:31:57 +00008467
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008468IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008469 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00008470}
8471
John McCall263a48b2010-01-04 23:31:57 +00008472/// Checks whether the given value, which currently has the given
8473/// source semantics, has the same value when coerced through the
8474/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008475bool IsSameFloatAfterCast(const llvm::APFloat &value,
8476 const llvm::fltSemantics &Src,
8477 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008478 llvm::APFloat truncated = value;
8479
8480 bool ignored;
8481 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8482 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8483
8484 return truncated.bitwiseIsEqual(value);
8485}
8486
8487/// Checks whether the given value, which currently has the given
8488/// source semantics, has the same value when coerced through the
8489/// target semantics.
8490///
8491/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008492bool IsSameFloatAfterCast(const APValue &value,
8493 const llvm::fltSemantics &Src,
8494 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008495 if (value.isFloat())
8496 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8497
8498 if (value.isVector()) {
8499 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8500 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8501 return false;
8502 return true;
8503 }
8504
8505 assert(value.isComplexFloat());
8506 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8507 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8508}
8509
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008510void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008511
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008512bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00008513 // Suppress cases where we are comparing against an enum constant.
8514 if (const DeclRefExpr *DR =
8515 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8516 if (isa<EnumConstantDecl>(DR->getDecl()))
8517 return false;
8518
8519 // Suppress cases where the '0' value is expanded from a macro.
8520 if (E->getLocStart().isMacroID())
8521 return false;
8522
John McCallcc7e5bf2010-05-06 08:58:33 +00008523 llvm::APSInt Value;
8524 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8525}
8526
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008527bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00008528 // Strip off implicit integral promotions.
8529 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008530 if (ICE->getCastKind() != CK_IntegralCast &&
8531 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00008532 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008533 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00008534 }
8535
8536 return E->getType()->isEnumeralType();
8537}
8538
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008539void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00008540 // Disable warning in template instantiations.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008541 if (S.inTemplateInstantiation())
Richard Trieu36594562013-11-01 21:47:19 +00008542 return;
8543
John McCalle3027922010-08-25 11:45:40 +00008544 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00008545 if (E->isValueDependent())
8546 return;
8547
John McCalle3027922010-08-25 11:45:40 +00008548 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008549 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008550 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008551 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008552 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008553 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008554 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008555 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008556 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008557 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008558 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008559 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008560 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008561 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008562 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008563 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8564 }
8565}
8566
Benjamin Kramer7320b992016-06-15 14:20:56 +00008567void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8568 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008569 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00008570 // Disable warning in template instantiations.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008571 if (S.inTemplateInstantiation())
Richard Trieudd51d742013-11-01 21:19:43 +00008572 return;
8573
Richard Trieu0f097742014-04-04 04:13:47 +00008574 // TODO: Investigate using GetExprRange() to get tighter bounds
8575 // on the bit ranges.
8576 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00008577 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00008578 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00008579 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8580 unsigned OtherWidth = OtherRange.Width;
8581
8582 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8583
Richard Trieu560910c2012-11-14 22:50:24 +00008584 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00008585 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00008586 return;
8587
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008588 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00008589 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008590
Richard Trieu0f097742014-04-04 04:13:47 +00008591 // Used for diagnostic printout.
8592 enum {
8593 LiteralConstant = 0,
8594 CXXBoolLiteralTrue,
8595 CXXBoolLiteralFalse
8596 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008597
Richard Trieu0f097742014-04-04 04:13:47 +00008598 if (!OtherIsBooleanType) {
8599 QualType ConstantT = Constant->getType();
8600 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00008601
Richard Trieu0f097742014-04-04 04:13:47 +00008602 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8603 return;
8604 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8605 "comparison with non-integer type");
8606
8607 bool ConstantSigned = ConstantT->isSignedIntegerType();
8608 bool CommonSigned = CommonT->isSignedIntegerType();
8609
8610 bool EqualityOnly = false;
8611
8612 if (CommonSigned) {
8613 // The common type is signed, therefore no signed to unsigned conversion.
8614 if (!OtherRange.NonNegative) {
8615 // Check that the constant is representable in type OtherT.
8616 if (ConstantSigned) {
8617 if (OtherWidth >= Value.getMinSignedBits())
8618 return;
8619 } else { // !ConstantSigned
8620 if (OtherWidth >= Value.getActiveBits() + 1)
8621 return;
8622 }
8623 } else { // !OtherSigned
8624 // Check that the constant is representable in type OtherT.
8625 // Negative values are out of range.
8626 if (ConstantSigned) {
8627 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8628 return;
8629 } else { // !ConstantSigned
8630 if (OtherWidth >= Value.getActiveBits())
8631 return;
8632 }
Richard Trieu560910c2012-11-14 22:50:24 +00008633 }
Richard Trieu0f097742014-04-04 04:13:47 +00008634 } else { // !CommonSigned
8635 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00008636 if (OtherWidth >= Value.getActiveBits())
8637 return;
Craig Toppercf360162014-06-18 05:13:11 +00008638 } else { // OtherSigned
8639 assert(!ConstantSigned &&
8640 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00008641 // Check to see if the constant is representable in OtherT.
8642 if (OtherWidth > Value.getActiveBits())
8643 return;
8644 // Check to see if the constant is equivalent to a negative value
8645 // cast to CommonT.
8646 if (S.Context.getIntWidth(ConstantT) ==
8647 S.Context.getIntWidth(CommonT) &&
8648 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8649 return;
8650 // The constant value rests between values that OtherT can represent
8651 // after conversion. Relational comparison still works, but equality
8652 // comparisons will be tautological.
8653 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008654 }
8655 }
Richard Trieu0f097742014-04-04 04:13:47 +00008656
8657 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8658
8659 if (op == BO_EQ || op == BO_NE) {
8660 IsTrue = op == BO_NE;
8661 } else if (EqualityOnly) {
8662 return;
8663 } else if (RhsConstant) {
8664 if (op == BO_GT || op == BO_GE)
8665 IsTrue = !PositiveConstant;
8666 else // op == BO_LT || op == BO_LE
8667 IsTrue = PositiveConstant;
8668 } else {
8669 if (op == BO_LT || op == BO_LE)
8670 IsTrue = !PositiveConstant;
8671 else // op == BO_GT || op == BO_GE
8672 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008673 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008674 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00008675 // Other isKnownToHaveBooleanValue
8676 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8677 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8678 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8679
8680 static const struct LinkedConditions {
8681 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8682 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8683 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8684 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8685 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8686 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8687
8688 } TruthTable = {
8689 // Constant on LHS. | Constant on RHS. |
8690 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
8691 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8692 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8693 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8694 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8695 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8696 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8697 };
8698
8699 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8700
8701 enum ConstantValue ConstVal = Zero;
8702 if (Value.isUnsigned() || Value.isNonNegative()) {
8703 if (Value == 0) {
8704 LiteralOrBoolConstant =
8705 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8706 ConstVal = Zero;
8707 } else if (Value == 1) {
8708 LiteralOrBoolConstant =
8709 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8710 ConstVal = One;
8711 } else {
8712 LiteralOrBoolConstant = LiteralConstant;
8713 ConstVal = GT_One;
8714 }
8715 } else {
8716 ConstVal = LT_Zero;
8717 }
8718
8719 CompareBoolWithConstantResult CmpRes;
8720
8721 switch (op) {
8722 case BO_LT:
8723 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8724 break;
8725 case BO_GT:
8726 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8727 break;
8728 case BO_LE:
8729 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8730 break;
8731 case BO_GE:
8732 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8733 break;
8734 case BO_EQ:
8735 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8736 break;
8737 case BO_NE:
8738 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8739 break;
8740 default:
8741 CmpRes = Unkwn;
8742 break;
8743 }
8744
8745 if (CmpRes == AFals) {
8746 IsTrue = false;
8747 } else if (CmpRes == ATrue) {
8748 IsTrue = true;
8749 } else {
8750 return;
8751 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008752 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008753
8754 // If this is a comparison to an enum constant, include that
8755 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00008756 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008757 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8758 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8759
8760 SmallString<64> PrettySourceValue;
8761 llvm::raw_svector_ostream OS(PrettySourceValue);
8762 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00008763 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008764 else
8765 OS << Value;
8766
Richard Trieu0f097742014-04-04 04:13:47 +00008767 S.DiagRuntimeBehavior(
8768 E->getOperatorLoc(), E,
8769 S.PDiag(diag::warn_out_of_range_compare)
8770 << OS.str() << LiteralOrBoolConstant
8771 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8772 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008773}
8774
John McCallcc7e5bf2010-05-06 08:58:33 +00008775/// Analyze the operands of the given comparison. Implements the
8776/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008777void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00008778 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8779 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008780}
John McCall263a48b2010-01-04 23:31:57 +00008781
John McCallca01b222010-01-04 23:21:16 +00008782/// \brief Implements -Wsign-compare.
8783///
Richard Trieu82402a02011-09-15 21:56:47 +00008784/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008785void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008786 // The type the comparison is being performed in.
8787 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00008788
8789 // Only analyze comparison operators where both sides have been converted to
8790 // the same type.
8791 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8792 return AnalyzeImpConvsInComparison(S, E);
8793
8794 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00008795 if (E->isValueDependent())
8796 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008797
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008798 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8799 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008800
8801 bool IsComparisonConstant = false;
8802
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008803 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008804 // of 'true' or 'false'.
8805 if (T->isIntegralType(S.Context)) {
8806 llvm::APSInt RHSValue;
8807 bool IsRHSIntegralLiteral =
8808 RHS->isIntegerConstantExpr(RHSValue, S.Context);
8809 llvm::APSInt LHSValue;
8810 bool IsLHSIntegralLiteral =
8811 LHS->isIntegerConstantExpr(LHSValue, S.Context);
8812 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8813 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8814 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8815 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8816 else
8817 IsComparisonConstant =
8818 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008819 } else if (!T->hasUnsignedIntegerRepresentation())
8820 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008821
John McCallcc7e5bf2010-05-06 08:58:33 +00008822 // We don't do anything special if this isn't an unsigned integral
8823 // comparison: we're only interested in integral comparisons, and
8824 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00008825 //
8826 // We also don't care about value-dependent expressions or expressions
8827 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008828 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00008829 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008830
John McCallcc7e5bf2010-05-06 08:58:33 +00008831 // Check to see if one of the (unmodified) operands is of different
8832 // signedness.
8833 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00008834 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8835 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00008836 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00008837 signedOperand = LHS;
8838 unsignedOperand = RHS;
8839 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8840 signedOperand = RHS;
8841 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00008842 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00008843 CheckTrivialUnsignedComparison(S, E);
8844 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008845 }
8846
John McCallcc7e5bf2010-05-06 08:58:33 +00008847 // Otherwise, calculate the effective range of the signed operand.
8848 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00008849
John McCallcc7e5bf2010-05-06 08:58:33 +00008850 // Go ahead and analyze implicit conversions in the operands. Note
8851 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00008852 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8853 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00008854
John McCallcc7e5bf2010-05-06 08:58:33 +00008855 // If the signed range is non-negative, -Wsign-compare won't fire,
8856 // but we should still check for comparisons which are always true
8857 // or false.
8858 if (signedRange.NonNegative)
8859 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008860
8861 // For (in)equality comparisons, if the unsigned operand is a
8862 // constant which cannot collide with a overflowed signed operand,
8863 // then reinterpreting the signed operand as unsigned will not
8864 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00008865 if (E->isEqualityOp()) {
8866 unsigned comparisonWidth = S.Context.getIntWidth(T);
8867 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00008868
John McCallcc7e5bf2010-05-06 08:58:33 +00008869 // We should never be unable to prove that the unsigned operand is
8870 // non-negative.
8871 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8872
8873 if (unsignedRange.Width < comparisonWidth)
8874 return;
8875 }
8876
Douglas Gregorbfb4a212012-05-01 01:53:49 +00008877 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8878 S.PDiag(diag::warn_mixed_sign_comparison)
8879 << LHS->getType() << RHS->getType()
8880 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00008881}
8882
John McCall1f425642010-11-11 03:21:53 +00008883/// Analyzes an attempt to assign the given value to a bitfield.
8884///
8885/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008886bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8887 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00008888 assert(Bitfield->isBitField());
8889 if (Bitfield->isInvalidDecl())
8890 return false;
8891
John McCalldeebbcf2010-11-11 05:33:51 +00008892 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00008893 QualType BitfieldType = Bitfield->getType();
8894 if (BitfieldType->isBooleanType())
8895 return false;
8896
8897 if (BitfieldType->isEnumeralType()) {
8898 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
8899 // If the underlying enum type was not explicitly specified as an unsigned
8900 // type and the enum contain only positive values, MSVC++ will cause an
8901 // inconsistency by storing this as a signed type.
8902 if (S.getLangOpts().CPlusPlus11 &&
8903 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
8904 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
8905 BitfieldEnumDecl->getNumNegativeBits() == 0) {
8906 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
8907 << BitfieldEnumDecl->getNameAsString();
8908 }
8909 }
8910
John McCalldeebbcf2010-11-11 05:33:51 +00008911 if (Bitfield->getType()->isBooleanType())
8912 return false;
8913
Douglas Gregor789adec2011-02-04 13:09:01 +00008914 // Ignore value- or type-dependent expressions.
8915 if (Bitfield->getBitWidth()->isValueDependent() ||
8916 Bitfield->getBitWidth()->isTypeDependent() ||
8917 Init->isValueDependent() ||
8918 Init->isTypeDependent())
8919 return false;
8920
John McCall1f425642010-11-11 03:21:53 +00008921 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00008922 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00008923
Richard Smith5fab0c92011-12-28 19:48:30 +00008924 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00008925 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
8926 Expr::SE_AllowSideEffects)) {
8927 // The RHS is not constant. If the RHS has an enum type, make sure the
8928 // bitfield is wide enough to hold all the values of the enum without
8929 // truncation.
8930 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
8931 EnumDecl *ED = EnumTy->getDecl();
8932 bool SignedBitfield = BitfieldType->isSignedIntegerType();
8933
8934 // Enum types are implicitly signed on Windows, so check if there are any
8935 // negative enumerators to see if the enum was intended to be signed or
8936 // not.
8937 bool SignedEnum = ED->getNumNegativeBits() > 0;
8938
8939 // Check for surprising sign changes when assigning enum values to a
8940 // bitfield of different signedness. If the bitfield is signed and we
8941 // have exactly the right number of bits to store this unsigned enum,
8942 // suggest changing the enum to an unsigned type. This typically happens
8943 // on Windows where unfixed enums always use an underlying type of 'int'.
8944 unsigned DiagID = 0;
8945 if (SignedEnum && !SignedBitfield) {
8946 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
8947 } else if (SignedBitfield && !SignedEnum &&
8948 ED->getNumPositiveBits() == FieldWidth) {
8949 DiagID = diag::warn_signed_bitfield_enum_conversion;
8950 }
8951
8952 if (DiagID) {
8953 S.Diag(InitLoc, DiagID) << Bitfield << ED;
8954 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
8955 SourceRange TypeRange =
8956 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
8957 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
8958 << SignedEnum << TypeRange;
8959 }
8960
8961 // Compute the required bitwidth. If the enum has negative values, we need
8962 // one more bit than the normal number of positive bits to represent the
8963 // sign bit.
8964 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
8965 ED->getNumNegativeBits())
8966 : ED->getNumPositiveBits();
8967
8968 // Check the bitwidth.
8969 if (BitsNeeded > FieldWidth) {
8970 Expr *WidthExpr = Bitfield->getBitWidth();
8971 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
8972 << Bitfield << ED;
8973 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
8974 << BitsNeeded << ED << WidthExpr->getSourceRange();
8975 }
8976 }
8977
John McCall1f425642010-11-11 03:21:53 +00008978 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00008979 }
John McCall1f425642010-11-11 03:21:53 +00008980
John McCall1f425642010-11-11 03:21:53 +00008981 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00008982
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008983 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00008984 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008985 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8986 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00008987
John McCall1f425642010-11-11 03:21:53 +00008988 if (OriginalWidth <= FieldWidth)
8989 return false;
8990
Eli Friedmanc267a322012-01-26 23:11:39 +00008991 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00008992 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00008993 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00008994
Eli Friedmanc267a322012-01-26 23:11:39 +00008995 // Check whether the stored value is equal to the original value.
8996 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00008997 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00008998 return false;
8999
Eli Friedmanc267a322012-01-26 23:11:39 +00009000 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00009001 // therefore don't strictly fit into a signed bitfield of width 1.
9002 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00009003 return false;
9004
John McCall1f425642010-11-11 03:21:53 +00009005 std::string PrettyValue = Value.toString(10);
9006 std::string PrettyTrunc = TruncatedValue.toString(10);
9007
9008 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9009 << PrettyValue << PrettyTrunc << OriginalInit->getType()
9010 << Init->getSourceRange();
9011
9012 return true;
9013}
9014
John McCalld2a53122010-11-09 23:24:47 +00009015/// Analyze the given simple or compound assignment for warning-worthy
9016/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009017void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00009018 // Just recurse on the LHS.
9019 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9020
9021 // We want to recurse on the RHS as normal unless we're assigning to
9022 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00009023 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009024 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00009025 E->getOperatorLoc())) {
9026 // Recurse, ignoring any implicit conversions on the RHS.
9027 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9028 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00009029 }
9030 }
9031
9032 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9033}
9034
John McCall263a48b2010-01-04 23:31:57 +00009035/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009036void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9037 SourceLocation CContext, unsigned diag,
9038 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009039 if (pruneControlFlow) {
9040 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9041 S.PDiag(diag)
9042 << SourceType << T << E->getSourceRange()
9043 << SourceRange(CContext));
9044 return;
9045 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00009046 S.Diag(E->getExprLoc(), diag)
9047 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9048}
9049
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009050/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009051void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
9052 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009053 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009054}
9055
Richard Trieube234c32016-04-21 21:04:55 +00009056
9057/// Diagnose an implicit cast from a floating point value to an integer value.
9058void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9059
9060 SourceLocation CContext) {
9061 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00009062 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00009063
9064 Expr *InnerE = E->IgnoreParenImpCasts();
9065 // We also want to warn on, e.g., "int i = -1.234"
9066 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9067 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9068 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9069
9070 const bool IsLiteral =
9071 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9072
9073 llvm::APFloat Value(0.0);
9074 bool IsConstant =
9075 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9076 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00009077 return DiagnoseImpCast(S, E, T, CContext,
9078 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00009079 }
9080
Chandler Carruth016ef402011-04-10 08:36:24 +00009081 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00009082
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00009083 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9084 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00009085 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
9086 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00009087 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00009088 if (IsLiteral) return;
9089 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9090 PruneWarnings);
9091 }
9092
9093 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00009094 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00009095 // Warn on floating point literal to integer.
9096 DiagID = diag::warn_impcast_literal_float_to_integer;
9097 } else if (IntegerValue == 0) {
9098 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
9099 return DiagnoseImpCast(S, E, T, CContext,
9100 diag::warn_impcast_float_integer, PruneWarnings);
9101 }
9102 // Warn on non-zero to zero conversion.
9103 DiagID = diag::warn_impcast_float_to_integer_zero;
9104 } else {
9105 if (IntegerValue.isUnsigned()) {
9106 if (!IntegerValue.isMaxValue()) {
9107 return DiagnoseImpCast(S, E, T, CContext,
9108 diag::warn_impcast_float_integer, PruneWarnings);
9109 }
9110 } else { // IntegerValue.isSigned()
9111 if (!IntegerValue.isMaxSignedValue() &&
9112 !IntegerValue.isMinSignedValue()) {
9113 return DiagnoseImpCast(S, E, T, CContext,
9114 diag::warn_impcast_float_integer, PruneWarnings);
9115 }
9116 }
9117 // Warn on evaluatable floating point expression to integer conversion.
9118 DiagID = diag::warn_impcast_float_to_integer;
9119 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009120
Eli Friedman07185912013-08-29 23:44:43 +00009121 // FIXME: Force the precision of the source value down so we don't print
9122 // digits which are usually useless (we don't really care here if we
9123 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9124 // would automatically print the shortest representation, but it's a bit
9125 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00009126 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00009127 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9128 precision = (precision * 59 + 195) / 196;
9129 Value.toString(PrettySourceValue, precision);
9130
David Blaikie9b88cc02012-05-15 17:18:27 +00009131 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00009132 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00009133 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00009134 else
David Blaikie9b88cc02012-05-15 17:18:27 +00009135 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00009136
Richard Trieube234c32016-04-21 21:04:55 +00009137 if (PruneWarnings) {
9138 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9139 S.PDiag(DiagID)
9140 << E->getType() << T.getUnqualifiedType()
9141 << PrettySourceValue << PrettyTargetValue
9142 << E->getSourceRange() << SourceRange(CContext));
9143 } else {
9144 S.Diag(E->getExprLoc(), DiagID)
9145 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9146 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9147 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009148}
9149
John McCall18a2c2c2010-11-09 22:22:12 +00009150std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
9151 if (!Range.Width) return "0";
9152
9153 llvm::APSInt ValueInRange = Value;
9154 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00009155 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00009156 return ValueInRange.toString(10);
9157}
9158
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009159bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009160 if (!isa<ImplicitCastExpr>(Ex))
9161 return false;
9162
9163 Expr *InnerE = Ex->IgnoreParenImpCasts();
9164 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9165 const Type *Source =
9166 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9167 if (Target->isDependentType())
9168 return false;
9169
9170 const BuiltinType *FloatCandidateBT =
9171 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9172 const Type *BoolCandidateType = ToBool ? Target : Source;
9173
9174 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9175 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9176}
9177
9178void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9179 SourceLocation CC) {
9180 unsigned NumArgs = TheCall->getNumArgs();
9181 for (unsigned i = 0; i < NumArgs; ++i) {
9182 Expr *CurrA = TheCall->getArg(i);
9183 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9184 continue;
9185
9186 bool IsSwapped = ((i > 0) &&
9187 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9188 IsSwapped |= ((i < (NumArgs - 1)) &&
9189 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9190 if (IsSwapped) {
9191 // Warn on this floating-point to bool conversion.
9192 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9193 CurrA->getType(), CC,
9194 diag::warn_impcast_floating_point_to_bool);
9195 }
9196 }
9197}
9198
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009199void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009200 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9201 E->getExprLoc()))
9202 return;
9203
Richard Trieu09d6b802016-01-08 23:35:06 +00009204 // Don't warn on functions which have return type nullptr_t.
9205 if (isa<CallExpr>(E))
9206 return;
9207
Richard Trieu5b993502014-10-15 03:42:06 +00009208 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9209 const Expr::NullPointerConstantKind NullKind =
9210 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9211 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9212 return;
9213
9214 // Return if target type is a safe conversion.
9215 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9216 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9217 return;
9218
9219 SourceLocation Loc = E->getSourceRange().getBegin();
9220
Richard Trieu0a5e1662016-02-13 00:58:53 +00009221 // Venture through the macro stacks to get to the source of macro arguments.
9222 // The new location is a better location than the complete location that was
9223 // passed in.
9224 while (S.SourceMgr.isMacroArgExpansion(Loc))
9225 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
9226
9227 while (S.SourceMgr.isMacroArgExpansion(CC))
9228 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
9229
Richard Trieu5b993502014-10-15 03:42:06 +00009230 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00009231 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9232 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9233 Loc, S.SourceMgr, S.getLangOpts());
9234 if (MacroName == "NULL")
9235 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00009236 }
9237
9238 // Only warn if the null and context location are in the same macro expansion.
9239 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9240 return;
9241
9242 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9243 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
9244 << FixItHint::CreateReplacement(Loc,
9245 S.getFixItZeroLiteralForType(T, Loc));
9246}
9247
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009248void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9249 ObjCArrayLiteral *ArrayLiteral);
9250void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9251 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00009252
9253/// Check a single element within a collection literal against the
9254/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009255void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
9256 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009257 // Skip a bitcast to 'id' or qualified 'id'.
9258 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9259 if (ICE->getCastKind() == CK_BitCast &&
9260 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9261 Element = ICE->getSubExpr();
9262 }
9263
9264 QualType ElementType = Element->getType();
9265 ExprResult ElementResult(Element);
9266 if (ElementType->getAs<ObjCObjectPointerType>() &&
9267 S.CheckSingleAssignmentConstraints(TargetElementType,
9268 ElementResult,
9269 false, false)
9270 != Sema::Compatible) {
9271 S.Diag(Element->getLocStart(),
9272 diag::warn_objc_collection_literal_element)
9273 << ElementType << ElementKind << TargetElementType
9274 << Element->getSourceRange();
9275 }
9276
9277 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9278 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9279 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9280 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9281}
9282
9283/// Check an Objective-C array literal being converted to the given
9284/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009285void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9286 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009287 if (!S.NSArrayDecl)
9288 return;
9289
9290 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9291 if (!TargetObjCPtr)
9292 return;
9293
9294 if (TargetObjCPtr->isUnspecialized() ||
9295 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9296 != S.NSArrayDecl->getCanonicalDecl())
9297 return;
9298
9299 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9300 if (TypeArgs.size() != 1)
9301 return;
9302
9303 QualType TargetElementType = TypeArgs[0];
9304 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9305 checkObjCCollectionLiteralElement(S, TargetElementType,
9306 ArrayLiteral->getElement(I),
9307 0);
9308 }
9309}
9310
9311/// Check an Objective-C dictionary literal being converted to the given
9312/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009313void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9314 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009315 if (!S.NSDictionaryDecl)
9316 return;
9317
9318 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9319 if (!TargetObjCPtr)
9320 return;
9321
9322 if (TargetObjCPtr->isUnspecialized() ||
9323 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9324 != S.NSDictionaryDecl->getCanonicalDecl())
9325 return;
9326
9327 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9328 if (TypeArgs.size() != 2)
9329 return;
9330
9331 QualType TargetKeyType = TypeArgs[0];
9332 QualType TargetObjectType = TypeArgs[1];
9333 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9334 auto Element = DictionaryLiteral->getKeyValueElement(I);
9335 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9336 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9337 }
9338}
9339
Richard Trieufc404c72016-02-05 23:02:38 +00009340// Helper function to filter out cases for constant width constant conversion.
9341// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009342bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9343 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00009344 // If initializing from a constant, and the constant starts with '0',
9345 // then it is a binary, octal, or hexadecimal. Allow these constants
9346 // to fill all the bits, even if there is a sign change.
9347 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9348 const char FirstLiteralCharacter =
9349 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9350 if (FirstLiteralCharacter == '0')
9351 return false;
9352 }
9353
9354 // If the CC location points to a '{', and the type is char, then assume
9355 // assume it is an array initialization.
9356 if (CC.isValid() && T->isCharType()) {
9357 const char FirstContextCharacter =
9358 S.getSourceManager().getCharacterData(CC)[0];
9359 if (FirstContextCharacter == '{')
9360 return false;
9361 }
9362
9363 return true;
9364}
9365
John McCallcc7e5bf2010-05-06 08:58:33 +00009366void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00009367 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009368 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00009369
John McCallcc7e5bf2010-05-06 08:58:33 +00009370 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9371 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9372 if (Source == Target) return;
9373 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00009374
Chandler Carruthc22845a2011-07-26 05:40:03 +00009375 // If the conversion context location is invalid don't complain. We also
9376 // don't want to emit a warning if the issue occurs from the expansion of
9377 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9378 // delay this check as long as possible. Once we detect we are in that
9379 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009380 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00009381 return;
9382
Richard Trieu021baa32011-09-23 20:10:00 +00009383 // Diagnose implicit casts to bool.
9384 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9385 if (isa<StringLiteral>(E))
9386 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00009387 // and expressions, for instance, assert(0 && "error here"), are
9388 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00009389 return DiagnoseImpCast(S, E, T, CC,
9390 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00009391 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9392 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9393 // This covers the literal expressions that evaluate to Objective-C
9394 // objects.
9395 return DiagnoseImpCast(S, E, T, CC,
9396 diag::warn_impcast_objective_c_literal_to_bool);
9397 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009398 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9399 // Warn on pointer to bool conversion that is always true.
9400 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9401 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00009402 }
Richard Trieu021baa32011-09-23 20:10:00 +00009403 }
John McCall263a48b2010-01-04 23:31:57 +00009404
Douglas Gregor5054cb02015-07-07 03:58:22 +00009405 // Check implicit casts from Objective-C collection literals to specialized
9406 // collection types, e.g., NSArray<NSString *> *.
9407 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9408 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9409 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9410 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9411
John McCall263a48b2010-01-04 23:31:57 +00009412 // Strip vector types.
9413 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009414 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009415 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009416 return;
John McCallacf0ee52010-10-08 02:01:28 +00009417 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009418 }
Chris Lattneree7286f2011-06-14 04:51:15 +00009419
9420 // If the vector cast is cast between two vectors of the same size, it is
9421 // a bitcast, not a conversion.
9422 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9423 return;
John McCall263a48b2010-01-04 23:31:57 +00009424
9425 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9426 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9427 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00009428 if (auto VecTy = dyn_cast<VectorType>(Target))
9429 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00009430
9431 // Strip complex types.
9432 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009433 if (!isa<ComplexType>(Target)) {
Tim Northover02416372017-08-08 23:18:05 +00009434 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009435 return;
9436
Tim Northover02416372017-08-08 23:18:05 +00009437 return DiagnoseImpCast(S, E, T, CC,
9438 S.getLangOpts().CPlusPlus
9439 ? diag::err_impcast_complex_scalar
9440 : diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009441 }
John McCall263a48b2010-01-04 23:31:57 +00009442
9443 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9444 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9445 }
9446
9447 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9448 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9449
9450 // If the source is floating point...
9451 if (SourceBT && SourceBT->isFloatingPoint()) {
9452 // ...and the target is floating point...
9453 if (TargetBT && TargetBT->isFloatingPoint()) {
9454 // ...then warn if we're dropping FP rank.
9455
9456 // Builtin FP kinds are ordered by increasing FP rank.
9457 if (SourceBT->getKind() > TargetBT->getKind()) {
9458 // Don't warn about float constants that are precisely
9459 // representable in the target type.
9460 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009461 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00009462 // Value might be a float, a float vector, or a float complex.
9463 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00009464 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9465 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00009466 return;
9467 }
9468
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009469 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009470 return;
9471
John McCallacf0ee52010-10-08 02:01:28 +00009472 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00009473 }
9474 // ... or possibly if we're increasing rank, too
9475 else if (TargetBT->getKind() > SourceBT->getKind()) {
9476 if (S.SourceMgr.isInSystemMacro(CC))
9477 return;
9478
9479 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00009480 }
9481 return;
9482 }
9483
Richard Trieube234c32016-04-21 21:04:55 +00009484 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00009485 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009486 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009487 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00009488
Richard Trieube234c32016-04-21 21:04:55 +00009489 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00009490 }
John McCall263a48b2010-01-04 23:31:57 +00009491
Richard Smith54894fd2015-12-30 01:06:52 +00009492 // Detect the case where a call result is converted from floating-point to
9493 // to bool, and the final argument to the call is converted from bool, to
9494 // discover this typo:
9495 //
9496 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9497 //
9498 // FIXME: This is an incredibly special case; is there some more general
9499 // way to detect this class of misplaced-parentheses bug?
9500 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009501 // Check last argument of function call to see if it is an
9502 // implicit cast from a type matching the type the result
9503 // is being cast to.
9504 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00009505 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009506 Expr *LastA = CEx->getArg(NumArgs - 1);
9507 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00009508 if (isa<ImplicitCastExpr>(LastA) &&
9509 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009510 // Warn on this floating-point to bool conversion
9511 DiagnoseImpCast(S, E, T, CC,
9512 diag::warn_impcast_floating_point_to_bool);
9513 }
9514 }
9515 }
John McCall263a48b2010-01-04 23:31:57 +00009516 return;
9517 }
9518
Richard Trieu5b993502014-10-15 03:42:06 +00009519 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00009520
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009521 S.DiscardMisalignedMemberAddress(Target, E);
9522
David Blaikie9366d2b2012-06-19 21:19:06 +00009523 if (!Source->isIntegerType() || !Target->isIntegerType())
9524 return;
9525
David Blaikie7555b6a2012-05-15 16:56:36 +00009526 // TODO: remove this early return once the false positives for constant->bool
9527 // in templates, macros, etc, are reduced or removed.
9528 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9529 return;
9530
John McCallcc7e5bf2010-05-06 08:58:33 +00009531 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00009532 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00009533
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009534 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00009535 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009536 // TODO: this should happen for bitfield stores, too.
9537 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00009538 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009539 if (S.SourceMgr.isInSystemMacro(CC))
9540 return;
9541
John McCall18a2c2c2010-11-09 22:22:12 +00009542 std::string PrettySourceValue = Value.toString(10);
9543 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009544
Ted Kremenek33ba9952011-10-22 02:37:33 +00009545 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9546 S.PDiag(diag::warn_impcast_integer_precision_constant)
9547 << PrettySourceValue << PrettyTargetValue
9548 << E->getType() << T << E->getSourceRange()
9549 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00009550 return;
9551 }
9552
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009553 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9554 if (S.SourceMgr.isInSystemMacro(CC))
9555 return;
9556
David Blaikie9455da02012-04-12 22:40:54 +00009557 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00009558 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9559 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00009560 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00009561 }
9562
Richard Trieudcb55572016-01-29 23:51:16 +00009563 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9564 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9565 // Warn when doing a signed to signed conversion, warn if the positive
9566 // source value is exactly the width of the target type, which will
9567 // cause a negative value to be stored.
9568
9569 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00009570 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9571 !S.SourceMgr.isInSystemMacro(CC)) {
9572 if (isSameWidthConstantConversion(S, E, T, CC)) {
9573 std::string PrettySourceValue = Value.toString(10);
9574 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00009575
Richard Trieufc404c72016-02-05 23:02:38 +00009576 S.DiagRuntimeBehavior(
9577 E->getExprLoc(), E,
9578 S.PDiag(diag::warn_impcast_integer_precision_constant)
9579 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9580 << E->getSourceRange() << clang::SourceRange(CC));
9581 return;
Richard Trieudcb55572016-01-29 23:51:16 +00009582 }
9583 }
Richard Trieufc404c72016-02-05 23:02:38 +00009584
Richard Trieudcb55572016-01-29 23:51:16 +00009585 // Fall through for non-constants to give a sign conversion warning.
9586 }
9587
John McCallcc7e5bf2010-05-06 08:58:33 +00009588 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9589 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9590 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009591 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009592 return;
9593
John McCallcc7e5bf2010-05-06 08:58:33 +00009594 unsigned DiagID = diag::warn_impcast_integer_sign;
9595
9596 // Traditionally, gcc has warned about this under -Wsign-compare.
9597 // We also want to warn about it in -Wconversion.
9598 // So if -Wconversion is off, use a completely identical diagnostic
9599 // in the sign-compare group.
9600 // The conditional-checking code will
9601 if (ICContext) {
9602 DiagID = diag::warn_impcast_integer_sign_conditional;
9603 *ICContext = true;
9604 }
9605
John McCallacf0ee52010-10-08 02:01:28 +00009606 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00009607 }
9608
Douglas Gregora78f1932011-02-22 02:45:07 +00009609 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00009610 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9611 // type, to give us better diagnostics.
9612 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009613 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00009614 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9615 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9616 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9617 SourceType = S.Context.getTypeDeclType(Enum);
9618 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9619 }
9620 }
9621
Douglas Gregora78f1932011-02-22 02:45:07 +00009622 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9623 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00009624 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9625 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009626 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009627 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009628 return;
9629
Douglas Gregor364f7db2011-03-12 00:14:31 +00009630 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00009631 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009632 }
John McCall263a48b2010-01-04 23:31:57 +00009633}
9634
David Blaikie18e9ac72012-05-15 21:57:38 +00009635void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9636 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009637
9638void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00009639 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009640 E = E->IgnoreParenImpCasts();
9641
9642 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00009643 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009644
John McCallacf0ee52010-10-08 02:01:28 +00009645 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009646 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009647 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00009648}
9649
David Blaikie18e9ac72012-05-15 21:57:38 +00009650void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9651 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00009652 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009653
9654 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00009655 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9656 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009657
9658 // If -Wconversion would have warned about either of the candidates
9659 // for a signedness conversion to the context type...
9660 if (!Suspicious) return;
9661
9662 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009663 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00009664 return;
9665
John McCallcc7e5bf2010-05-06 08:58:33 +00009666 // ...then check whether it would have warned about either of the
9667 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00009668 if (E->getType() == T) return;
9669
9670 Suspicious = false;
9671 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9672 E->getType(), CC, &Suspicious);
9673 if (!Suspicious)
9674 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00009675 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009676}
9677
Richard Trieu65724892014-11-15 06:37:39 +00009678/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9679/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009680void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00009681 if (S.getLangOpts().Bool)
9682 return;
9683 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9684}
9685
John McCallcc7e5bf2010-05-06 08:58:33 +00009686/// AnalyzeImplicitConversions - Find and report any interesting
9687/// implicit conversions in the given expression. There are a couple
9688/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009689void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00009690 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00009691 Expr *E = OrigE->IgnoreParenImpCasts();
9692
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00009693 if (E->isTypeDependent() || E->isValueDependent())
9694 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00009695
John McCallcc7e5bf2010-05-06 08:58:33 +00009696 // For conditional operators, we analyze the arguments as if they
9697 // were being fed directly into the output.
9698 if (isa<ConditionalOperator>(E)) {
9699 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00009700 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009701 return;
9702 }
9703
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009704 // Check implicit argument conversions for function calls.
9705 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9706 CheckImplicitArgumentConversions(S, Call, CC);
9707
John McCallcc7e5bf2010-05-06 08:58:33 +00009708 // Go ahead and check any implicit conversions we might have skipped.
9709 // The non-canonical typecheck is just an optimization;
9710 // CheckImplicitConversion will filter out dead implicit conversions.
9711 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009712 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009713
9714 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00009715
9716 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9717 // The bound subexpressions in a PseudoObjectExpr are not reachable
9718 // as transitive children.
9719 // FIXME: Use a more uniform representation for this.
9720 for (auto *SE : POE->semantics())
9721 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9722 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00009723 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00009724
John McCallcc7e5bf2010-05-06 08:58:33 +00009725 // Skip past explicit casts.
9726 if (isa<ExplicitCastExpr>(E)) {
9727 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00009728 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009729 }
9730
John McCalld2a53122010-11-09 23:24:47 +00009731 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9732 // Do a somewhat different check with comparison operators.
9733 if (BO->isComparisonOp())
9734 return AnalyzeComparison(S, BO);
9735
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009736 // And with simple assignments.
9737 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00009738 return AnalyzeAssignment(S, BO);
9739 }
John McCallcc7e5bf2010-05-06 08:58:33 +00009740
9741 // These break the otherwise-useful invariant below. Fortunately,
9742 // we don't really need to recurse into them, because any internal
9743 // expressions should have been analyzed already when they were
9744 // built into statements.
9745 if (isa<StmtExpr>(E)) return;
9746
9747 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00009748 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00009749
9750 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00009751 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00009752 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00009753 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00009754 for (Stmt *SubStmt : E->children()) {
9755 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00009756 if (!ChildExpr)
9757 continue;
9758
Richard Trieu955231d2014-01-25 01:10:35 +00009759 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00009760 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00009761 // Ignore checking string literals that are in logical and operators.
9762 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00009763 continue;
9764 AnalyzeImplicitConversions(S, ChildExpr, CC);
9765 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009766
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009767 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00009768 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9769 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009770 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00009771
9772 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9773 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009774 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009775 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009776
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009777 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9778 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00009779 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009780}
9781
9782} // end anonymous namespace
9783
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009784/// Diagnose integer type and any valid implicit convertion to it.
9785static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9786 // Taking into account implicit conversions,
9787 // allow any integer.
9788 if (!E->getType()->isIntegerType()) {
9789 S.Diag(E->getLocStart(),
9790 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9791 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009792 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009793 // Potentially emit standard warnings for implicit conversions if enabled
9794 // using -Wconversion.
9795 CheckImplicitConversion(S, E, IntT, E->getLocStart());
9796 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009797}
9798
Richard Trieuc1888e02014-06-28 23:25:37 +00009799// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9800// Returns true when emitting a warning about taking the address of a reference.
9801static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00009802 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00009803 E = E->IgnoreParenImpCasts();
9804
9805 const FunctionDecl *FD = nullptr;
9806
9807 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9808 if (!DRE->getDecl()->getType()->isReferenceType())
9809 return false;
9810 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9811 if (!M->getMemberDecl()->getType()->isReferenceType())
9812 return false;
9813 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00009814 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00009815 return false;
9816 FD = Call->getDirectCallee();
9817 } else {
9818 return false;
9819 }
9820
9821 SemaRef.Diag(E->getExprLoc(), PD);
9822
9823 // If possible, point to location of function.
9824 if (FD) {
9825 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9826 }
9827
9828 return true;
9829}
9830
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009831// Returns true if the SourceLocation is expanded from any macro body.
9832// Returns false if the SourceLocation is invalid, is from not in a macro
9833// expansion, or is from expanded from a top-level macro argument.
9834static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9835 if (Loc.isInvalid())
9836 return false;
9837
9838 while (Loc.isMacroID()) {
9839 if (SM.isMacroBodyExpansion(Loc))
9840 return true;
9841 Loc = SM.getImmediateMacroCallerLoc(Loc);
9842 }
9843
9844 return false;
9845}
9846
Richard Trieu3bb8b562014-02-26 02:36:06 +00009847/// \brief Diagnose pointers that are always non-null.
9848/// \param E the expression containing the pointer
9849/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9850/// compared to a null pointer
9851/// \param IsEqual True when the comparison is equal to a null pointer
9852/// \param Range Extra SourceRange to highlight in the diagnostic
9853void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9854 Expr::NullPointerConstantKind NullKind,
9855 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00009856 if (!E)
9857 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009858
9859 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009860 if (E->getExprLoc().isMacroID()) {
9861 const SourceManager &SM = getSourceManager();
9862 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9863 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00009864 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009865 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009866 E = E->IgnoreImpCasts();
9867
9868 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9869
Richard Trieuf7432752014-06-06 21:39:26 +00009870 if (isa<CXXThisExpr>(E)) {
9871 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9872 : diag::warn_this_bool_conversion;
9873 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9874 return;
9875 }
9876
Richard Trieu3bb8b562014-02-26 02:36:06 +00009877 bool IsAddressOf = false;
9878
9879 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9880 if (UO->getOpcode() != UO_AddrOf)
9881 return;
9882 IsAddressOf = true;
9883 E = UO->getSubExpr();
9884 }
9885
Richard Trieuc1888e02014-06-28 23:25:37 +00009886 if (IsAddressOf) {
9887 unsigned DiagID = IsCompare
9888 ? diag::warn_address_of_reference_null_compare
9889 : diag::warn_address_of_reference_bool_conversion;
9890 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9891 << IsEqual;
9892 if (CheckForReference(*this, E, PD)) {
9893 return;
9894 }
9895 }
9896
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009897 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9898 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00009899 std::string Str;
9900 llvm::raw_string_ostream S(Str);
9901 E->printPretty(S, nullptr, getPrintingPolicy());
9902 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9903 : diag::warn_cast_nonnull_to_bool;
9904 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9905 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009906 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00009907 };
9908
9909 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9910 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9911 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009912 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9913 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009914 return;
9915 }
9916 }
9917 }
9918
Richard Trieu3bb8b562014-02-26 02:36:06 +00009919 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00009920 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009921 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9922 D = R->getDecl();
9923 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9924 D = M->getMemberDecl();
9925 }
9926
9927 // Weak Decls can be null.
9928 if (!D || D->isWeak())
9929 return;
George Burgess IV850269a2015-12-08 22:02:00 +00009930
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009931 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00009932 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9933 if (getCurFunction() &&
9934 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009935 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9936 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009937 return;
9938 }
9939
9940 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +00009941 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +00009942 assert(ParamIter != FD->param_end());
9943 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9944
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009945 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9946 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009947 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +00009948 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009949 }
George Burgess IV850269a2015-12-08 22:02:00 +00009950
9951 for (unsigned ArgNo : NonNull->args()) {
9952 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009953 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009954 return;
9955 }
George Burgess IV850269a2015-12-08 22:02:00 +00009956 }
9957 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009958 }
9959 }
George Burgess IV850269a2015-12-08 22:02:00 +00009960 }
9961
Richard Trieu3bb8b562014-02-26 02:36:06 +00009962 QualType T = D->getType();
9963 const bool IsArray = T->isArrayType();
9964 const bool IsFunction = T->isFunctionType();
9965
Richard Trieuc1888e02014-06-28 23:25:37 +00009966 // Address of function is used to silence the function warning.
9967 if (IsAddressOf && IsFunction) {
9968 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009969 }
9970
9971 // Found nothing.
9972 if (!IsAddressOf && !IsFunction && !IsArray)
9973 return;
9974
9975 // Pretty print the expression for the diagnostic.
9976 std::string Str;
9977 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00009978 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00009979
9980 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9981 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00009982 enum {
9983 AddressOf,
9984 FunctionPointer,
9985 ArrayPointer
9986 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009987 if (IsAddressOf)
9988 DiagType = AddressOf;
9989 else if (IsFunction)
9990 DiagType = FunctionPointer;
9991 else if (IsArray)
9992 DiagType = ArrayPointer;
9993 else
9994 llvm_unreachable("Could not determine diagnostic.");
9995 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9996 << Range << IsEqual;
9997
9998 if (!IsFunction)
9999 return;
10000
10001 // Suggest '&' to silence the function warning.
10002 Diag(E->getExprLoc(), diag::note_function_warning_silence)
10003 << FixItHint::CreateInsertion(E->getLocStart(), "&");
10004
10005 // Check to see if '()' fixit should be emitted.
10006 QualType ReturnType;
10007 UnresolvedSet<4> NonTemplateOverloads;
10008 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10009 if (ReturnType.isNull())
10010 return;
10011
10012 if (IsCompare) {
10013 // There are two cases here. If there is null constant, the only suggest
10014 // for a pointer return type. If the null is 0, then suggest if the return
10015 // type is a pointer or an integer type.
10016 if (!ReturnType->isPointerType()) {
10017 if (NullKind == Expr::NPCK_ZeroExpression ||
10018 NullKind == Expr::NPCK_ZeroLiteral) {
10019 if (!ReturnType->isIntegerType())
10020 return;
10021 } else {
10022 return;
10023 }
10024 }
10025 } else { // !IsCompare
10026 // For function to bool, only suggest if the function pointer has bool
10027 // return type.
10028 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10029 return;
10030 }
10031 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +000010032 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +000010033}
10034
John McCallcc7e5bf2010-05-06 08:58:33 +000010035/// Diagnoses "dangerous" implicit conversions within the given
10036/// expression (which is a full expression). Implements -Wconversion
10037/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +000010038///
10039/// \param CC the "context" location of the implicit conversion, i.e.
10040/// the most location of the syntactic entity requiring the implicit
10041/// conversion
10042void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010043 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +000010044 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +000010045 return;
10046
10047 // Don't diagnose for value- or type-dependent expressions.
10048 if (E->isTypeDependent() || E->isValueDependent())
10049 return;
10050
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010051 // Check for array bounds violations in cases where the check isn't triggered
10052 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10053 // ArraySubscriptExpr is on the RHS of a variable initialization.
10054 CheckArrayAccess(E);
10055
John McCallacf0ee52010-10-08 02:01:28 +000010056 // This is not the right CC for (e.g.) a variable initialization.
10057 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010058}
10059
Richard Trieu65724892014-11-15 06:37:39 +000010060/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10061/// Input argument E is a logical expression.
10062void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10063 ::CheckBoolLikeConversion(*this, E, CC);
10064}
10065
Richard Smith9f7df0c2017-06-26 23:19:32 +000010066/// Diagnose when expression is an integer constant expression and its evaluation
10067/// results in integer overflow
10068void Sema::CheckForIntOverflow (Expr *E) {
10069 // Use a work list to deal with nested struct initializers.
10070 SmallVector<Expr *, 2> Exprs(1, E);
10071
10072 do {
10073 Expr *E = Exprs.pop_back_val();
10074
10075 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
10076 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10077 continue;
10078 }
10079
10080 if (auto InitList = dyn_cast<InitListExpr>(E))
10081 Exprs.append(InitList->inits().begin(), InitList->inits().end());
10082
10083 if (isa<ObjCBoxedExpr>(E))
10084 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10085 } while (!Exprs.empty());
10086}
10087
Richard Smithc406cb72013-01-17 01:17:56 +000010088namespace {
10089/// \brief Visitor for expressions which looks for unsequenced operations on the
10090/// same object.
10091class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010092 typedef EvaluatedExprVisitor<SequenceChecker> Base;
10093
Richard Smithc406cb72013-01-17 01:17:56 +000010094 /// \brief A tree of sequenced regions within an expression. Two regions are
10095 /// unsequenced if one is an ancestor or a descendent of the other. When we
10096 /// finish processing an expression with sequencing, such as a comma
10097 /// expression, we fold its tree nodes into its parent, since they are
10098 /// unsequenced with respect to nodes we will visit later.
10099 class SequenceTree {
10100 struct Value {
10101 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10102 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +000010103 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +000010104 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010105 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +000010106
10107 public:
10108 /// \brief A region within an expression which may be sequenced with respect
10109 /// to some other region.
10110 class Seq {
10111 explicit Seq(unsigned N) : Index(N) {}
10112 unsigned Index;
10113 friend class SequenceTree;
10114 public:
10115 Seq() : Index(0) {}
10116 };
10117
10118 SequenceTree() { Values.push_back(Value(0)); }
10119 Seq root() const { return Seq(0); }
10120
10121 /// \brief Create a new sequence of operations, which is an unsequenced
10122 /// subset of \p Parent. This sequence of operations is sequenced with
10123 /// respect to other children of \p Parent.
10124 Seq allocate(Seq Parent) {
10125 Values.push_back(Value(Parent.Index));
10126 return Seq(Values.size() - 1);
10127 }
10128
10129 /// \brief Merge a sequence of operations into its parent.
10130 void merge(Seq S) {
10131 Values[S.Index].Merged = true;
10132 }
10133
10134 /// \brief Determine whether two operations are unsequenced. This operation
10135 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10136 /// should have been merged into its parent as appropriate.
10137 bool isUnsequenced(Seq Cur, Seq Old) {
10138 unsigned C = representative(Cur.Index);
10139 unsigned Target = representative(Old.Index);
10140 while (C >= Target) {
10141 if (C == Target)
10142 return true;
10143 C = Values[C].Parent;
10144 }
10145 return false;
10146 }
10147
10148 private:
10149 /// \brief Pick a representative for a sequence.
10150 unsigned representative(unsigned K) {
10151 if (Values[K].Merged)
10152 // Perform path compression as we go.
10153 return Values[K].Parent = representative(Values[K].Parent);
10154 return K;
10155 }
10156 };
10157
10158 /// An object for which we can track unsequenced uses.
10159 typedef NamedDecl *Object;
10160
10161 /// Different flavors of object usage which we track. We only track the
10162 /// least-sequenced usage of each kind.
10163 enum UsageKind {
10164 /// A read of an object. Multiple unsequenced reads are OK.
10165 UK_Use,
10166 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000010167 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000010168 UK_ModAsValue,
10169 /// A modification of an object which is not sequenced before the value
10170 /// computation of the expression, such as n++.
10171 UK_ModAsSideEffect,
10172
10173 UK_Count = UK_ModAsSideEffect + 1
10174 };
10175
10176 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +000010177 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +000010178 Expr *Use;
10179 SequenceTree::Seq Seq;
10180 };
10181
10182 struct UsageInfo {
10183 UsageInfo() : Diagnosed(false) {}
10184 Usage Uses[UK_Count];
10185 /// Have we issued a diagnostic for this variable already?
10186 bool Diagnosed;
10187 };
10188 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
10189
10190 Sema &SemaRef;
10191 /// Sequenced regions within the expression.
10192 SequenceTree Tree;
10193 /// Declaration modifications and references which we have seen.
10194 UsageInfoMap UsageMap;
10195 /// The region we are currently within.
10196 SequenceTree::Seq Region;
10197 /// Filled in with declarations which were modified as a side-effect
10198 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010199 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +000010200 /// Expressions to check later. We defer checking these to reduce
10201 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010202 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000010203
10204 /// RAII object wrapping the visitation of a sequenced subexpression of an
10205 /// expression. At the end of this process, the side-effects of the evaluation
10206 /// become sequenced with respect to the value computation of the result, so
10207 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10208 /// UK_ModAsValue.
10209 struct SequencedSubexpression {
10210 SequencedSubexpression(SequenceChecker &Self)
10211 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10212 Self.ModAsSideEffect = &ModAsSideEffect;
10213 }
10214 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000010215 for (auto &M : llvm::reverse(ModAsSideEffect)) {
10216 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000010217 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000010218 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10219 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000010220 }
10221 Self.ModAsSideEffect = OldModAsSideEffect;
10222 }
10223
10224 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010225 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
10226 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000010227 };
10228
Richard Smith40238f02013-06-20 22:21:56 +000010229 /// RAII object wrapping the visitation of a subexpression which we might
10230 /// choose to evaluate as a constant. If any subexpression is evaluated and
10231 /// found to be non-constant, this allows us to suppress the evaluation of
10232 /// the outer expression.
10233 class EvaluationTracker {
10234 public:
10235 EvaluationTracker(SequenceChecker &Self)
10236 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
10237 Self.EvalTracker = this;
10238 }
10239 ~EvaluationTracker() {
10240 Self.EvalTracker = Prev;
10241 if (Prev)
10242 Prev->EvalOK &= EvalOK;
10243 }
10244
10245 bool evaluate(const Expr *E, bool &Result) {
10246 if (!EvalOK || E->isValueDependent())
10247 return false;
10248 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10249 return EvalOK;
10250 }
10251
10252 private:
10253 SequenceChecker &Self;
10254 EvaluationTracker *Prev;
10255 bool EvalOK;
10256 } *EvalTracker;
10257
Richard Smithc406cb72013-01-17 01:17:56 +000010258 /// \brief Find the object which is produced by the specified expression,
10259 /// if any.
10260 Object getObject(Expr *E, bool Mod) const {
10261 E = E->IgnoreParenCasts();
10262 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10263 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10264 return getObject(UO->getSubExpr(), Mod);
10265 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10266 if (BO->getOpcode() == BO_Comma)
10267 return getObject(BO->getRHS(), Mod);
10268 if (Mod && BO->isAssignmentOp())
10269 return getObject(BO->getLHS(), Mod);
10270 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10271 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10272 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10273 return ME->getMemberDecl();
10274 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10275 // FIXME: If this is a reference, map through to its value.
10276 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000010277 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010278 }
10279
10280 /// \brief Note that an object was modified or used by an expression.
10281 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10282 Usage &U = UI.Uses[UK];
10283 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10284 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10285 ModAsSideEffect->push_back(std::make_pair(O, U));
10286 U.Use = Ref;
10287 U.Seq = Region;
10288 }
10289 }
10290 /// \brief Check whether a modification or use conflicts with a prior usage.
10291 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10292 bool IsModMod) {
10293 if (UI.Diagnosed)
10294 return;
10295
10296 const Usage &U = UI.Uses[OtherKind];
10297 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10298 return;
10299
10300 Expr *Mod = U.Use;
10301 Expr *ModOrUse = Ref;
10302 if (OtherKind == UK_Use)
10303 std::swap(Mod, ModOrUse);
10304
10305 SemaRef.Diag(Mod->getExprLoc(),
10306 IsModMod ? diag::warn_unsequenced_mod_mod
10307 : diag::warn_unsequenced_mod_use)
10308 << O << SourceRange(ModOrUse->getExprLoc());
10309 UI.Diagnosed = true;
10310 }
10311
10312 void notePreUse(Object O, Expr *Use) {
10313 UsageInfo &U = UsageMap[O];
10314 // Uses conflict with other modifications.
10315 checkUsage(O, U, Use, UK_ModAsValue, false);
10316 }
10317 void notePostUse(Object O, Expr *Use) {
10318 UsageInfo &U = UsageMap[O];
10319 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10320 addUsage(U, O, Use, UK_Use);
10321 }
10322
10323 void notePreMod(Object O, Expr *Mod) {
10324 UsageInfo &U = UsageMap[O];
10325 // Modifications conflict with other modifications and with uses.
10326 checkUsage(O, U, Mod, UK_ModAsValue, true);
10327 checkUsage(O, U, Mod, UK_Use, false);
10328 }
10329 void notePostMod(Object O, Expr *Use, UsageKind UK) {
10330 UsageInfo &U = UsageMap[O];
10331 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10332 addUsage(U, O, Use, UK);
10333 }
10334
10335public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010336 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +000010337 : Base(S.Context), SemaRef(S), Region(Tree.root()),
10338 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010339 Visit(E);
10340 }
10341
10342 void VisitStmt(Stmt *S) {
10343 // Skip all statements which aren't expressions for now.
10344 }
10345
10346 void VisitExpr(Expr *E) {
10347 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000010348 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000010349 }
10350
10351 void VisitCastExpr(CastExpr *E) {
10352 Object O = Object();
10353 if (E->getCastKind() == CK_LValueToRValue)
10354 O = getObject(E->getSubExpr(), false);
10355
10356 if (O)
10357 notePreUse(O, E);
10358 VisitExpr(E);
10359 if (O)
10360 notePostUse(O, E);
10361 }
10362
10363 void VisitBinComma(BinaryOperator *BO) {
10364 // C++11 [expr.comma]p1:
10365 // Every value computation and side effect associated with the left
10366 // expression is sequenced before every value computation and side
10367 // effect associated with the right expression.
10368 SequenceTree::Seq LHS = Tree.allocate(Region);
10369 SequenceTree::Seq RHS = Tree.allocate(Region);
10370 SequenceTree::Seq OldRegion = Region;
10371
10372 {
10373 SequencedSubexpression SeqLHS(*this);
10374 Region = LHS;
10375 Visit(BO->getLHS());
10376 }
10377
10378 Region = RHS;
10379 Visit(BO->getRHS());
10380
10381 Region = OldRegion;
10382
10383 // Forget that LHS and RHS are sequenced. They are both unsequenced
10384 // with respect to other stuff.
10385 Tree.merge(LHS);
10386 Tree.merge(RHS);
10387 }
10388
10389 void VisitBinAssign(BinaryOperator *BO) {
10390 // The modification is sequenced after the value computation of the LHS
10391 // and RHS, so check it before inspecting the operands and update the
10392 // map afterwards.
10393 Object O = getObject(BO->getLHS(), true);
10394 if (!O)
10395 return VisitExpr(BO);
10396
10397 notePreMod(O, BO);
10398
10399 // C++11 [expr.ass]p7:
10400 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10401 // only once.
10402 //
10403 // Therefore, for a compound assignment operator, O is considered used
10404 // everywhere except within the evaluation of E1 itself.
10405 if (isa<CompoundAssignOperator>(BO))
10406 notePreUse(O, BO);
10407
10408 Visit(BO->getLHS());
10409
10410 if (isa<CompoundAssignOperator>(BO))
10411 notePostUse(O, BO);
10412
10413 Visit(BO->getRHS());
10414
Richard Smith83e37bee2013-06-26 23:16:51 +000010415 // C++11 [expr.ass]p1:
10416 // the assignment is sequenced [...] before the value computation of the
10417 // assignment expression.
10418 // C11 6.5.16/3 has no such rule.
10419 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10420 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010421 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010422
Richard Smithc406cb72013-01-17 01:17:56 +000010423 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10424 VisitBinAssign(CAO);
10425 }
10426
10427 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10428 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10429 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10430 Object O = getObject(UO->getSubExpr(), true);
10431 if (!O)
10432 return VisitExpr(UO);
10433
10434 notePreMod(O, UO);
10435 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000010436 // C++11 [expr.pre.incr]p1:
10437 // the expression ++x is equivalent to x+=1
10438 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10439 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010440 }
10441
10442 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10443 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10444 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10445 Object O = getObject(UO->getSubExpr(), true);
10446 if (!O)
10447 return VisitExpr(UO);
10448
10449 notePreMod(O, UO);
10450 Visit(UO->getSubExpr());
10451 notePostMod(O, UO, UK_ModAsSideEffect);
10452 }
10453
10454 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10455 void VisitBinLOr(BinaryOperator *BO) {
10456 // The side-effects of the LHS of an '&&' are sequenced before the
10457 // value computation of the RHS, and hence before the value computation
10458 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10459 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000010460 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010461 {
10462 SequencedSubexpression Sequenced(*this);
10463 Visit(BO->getLHS());
10464 }
10465
10466 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010467 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010468 if (!Result)
10469 Visit(BO->getRHS());
10470 } else {
10471 // Check for unsequenced operations in the RHS, treating it as an
10472 // entirely separate evaluation.
10473 //
10474 // FIXME: If there are operations in the RHS which are unsequenced
10475 // with respect to operations outside the RHS, and those operations
10476 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000010477 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010478 }
Richard Smithc406cb72013-01-17 01:17:56 +000010479 }
10480 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000010481 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010482 {
10483 SequencedSubexpression Sequenced(*this);
10484 Visit(BO->getLHS());
10485 }
10486
10487 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010488 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010489 if (Result)
10490 Visit(BO->getRHS());
10491 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000010492 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010493 }
Richard Smithc406cb72013-01-17 01:17:56 +000010494 }
10495
10496 // Only visit the condition, unless we can be sure which subexpression will
10497 // be chosen.
10498 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000010499 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000010500 {
10501 SequencedSubexpression Sequenced(*this);
10502 Visit(CO->getCond());
10503 }
Richard Smithc406cb72013-01-17 01:17:56 +000010504
10505 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010506 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000010507 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010508 else {
Richard Smithd33f5202013-01-17 23:18:09 +000010509 WorkList.push_back(CO->getTrueExpr());
10510 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010511 }
Richard Smithc406cb72013-01-17 01:17:56 +000010512 }
10513
Richard Smithe3dbfe02013-06-30 10:40:20 +000010514 void VisitCallExpr(CallExpr *CE) {
10515 // C++11 [intro.execution]p15:
10516 // When calling a function [...], every value computation and side effect
10517 // associated with any argument expression, or with the postfix expression
10518 // designating the called function, is sequenced before execution of every
10519 // expression or statement in the body of the function [and thus before
10520 // the value computation of its result].
10521 SequencedSubexpression Sequenced(*this);
10522 Base::VisitCallExpr(CE);
10523
10524 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10525 }
10526
Richard Smithc406cb72013-01-17 01:17:56 +000010527 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010528 // This is a call, so all subexpressions are sequenced before the result.
10529 SequencedSubexpression Sequenced(*this);
10530
Richard Smithc406cb72013-01-17 01:17:56 +000010531 if (!CCE->isListInitialization())
10532 return VisitExpr(CCE);
10533
10534 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010535 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010536 SequenceTree::Seq Parent = Region;
10537 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10538 E = CCE->arg_end();
10539 I != E; ++I) {
10540 Region = Tree.allocate(Parent);
10541 Elts.push_back(Region);
10542 Visit(*I);
10543 }
10544
10545 // Forget that the initializers are sequenced.
10546 Region = Parent;
10547 for (unsigned I = 0; I < Elts.size(); ++I)
10548 Tree.merge(Elts[I]);
10549 }
10550
10551 void VisitInitListExpr(InitListExpr *ILE) {
10552 if (!SemaRef.getLangOpts().CPlusPlus11)
10553 return VisitExpr(ILE);
10554
10555 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010556 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010557 SequenceTree::Seq Parent = Region;
10558 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10559 Expr *E = ILE->getInit(I);
10560 if (!E) continue;
10561 Region = Tree.allocate(Parent);
10562 Elts.push_back(Region);
10563 Visit(E);
10564 }
10565
10566 // Forget that the initializers are sequenced.
10567 Region = Parent;
10568 for (unsigned I = 0; I < Elts.size(); ++I)
10569 Tree.merge(Elts[I]);
10570 }
10571};
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010572} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +000010573
10574void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010575 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000010576 WorkList.push_back(E);
10577 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000010578 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000010579 SequenceChecker(*this, Item, WorkList);
10580 }
Richard Smithc406cb72013-01-17 01:17:56 +000010581}
10582
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010583void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10584 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010585 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000010586 if (!E->isInstantiationDependent())
10587 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010588 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000010589 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010590 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000010591}
10592
John McCall1f425642010-11-11 03:21:53 +000010593void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10594 FieldDecl *BitField,
10595 Expr *Init) {
10596 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10597}
10598
David Majnemer61a5bbf2015-04-07 22:08:51 +000010599static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10600 SourceLocation Loc) {
10601 if (!PType->isVariablyModifiedType())
10602 return;
10603 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10604 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10605 return;
10606 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000010607 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10608 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10609 return;
10610 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000010611 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10612 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10613 return;
10614 }
10615
10616 const ArrayType *AT = S.Context.getAsArrayType(PType);
10617 if (!AT)
10618 return;
10619
10620 if (AT->getSizeModifier() != ArrayType::Star) {
10621 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10622 return;
10623 }
10624
10625 S.Diag(Loc, diag::err_array_star_in_function_definition);
10626}
10627
Mike Stump0c2ec772010-01-21 03:59:47 +000010628/// CheckParmsForFunctionDef - Check that the parameters of the given
10629/// function are appropriate for the definition of a function. This
10630/// takes care of any checks that cannot be performed on the
10631/// declaration itself, e.g., that the types of each of the function
10632/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000010633bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000010634 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010635 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000010636 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010637 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10638 // function declarator that is part of a function definition of
10639 // that function shall not have incomplete type.
10640 //
10641 // This is also C++ [dcl.fct]p6.
10642 if (!Param->isInvalidDecl() &&
10643 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010644 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010645 Param->setInvalidDecl();
10646 HasInvalidParm = true;
10647 }
10648
10649 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10650 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000010651 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000010652 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000010653 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000010654 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000010655 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000010656
10657 // C99 6.7.5.3p12:
10658 // If the function declarator is not part of a definition of that
10659 // function, parameters may have incomplete type and may use the [*]
10660 // notation in their sequences of declarator specifiers to specify
10661 // variable length array types.
10662 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000010663 // FIXME: This diagnostic should point the '[*]' if source-location
10664 // information is added for it.
10665 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010666
10667 // MSVC destroys objects passed by value in the callee. Therefore a
10668 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010669 // object's destructor. However, we don't perform any direct access check
10670 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +000010671 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10672 .getCXXABI()
10673 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +000010674 if (!Param->isInvalidDecl()) {
10675 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10676 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10677 if (!ClassDecl->isInvalidDecl() &&
10678 !ClassDecl->hasIrrelevantDestructor() &&
10679 !ClassDecl->isDependentContext()) {
10680 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10681 MarkFunctionReferenced(Param->getLocation(), Destructor);
10682 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10683 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010684 }
10685 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010686 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010687
10688 // Parameters with the pass_object_size attribute only need to be marked
10689 // constant at function definitions. Because we lack information about
10690 // whether we're on a declaration or definition when we're instantiating the
10691 // attribute, we need to check for constness here.
10692 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10693 if (!Param->getType().isConstQualified())
10694 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10695 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000010696 }
10697
10698 return HasInvalidParm;
10699}
John McCall2b5c1b22010-08-12 21:44:57 +000010700
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010701/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10702/// or MemberExpr.
10703static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10704 ASTContext &Context) {
10705 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10706 return Context.getDeclAlign(DRE->getDecl());
10707
10708 if (const auto *ME = dyn_cast<MemberExpr>(E))
10709 return Context.getDeclAlign(ME->getMemberDecl());
10710
10711 return TypeAlign;
10712}
10713
John McCall2b5c1b22010-08-12 21:44:57 +000010714/// CheckCastAlign - Implements -Wcast-align, which warns when a
10715/// pointer cast increases the alignment requirements.
10716void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10717 // This is actually a lot of work to potentially be doing on every
10718 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010719 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000010720 return;
10721
10722 // Ignore dependent types.
10723 if (T->isDependentType() || Op->getType()->isDependentType())
10724 return;
10725
10726 // Require that the destination be a pointer type.
10727 const PointerType *DestPtr = T->getAs<PointerType>();
10728 if (!DestPtr) return;
10729
10730 // If the destination has alignment 1, we're done.
10731 QualType DestPointee = DestPtr->getPointeeType();
10732 if (DestPointee->isIncompleteType()) return;
10733 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10734 if (DestAlign.isOne()) return;
10735
10736 // Require that the source be a pointer type.
10737 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10738 if (!SrcPtr) return;
10739 QualType SrcPointee = SrcPtr->getPointeeType();
10740
10741 // Whitelist casts from cv void*. We already implicitly
10742 // whitelisted casts to cv void*, since they have alignment 1.
10743 // Also whitelist casts involving incomplete types, which implicitly
10744 // includes 'void'.
10745 if (SrcPointee->isIncompleteType()) return;
10746
10747 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010748
10749 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10750 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10751 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10752 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10753 if (UO->getOpcode() == UO_AddrOf)
10754 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10755 }
10756
John McCall2b5c1b22010-08-12 21:44:57 +000010757 if (SrcAlign >= DestAlign) return;
10758
10759 Diag(TRange.getBegin(), diag::warn_cast_align)
10760 << Op->getType() << T
10761 << static_cast<unsigned>(SrcAlign.getQuantity())
10762 << static_cast<unsigned>(DestAlign.getQuantity())
10763 << TRange << Op->getSourceRange();
10764}
10765
Chandler Carruth28389f02011-08-05 09:10:50 +000010766/// \brief Check whether this array fits the idiom of a size-one tail padded
10767/// array member of a struct.
10768///
10769/// We avoid emitting out-of-bounds access warnings for such arrays as they are
10770/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000010771static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000010772 const NamedDecl *ND) {
10773 if (Size != 1 || !ND) return false;
10774
10775 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10776 if (!FD) return false;
10777
10778 // Don't consider sizes resulting from macro expansions or template argument
10779 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000010780
10781 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010782 while (TInfo) {
10783 TypeLoc TL = TInfo->getTypeLoc();
10784 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000010785 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10786 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010787 TInfo = TDL->getTypeSourceInfo();
10788 continue;
10789 }
David Blaikie6adc78e2013-02-18 22:06:02 +000010790 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10791 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000010792 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10793 return false;
10794 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010795 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000010796 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010797
10798 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000010799 if (!RD) return false;
10800 if (RD->isUnion()) return false;
10801 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10802 if (!CRD->isStandardLayout()) return false;
10803 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010804
Benjamin Kramer8c543672011-08-06 03:04:42 +000010805 // See if this is the last field decl in the record.
10806 const Decl *D = FD;
10807 while ((D = D->getNextDeclInContext()))
10808 if (isa<FieldDecl>(D))
10809 return false;
10810 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000010811}
10812
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010813void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010814 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000010815 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010816 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010817 if (IndexExpr->isValueDependent())
10818 return;
10819
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010820 const Type *EffectiveType =
10821 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010822 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010823 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010824 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010825 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000010826 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000010827
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010828 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000010829 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000010830 return;
Richard Smith13f67182011-12-16 19:31:14 +000010831 if (IndexNegated)
10832 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000010833
Craig Topperc3ec1492014-05-26 06:22:03 +000010834 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000010835 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10836 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +000010837 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +000010838 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +000010839
Ted Kremeneke4b316c2011-02-23 23:06:04 +000010840 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010841 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000010842 if (!size.isStrictlyPositive())
10843 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010844
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010845 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000010846 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010847 // Make sure we're comparing apples to apples when comparing index to size
10848 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10849 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000010850 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000010851 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010852 if (ptrarith_typesize != array_typesize) {
10853 // There's a cast to a different size type involved
10854 uint64_t ratio = array_typesize / ptrarith_typesize;
10855 // TODO: Be smarter about handling cases where array_typesize is not a
10856 // multiple of ptrarith_typesize
10857 if (ptrarith_typesize * ratio == array_typesize)
10858 size *= llvm::APInt(size.getBitWidth(), ratio);
10859 }
10860 }
10861
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010862 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010863 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010864 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010865 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010866
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010867 // For array subscripting the index must be less than size, but for pointer
10868 // arithmetic also allow the index (offset) to be equal to size since
10869 // computing the next address after the end of the array is legal and
10870 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010871 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000010872 return;
10873
10874 // Also don't warn for arrays of size 1 which are members of some
10875 // structure. These are often used to approximate flexible arrays in C89
10876 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010877 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000010878 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010879
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010880 // Suppress the warning if the subscript expression (as identified by the
10881 // ']' location) and the index expression are both from macro expansions
10882 // within a system header.
10883 if (ASE) {
10884 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10885 ASE->getRBracketLoc());
10886 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10887 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10888 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000010889 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010890 return;
10891 }
10892 }
10893
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010894 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010895 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010896 DiagID = diag::warn_array_index_exceeds_bounds;
10897
10898 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10899 PDiag(DiagID) << index.toString(10, true)
10900 << size.toString(10, true)
10901 << (unsigned)size.getLimitedValue(~0U)
10902 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010903 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010904 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010905 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010906 DiagID = diag::warn_ptr_arith_precedes_bounds;
10907 if (index.isNegative()) index = -index;
10908 }
10909
10910 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10911 PDiag(DiagID) << index.toString(10, true)
10912 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000010913 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000010914
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000010915 if (!ND) {
10916 // Try harder to find a NamedDecl to point at in the note.
10917 while (const ArraySubscriptExpr *ASE =
10918 dyn_cast<ArraySubscriptExpr>(BaseExpr))
10919 BaseExpr = ASE->getBase()->IgnoreParenCasts();
10920 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10921 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10922 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10923 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10924 }
10925
Chandler Carruth1af88f12011-02-17 21:10:52 +000010926 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010927 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10928 PDiag(diag::note_array_index_out_of_bounds)
10929 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000010930}
10931
Ted Kremenekdf26df72011-03-01 18:41:00 +000010932void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010933 int AllowOnePastEnd = 0;
10934 while (expr) {
10935 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000010936 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010937 case Stmt::ArraySubscriptExprClass: {
10938 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010939 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010940 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +000010941 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010942 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010943 case Stmt::OMPArraySectionExprClass: {
10944 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10945 if (ASE->getLowerBound())
10946 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10947 /*ASE=*/nullptr, AllowOnePastEnd > 0);
10948 return;
10949 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010950 case Stmt::UnaryOperatorClass: {
10951 // Only unwrap the * and & unary operators
10952 const UnaryOperator *UO = cast<UnaryOperator>(expr);
10953 expr = UO->getSubExpr();
10954 switch (UO->getOpcode()) {
10955 case UO_AddrOf:
10956 AllowOnePastEnd++;
10957 break;
10958 case UO_Deref:
10959 AllowOnePastEnd--;
10960 break;
10961 default:
10962 return;
10963 }
10964 break;
10965 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010966 case Stmt::ConditionalOperatorClass: {
10967 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10968 if (const Expr *lhs = cond->getLHS())
10969 CheckArrayAccess(lhs);
10970 if (const Expr *rhs = cond->getRHS())
10971 CheckArrayAccess(rhs);
10972 return;
10973 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000010974 case Stmt::CXXOperatorCallExprClass: {
10975 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
10976 for (const auto *Arg : OCE->arguments())
10977 CheckArrayAccess(Arg);
10978 return;
10979 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010980 default:
10981 return;
10982 }
Peter Collingbourne91147592011-04-15 00:35:48 +000010983 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010984}
John McCall31168b02011-06-15 23:02:42 +000010985
10986//===--- CHECK: Objective-C retain cycles ----------------------------------//
10987
10988namespace {
10989 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +000010990 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +000010991 VarDecl *Variable;
10992 SourceRange Range;
10993 SourceLocation Loc;
10994 bool Indirect;
10995
10996 void setLocsFrom(Expr *e) {
10997 Loc = e->getExprLoc();
10998 Range = e->getSourceRange();
10999 }
11000 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011001} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000011002
11003/// Consider whether capturing the given variable can possibly lead to
11004/// a retain cycle.
11005static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000011006 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000011007 // lifetime. In MRR, it's captured strongly if the variable is
11008 // __block and has an appropriate type.
11009 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11010 return false;
11011
11012 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011013 if (ref)
11014 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000011015 return true;
11016}
11017
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011018static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000011019 while (true) {
11020 e = e->IgnoreParens();
11021 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11022 switch (cast->getCastKind()) {
11023 case CK_BitCast:
11024 case CK_LValueBitCast:
11025 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000011026 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000011027 e = cast->getSubExpr();
11028 continue;
11029
John McCall31168b02011-06-15 23:02:42 +000011030 default:
11031 return false;
11032 }
11033 }
11034
11035 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11036 ObjCIvarDecl *ivar = ref->getDecl();
11037 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11038 return false;
11039
11040 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011041 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000011042 return false;
11043
11044 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11045 owner.Indirect = true;
11046 return true;
11047 }
11048
11049 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11050 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11051 if (!var) return false;
11052 return considerVariable(var, ref, owner);
11053 }
11054
John McCall31168b02011-06-15 23:02:42 +000011055 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11056 if (member->isArrow()) return false;
11057
11058 // Don't count this as an indirect ownership.
11059 e = member->getBase();
11060 continue;
11061 }
11062
John McCallfe96e0b2011-11-06 09:01:30 +000011063 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11064 // Only pay attention to pseudo-objects on property references.
11065 ObjCPropertyRefExpr *pre
11066 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11067 ->IgnoreParens());
11068 if (!pre) return false;
11069 if (pre->isImplicitProperty()) return false;
11070 ObjCPropertyDecl *property = pre->getExplicitProperty();
11071 if (!property->isRetaining() &&
11072 !(property->getPropertyIvarDecl() &&
11073 property->getPropertyIvarDecl()->getType()
11074 .getObjCLifetime() == Qualifiers::OCL_Strong))
11075 return false;
11076
11077 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011078 if (pre->isSuperReceiver()) {
11079 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11080 if (!owner.Variable)
11081 return false;
11082 owner.Loc = pre->getLocation();
11083 owner.Range = pre->getSourceRange();
11084 return true;
11085 }
John McCallfe96e0b2011-11-06 09:01:30 +000011086 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11087 ->getSourceExpr());
11088 continue;
11089 }
11090
John McCall31168b02011-06-15 23:02:42 +000011091 // Array ivars?
11092
11093 return false;
11094 }
11095}
11096
11097namespace {
11098 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
11099 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11100 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011101 Context(Context), Variable(variable), Capturer(nullptr),
11102 VarWillBeReased(false) {}
11103 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000011104 VarDecl *Variable;
11105 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011106 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +000011107
11108 void VisitDeclRefExpr(DeclRefExpr *ref) {
11109 if (ref->getDecl() == Variable && !Capturer)
11110 Capturer = ref;
11111 }
11112
John McCall31168b02011-06-15 23:02:42 +000011113 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11114 if (Capturer) return;
11115 Visit(ref->getBase());
11116 if (Capturer && ref->isFreeIvar())
11117 Capturer = ref;
11118 }
11119
11120 void VisitBlockExpr(BlockExpr *block) {
11121 // Look inside nested blocks
11122 if (block->getBlockDecl()->capturesVariable(Variable))
11123 Visit(block->getBlockDecl()->getBody());
11124 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000011125
11126 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11127 if (Capturer) return;
11128 if (OVE->getSourceExpr())
11129 Visit(OVE->getSourceExpr());
11130 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011131 void VisitBinaryOperator(BinaryOperator *BinOp) {
11132 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11133 return;
11134 Expr *LHS = BinOp->getLHS();
11135 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11136 if (DRE->getDecl() != Variable)
11137 return;
11138 if (Expr *RHS = BinOp->getRHS()) {
11139 RHS = RHS->IgnoreParenCasts();
11140 llvm::APSInt Value;
11141 VarWillBeReased =
11142 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11143 }
11144 }
11145 }
John McCall31168b02011-06-15 23:02:42 +000011146 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011147} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000011148
11149/// Check whether the given argument is a block which captures a
11150/// variable.
11151static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11152 assert(owner.Variable && owner.Loc.isValid());
11153
11154 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000011155
11156 // Look through [^{...} copy] and Block_copy(^{...}).
11157 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11158 Selector Cmd = ME->getSelector();
11159 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11160 e = ME->getInstanceReceiver();
11161 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000011162 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000011163 e = e->IgnoreParenCasts();
11164 }
11165 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11166 if (CE->getNumArgs() == 1) {
11167 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000011168 if (Fn) {
11169 const IdentifierInfo *FnI = Fn->getIdentifier();
11170 if (FnI && FnI->isStr("_Block_copy")) {
11171 e = CE->getArg(0)->IgnoreParenCasts();
11172 }
11173 }
Jordan Rose67e887c2012-09-17 17:54:30 +000011174 }
11175 }
11176
John McCall31168b02011-06-15 23:02:42 +000011177 BlockExpr *block = dyn_cast<BlockExpr>(e);
11178 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000011179 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011180
11181 FindCaptureVisitor visitor(S.Context, owner.Variable);
11182 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011183 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000011184}
11185
11186static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11187 RetainCycleOwner &owner) {
11188 assert(capturer);
11189 assert(owner.Variable && owner.Loc.isValid());
11190
11191 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11192 << owner.Variable << capturer->getSourceRange();
11193 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11194 << owner.Indirect << owner.Range;
11195}
11196
11197/// Check for a keyword selector that starts with the word 'add' or
11198/// 'set'.
11199static bool isSetterLikeSelector(Selector sel) {
11200 if (sel.isUnarySelector()) return false;
11201
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011202 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000011203 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011204 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000011205 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011206 else if (str.startswith("add")) {
11207 // Specially whitelist 'addOperationWithBlock:'.
11208 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11209 return false;
11210 str = str.substr(3);
11211 }
John McCall31168b02011-06-15 23:02:42 +000011212 else
11213 return false;
11214
11215 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000011216 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000011217}
11218
Benjamin Kramer3a743452015-03-09 15:03:32 +000011219static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11220 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011221 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11222 Message->getReceiverInterface(),
11223 NSAPI::ClassId_NSMutableArray);
11224 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011225 return None;
11226 }
11227
11228 Selector Sel = Message->getSelector();
11229
11230 Optional<NSAPI::NSArrayMethodKind> MKOpt =
11231 S.NSAPIObj->getNSArrayMethodKind(Sel);
11232 if (!MKOpt) {
11233 return None;
11234 }
11235
11236 NSAPI::NSArrayMethodKind MK = *MKOpt;
11237
11238 switch (MK) {
11239 case NSAPI::NSMutableArr_addObject:
11240 case NSAPI::NSMutableArr_insertObjectAtIndex:
11241 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11242 return 0;
11243 case NSAPI::NSMutableArr_replaceObjectAtIndex:
11244 return 1;
11245
11246 default:
11247 return None;
11248 }
11249
11250 return None;
11251}
11252
11253static
11254Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11255 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011256 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11257 Message->getReceiverInterface(),
11258 NSAPI::ClassId_NSMutableDictionary);
11259 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011260 return None;
11261 }
11262
11263 Selector Sel = Message->getSelector();
11264
11265 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11266 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11267 if (!MKOpt) {
11268 return None;
11269 }
11270
11271 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11272
11273 switch (MK) {
11274 case NSAPI::NSMutableDict_setObjectForKey:
11275 case NSAPI::NSMutableDict_setValueForKey:
11276 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11277 return 0;
11278
11279 default:
11280 return None;
11281 }
11282
11283 return None;
11284}
11285
11286static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011287 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11288 Message->getReceiverInterface(),
11289 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000011290
Alex Denisov5dfac812015-08-06 04:51:14 +000011291 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11292 Message->getReceiverInterface(),
11293 NSAPI::ClassId_NSMutableOrderedSet);
11294 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011295 return None;
11296 }
11297
11298 Selector Sel = Message->getSelector();
11299
11300 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11301 if (!MKOpt) {
11302 return None;
11303 }
11304
11305 NSAPI::NSSetMethodKind MK = *MKOpt;
11306
11307 switch (MK) {
11308 case NSAPI::NSMutableSet_addObject:
11309 case NSAPI::NSOrderedSet_setObjectAtIndex:
11310 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11311 case NSAPI::NSOrderedSet_insertObjectAtIndex:
11312 return 0;
11313 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11314 return 1;
11315 }
11316
11317 return None;
11318}
11319
11320void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11321 if (!Message->isInstanceMessage()) {
11322 return;
11323 }
11324
11325 Optional<int> ArgOpt;
11326
11327 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11328 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11329 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11330 return;
11331 }
11332
11333 int ArgIndex = *ArgOpt;
11334
Alex Denisove1d882c2015-03-04 17:55:52 +000011335 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11336 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11337 Arg = OE->getSourceExpr()->IgnoreImpCasts();
11338 }
11339
Alex Denisov5dfac812015-08-06 04:51:14 +000011340 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011341 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011342 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011343 Diag(Message->getSourceRange().getBegin(),
11344 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000011345 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000011346 }
11347 }
Alex Denisov5dfac812015-08-06 04:51:14 +000011348 } else {
11349 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11350
11351 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11352 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11353 }
11354
11355 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11356 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11357 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11358 ValueDecl *Decl = ReceiverRE->getDecl();
11359 Diag(Message->getSourceRange().getBegin(),
11360 diag::warn_objc_circular_container)
11361 << Decl->getName() << Decl->getName();
11362 if (!ArgRE->isObjCSelfExpr()) {
11363 Diag(Decl->getLocation(),
11364 diag::note_objc_circular_container_declared_here)
11365 << Decl->getName();
11366 }
11367 }
11368 }
11369 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11370 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11371 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11372 ObjCIvarDecl *Decl = IvarRE->getDecl();
11373 Diag(Message->getSourceRange().getBegin(),
11374 diag::warn_objc_circular_container)
11375 << Decl->getName() << Decl->getName();
11376 Diag(Decl->getLocation(),
11377 diag::note_objc_circular_container_declared_here)
11378 << Decl->getName();
11379 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011380 }
11381 }
11382 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011383}
11384
John McCall31168b02011-06-15 23:02:42 +000011385/// Check a message send to see if it's likely to cause a retain cycle.
11386void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11387 // Only check instance methods whose selector looks like a setter.
11388 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11389 return;
11390
11391 // Try to find a variable that the receiver is strongly owned by.
11392 RetainCycleOwner owner;
11393 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011394 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000011395 return;
11396 } else {
11397 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11398 owner.Variable = getCurMethodDecl()->getSelfDecl();
11399 owner.Loc = msg->getSuperLoc();
11400 owner.Range = msg->getSuperLoc();
11401 }
11402
11403 // Check whether the receiver is captured by any of the arguments.
11404 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
11405 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
11406 return diagnoseRetainCycle(*this, capturer, owner);
11407}
11408
11409/// Check a property assign to see if it's likely to cause a retain cycle.
11410void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11411 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011412 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000011413 return;
11414
11415 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11416 diagnoseRetainCycle(*this, capturer, owner);
11417}
11418
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011419void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11420 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000011421 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011422 return;
11423
11424 // Because we don't have an expression for the variable, we have to set the
11425 // location explicitly here.
11426 Owner.Loc = Var->getLocation();
11427 Owner.Range = Var->getSourceRange();
11428
11429 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11430 diagnoseRetainCycle(*this, Capturer, Owner);
11431}
11432
Ted Kremenek9304da92012-12-21 08:04:28 +000011433static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11434 Expr *RHS, bool isProperty) {
11435 // Check if RHS is an Objective-C object literal, which also can get
11436 // immediately zapped in a weak reference. Note that we explicitly
11437 // allow ObjCStringLiterals, since those are designed to never really die.
11438 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011439
Ted Kremenek64873352012-12-21 22:46:35 +000011440 // This enum needs to match with the 'select' in
11441 // warn_objc_arc_literal_assign (off-by-1).
11442 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11443 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11444 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011445
11446 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000011447 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000011448 << (isProperty ? 0 : 1)
11449 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011450
11451 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000011452}
11453
Ted Kremenekc1f014a2012-12-21 19:45:30 +000011454static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11455 Qualifiers::ObjCLifetime LT,
11456 Expr *RHS, bool isProperty) {
11457 // Strip off any implicit cast added to get to the one ARC-specific.
11458 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11459 if (cast->getCastKind() == CK_ARCConsumeObject) {
11460 S.Diag(Loc, diag::warn_arc_retained_assign)
11461 << (LT == Qualifiers::OCL_ExplicitNone)
11462 << (isProperty ? 0 : 1)
11463 << RHS->getSourceRange();
11464 return true;
11465 }
11466 RHS = cast->getSubExpr();
11467 }
11468
11469 if (LT == Qualifiers::OCL_Weak &&
11470 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11471 return true;
11472
11473 return false;
11474}
11475
Ted Kremenekb36234d2012-12-21 08:04:20 +000011476bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11477 QualType LHS, Expr *RHS) {
11478 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11479
11480 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11481 return false;
11482
11483 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11484 return true;
11485
11486 return false;
11487}
11488
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011489void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11490 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011491 QualType LHSType;
11492 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011493 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011494 ObjCPropertyRefExpr *PRE
11495 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11496 if (PRE && !PRE->isImplicitProperty()) {
11497 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11498 if (PD)
11499 LHSType = PD->getType();
11500 }
11501
11502 if (LHSType.isNull())
11503 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000011504
11505 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11506
11507 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011508 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000011509 getCurFunction()->markSafeWeakUse(LHS);
11510 }
11511
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011512 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11513 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000011514
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011515 // FIXME. Check for other life times.
11516 if (LT != Qualifiers::OCL_None)
11517 return;
11518
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011519 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011520 if (PRE->isImplicitProperty())
11521 return;
11522 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11523 if (!PD)
11524 return;
11525
Bill Wendling44426052012-12-20 19:22:21 +000011526 unsigned Attributes = PD->getPropertyAttributes();
11527 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011528 // when 'assign' attribute was not explicitly specified
11529 // by user, ignore it and rely on property type itself
11530 // for lifetime info.
11531 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11532 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11533 LHSType->isObjCRetainableType())
11534 return;
11535
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011536 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000011537 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011538 Diag(Loc, diag::warn_arc_retained_property_assign)
11539 << RHS->getSourceRange();
11540 return;
11541 }
11542 RHS = cast->getSubExpr();
11543 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011544 }
Bill Wendling44426052012-12-20 19:22:21 +000011545 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000011546 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11547 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000011548 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011549 }
11550}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011551
11552//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11553
11554namespace {
11555bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11556 SourceLocation StmtLoc,
11557 const NullStmt *Body) {
11558 // Do not warn if the body is a macro that expands to nothing, e.g:
11559 //
11560 // #define CALL(x)
11561 // if (condition)
11562 // CALL(0);
11563 //
11564 if (Body->hasLeadingEmptyMacro())
11565 return false;
11566
11567 // Get line numbers of statement and body.
11568 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000011569 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011570 &StmtLineInvalid);
11571 if (StmtLineInvalid)
11572 return false;
11573
11574 bool BodyLineInvalid;
11575 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11576 &BodyLineInvalid);
11577 if (BodyLineInvalid)
11578 return false;
11579
11580 // Warn if null statement and body are on the same line.
11581 if (StmtLine != BodyLine)
11582 return false;
11583
11584 return true;
11585}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011586} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011587
11588void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11589 const Stmt *Body,
11590 unsigned DiagID) {
11591 // Since this is a syntactic check, don't emit diagnostic for template
11592 // instantiations, this just adds noise.
11593 if (CurrentInstantiationScope)
11594 return;
11595
11596 // The body should be a null statement.
11597 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11598 if (!NBody)
11599 return;
11600
11601 // Do the usual checks.
11602 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11603 return;
11604
11605 Diag(NBody->getSemiLoc(), DiagID);
11606 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11607}
11608
11609void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11610 const Stmt *PossibleBody) {
11611 assert(!CurrentInstantiationScope); // Ensured by caller
11612
11613 SourceLocation StmtLoc;
11614 const Stmt *Body;
11615 unsigned DiagID;
11616 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11617 StmtLoc = FS->getRParenLoc();
11618 Body = FS->getBody();
11619 DiagID = diag::warn_empty_for_body;
11620 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11621 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11622 Body = WS->getBody();
11623 DiagID = diag::warn_empty_while_body;
11624 } else
11625 return; // Neither `for' nor `while'.
11626
11627 // The body should be a null statement.
11628 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11629 if (!NBody)
11630 return;
11631
11632 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011633 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011634 return;
11635
11636 // Do the usual checks.
11637 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11638 return;
11639
11640 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11641 // noise level low, emit diagnostics only if for/while is followed by a
11642 // CompoundStmt, e.g.:
11643 // for (int i = 0; i < n; i++);
11644 // {
11645 // a(i);
11646 // }
11647 // or if for/while is followed by a statement with more indentation
11648 // than for/while itself:
11649 // for (int i = 0; i < n; i++);
11650 // a(i);
11651 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11652 if (!ProbableTypo) {
11653 bool BodyColInvalid;
11654 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11655 PossibleBody->getLocStart(),
11656 &BodyColInvalid);
11657 if (BodyColInvalid)
11658 return;
11659
11660 bool StmtColInvalid;
11661 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11662 S->getLocStart(),
11663 &StmtColInvalid);
11664 if (StmtColInvalid)
11665 return;
11666
11667 if (BodyCol > StmtCol)
11668 ProbableTypo = true;
11669 }
11670
11671 if (ProbableTypo) {
11672 Diag(NBody->getSemiLoc(), DiagID);
11673 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11674 }
11675}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011676
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011677//===--- CHECK: Warn on self move with std::move. -------------------------===//
11678
11679/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11680void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11681 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011682 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11683 return;
11684
Richard Smith51ec0cf2017-02-21 01:17:38 +000011685 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011686 return;
11687
11688 // Strip parens and casts away.
11689 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11690 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11691
11692 // Check for a call expression
11693 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11694 if (!CE || CE->getNumArgs() != 1)
11695 return;
11696
11697 // Check for a call to std::move
11698 const FunctionDecl *FD = CE->getDirectCallee();
11699 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11700 !FD->getIdentifier()->isStr("move"))
11701 return;
11702
11703 // Get argument from std::move
11704 RHSExpr = CE->getArg(0);
11705
11706 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11707 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11708
11709 // Two DeclRefExpr's, check that the decls are the same.
11710 if (LHSDeclRef && RHSDeclRef) {
11711 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11712 return;
11713 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11714 RHSDeclRef->getDecl()->getCanonicalDecl())
11715 return;
11716
11717 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11718 << LHSExpr->getSourceRange()
11719 << RHSExpr->getSourceRange();
11720 return;
11721 }
11722
11723 // Member variables require a different approach to check for self moves.
11724 // MemberExpr's are the same if every nested MemberExpr refers to the same
11725 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11726 // the base Expr's are CXXThisExpr's.
11727 const Expr *LHSBase = LHSExpr;
11728 const Expr *RHSBase = RHSExpr;
11729 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11730 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11731 if (!LHSME || !RHSME)
11732 return;
11733
11734 while (LHSME && RHSME) {
11735 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11736 RHSME->getMemberDecl()->getCanonicalDecl())
11737 return;
11738
11739 LHSBase = LHSME->getBase();
11740 RHSBase = RHSME->getBase();
11741 LHSME = dyn_cast<MemberExpr>(LHSBase);
11742 RHSME = dyn_cast<MemberExpr>(RHSBase);
11743 }
11744
11745 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11746 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11747 if (LHSDeclRef && RHSDeclRef) {
11748 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11749 return;
11750 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11751 RHSDeclRef->getDecl()->getCanonicalDecl())
11752 return;
11753
11754 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11755 << LHSExpr->getSourceRange()
11756 << RHSExpr->getSourceRange();
11757 return;
11758 }
11759
11760 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11761 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11762 << LHSExpr->getSourceRange()
11763 << RHSExpr->getSourceRange();
11764}
11765
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011766//===--- Layout compatibility ----------------------------------------------//
11767
11768namespace {
11769
11770bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11771
11772/// \brief Check if two enumeration types are layout-compatible.
11773bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11774 // C++11 [dcl.enum] p8:
11775 // Two enumeration types are layout-compatible if they have the same
11776 // underlying type.
11777 return ED1->isComplete() && ED2->isComplete() &&
11778 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11779}
11780
11781/// \brief Check if two fields are layout-compatible.
11782bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11783 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11784 return false;
11785
11786 if (Field1->isBitField() != Field2->isBitField())
11787 return false;
11788
11789 if (Field1->isBitField()) {
11790 // Make sure that the bit-fields are the same length.
11791 unsigned Bits1 = Field1->getBitWidthValue(C);
11792 unsigned Bits2 = Field2->getBitWidthValue(C);
11793
11794 if (Bits1 != Bits2)
11795 return false;
11796 }
11797
11798 return true;
11799}
11800
11801/// \brief Check if two standard-layout structs are layout-compatible.
11802/// (C++11 [class.mem] p17)
11803bool isLayoutCompatibleStruct(ASTContext &C,
11804 RecordDecl *RD1,
11805 RecordDecl *RD2) {
11806 // If both records are C++ classes, check that base classes match.
11807 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11808 // If one of records is a CXXRecordDecl we are in C++ mode,
11809 // thus the other one is a CXXRecordDecl, too.
11810 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11811 // Check number of base classes.
11812 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11813 return false;
11814
11815 // Check the base classes.
11816 for (CXXRecordDecl::base_class_const_iterator
11817 Base1 = D1CXX->bases_begin(),
11818 BaseEnd1 = D1CXX->bases_end(),
11819 Base2 = D2CXX->bases_begin();
11820 Base1 != BaseEnd1;
11821 ++Base1, ++Base2) {
11822 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11823 return false;
11824 }
11825 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11826 // If only RD2 is a C++ class, it should have zero base classes.
11827 if (D2CXX->getNumBases() > 0)
11828 return false;
11829 }
11830
11831 // Check the fields.
11832 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11833 Field2End = RD2->field_end(),
11834 Field1 = RD1->field_begin(),
11835 Field1End = RD1->field_end();
11836 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11837 if (!isLayoutCompatible(C, *Field1, *Field2))
11838 return false;
11839 }
11840 if (Field1 != Field1End || Field2 != Field2End)
11841 return false;
11842
11843 return true;
11844}
11845
11846/// \brief Check if two standard-layout unions are layout-compatible.
11847/// (C++11 [class.mem] p18)
11848bool isLayoutCompatibleUnion(ASTContext &C,
11849 RecordDecl *RD1,
11850 RecordDecl *RD2) {
11851 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011852 for (auto *Field2 : RD2->fields())
11853 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011854
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011855 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011856 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11857 I = UnmatchedFields.begin(),
11858 E = UnmatchedFields.end();
11859
11860 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011861 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011862 bool Result = UnmatchedFields.erase(*I);
11863 (void) Result;
11864 assert(Result);
11865 break;
11866 }
11867 }
11868 if (I == E)
11869 return false;
11870 }
11871
11872 return UnmatchedFields.empty();
11873}
11874
11875bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11876 if (RD1->isUnion() != RD2->isUnion())
11877 return false;
11878
11879 if (RD1->isUnion())
11880 return isLayoutCompatibleUnion(C, RD1, RD2);
11881 else
11882 return isLayoutCompatibleStruct(C, RD1, RD2);
11883}
11884
11885/// \brief Check if two types are layout-compatible in C++11 sense.
11886bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11887 if (T1.isNull() || T2.isNull())
11888 return false;
11889
11890 // C++11 [basic.types] p11:
11891 // If two types T1 and T2 are the same type, then T1 and T2 are
11892 // layout-compatible types.
11893 if (C.hasSameType(T1, T2))
11894 return true;
11895
11896 T1 = T1.getCanonicalType().getUnqualifiedType();
11897 T2 = T2.getCanonicalType().getUnqualifiedType();
11898
11899 const Type::TypeClass TC1 = T1->getTypeClass();
11900 const Type::TypeClass TC2 = T2->getTypeClass();
11901
11902 if (TC1 != TC2)
11903 return false;
11904
11905 if (TC1 == Type::Enum) {
11906 return isLayoutCompatible(C,
11907 cast<EnumType>(T1)->getDecl(),
11908 cast<EnumType>(T2)->getDecl());
11909 } else if (TC1 == Type::Record) {
11910 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11911 return false;
11912
11913 return isLayoutCompatible(C,
11914 cast<RecordType>(T1)->getDecl(),
11915 cast<RecordType>(T2)->getDecl());
11916 }
11917
11918 return false;
11919}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011920} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011921
11922//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11923
11924namespace {
11925/// \brief Given a type tag expression find the type tag itself.
11926///
11927/// \param TypeExpr Type tag expression, as it appears in user's code.
11928///
11929/// \param VD Declaration of an identifier that appears in a type tag.
11930///
11931/// \param MagicValue Type tag magic value.
11932bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11933 const ValueDecl **VD, uint64_t *MagicValue) {
11934 while(true) {
11935 if (!TypeExpr)
11936 return false;
11937
11938 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11939
11940 switch (TypeExpr->getStmtClass()) {
11941 case Stmt::UnaryOperatorClass: {
11942 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11943 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11944 TypeExpr = UO->getSubExpr();
11945 continue;
11946 }
11947 return false;
11948 }
11949
11950 case Stmt::DeclRefExprClass: {
11951 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11952 *VD = DRE->getDecl();
11953 return true;
11954 }
11955
11956 case Stmt::IntegerLiteralClass: {
11957 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11958 llvm::APInt MagicValueAPInt = IL->getValue();
11959 if (MagicValueAPInt.getActiveBits() <= 64) {
11960 *MagicValue = MagicValueAPInt.getZExtValue();
11961 return true;
11962 } else
11963 return false;
11964 }
11965
11966 case Stmt::BinaryConditionalOperatorClass:
11967 case Stmt::ConditionalOperatorClass: {
11968 const AbstractConditionalOperator *ACO =
11969 cast<AbstractConditionalOperator>(TypeExpr);
11970 bool Result;
11971 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11972 if (Result)
11973 TypeExpr = ACO->getTrueExpr();
11974 else
11975 TypeExpr = ACO->getFalseExpr();
11976 continue;
11977 }
11978 return false;
11979 }
11980
11981 case Stmt::BinaryOperatorClass: {
11982 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11983 if (BO->getOpcode() == BO_Comma) {
11984 TypeExpr = BO->getRHS();
11985 continue;
11986 }
11987 return false;
11988 }
11989
11990 default:
11991 return false;
11992 }
11993 }
11994}
11995
11996/// \brief Retrieve the C type corresponding to type tag TypeExpr.
11997///
11998/// \param TypeExpr Expression that specifies a type tag.
11999///
12000/// \param MagicValues Registered magic values.
12001///
12002/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12003/// kind.
12004///
12005/// \param TypeInfo Information about the corresponding C type.
12006///
12007/// \returns true if the corresponding C type was found.
12008bool GetMatchingCType(
12009 const IdentifierInfo *ArgumentKind,
12010 const Expr *TypeExpr, const ASTContext &Ctx,
12011 const llvm::DenseMap<Sema::TypeTagMagicValue,
12012 Sema::TypeTagData> *MagicValues,
12013 bool &FoundWrongKind,
12014 Sema::TypeTagData &TypeInfo) {
12015 FoundWrongKind = false;
12016
12017 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000012018 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012019
12020 uint64_t MagicValue;
12021
12022 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12023 return false;
12024
12025 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000012026 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012027 if (I->getArgumentKind() != ArgumentKind) {
12028 FoundWrongKind = true;
12029 return false;
12030 }
12031 TypeInfo.Type = I->getMatchingCType();
12032 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12033 TypeInfo.MustBeNull = I->getMustBeNull();
12034 return true;
12035 }
12036 return false;
12037 }
12038
12039 if (!MagicValues)
12040 return false;
12041
12042 llvm::DenseMap<Sema::TypeTagMagicValue,
12043 Sema::TypeTagData>::const_iterator I =
12044 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12045 if (I == MagicValues->end())
12046 return false;
12047
12048 TypeInfo = I->second;
12049 return true;
12050}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000012051} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012052
12053void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12054 uint64_t MagicValue, QualType Type,
12055 bool LayoutCompatible,
12056 bool MustBeNull) {
12057 if (!TypeTagForDatatypeMagicValues)
12058 TypeTagForDatatypeMagicValues.reset(
12059 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12060
12061 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12062 (*TypeTagForDatatypeMagicValues)[Magic] =
12063 TypeTagData(Type, LayoutCompatible, MustBeNull);
12064}
12065
12066namespace {
12067bool IsSameCharType(QualType T1, QualType T2) {
12068 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12069 if (!BT1)
12070 return false;
12071
12072 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12073 if (!BT2)
12074 return false;
12075
12076 BuiltinType::Kind T1Kind = BT1->getKind();
12077 BuiltinType::Kind T2Kind = BT2->getKind();
12078
12079 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
12080 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
12081 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12082 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12083}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000012084} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012085
12086void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
12087 const Expr * const *ExprArgs) {
12088 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12089 bool IsPointerAttr = Attr->getIsPointer();
12090
12091 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
12092 bool FoundWrongKind;
12093 TypeTagData TypeInfo;
12094 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12095 TypeTagForDatatypeMagicValues.get(),
12096 FoundWrongKind, TypeInfo)) {
12097 if (FoundWrongKind)
12098 Diag(TypeTagExpr->getExprLoc(),
12099 diag::warn_type_tag_for_datatype_wrong_kind)
12100 << TypeTagExpr->getSourceRange();
12101 return;
12102 }
12103
12104 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
12105 if (IsPointerAttr) {
12106 // Skip implicit cast of pointer to `void *' (as a function argument).
12107 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000012108 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000012109 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012110 ArgumentExpr = ICE->getSubExpr();
12111 }
12112 QualType ArgumentType = ArgumentExpr->getType();
12113
12114 // Passing a `void*' pointer shouldn't trigger a warning.
12115 if (IsPointerAttr && ArgumentType->isVoidPointerType())
12116 return;
12117
12118 if (TypeInfo.MustBeNull) {
12119 // Type tag with matching void type requires a null pointer.
12120 if (!ArgumentExpr->isNullPointerConstant(Context,
12121 Expr::NPC_ValueDependentIsNotNull)) {
12122 Diag(ArgumentExpr->getExprLoc(),
12123 diag::warn_type_safety_null_pointer_required)
12124 << ArgumentKind->getName()
12125 << ArgumentExpr->getSourceRange()
12126 << TypeTagExpr->getSourceRange();
12127 }
12128 return;
12129 }
12130
12131 QualType RequiredType = TypeInfo.Type;
12132 if (IsPointerAttr)
12133 RequiredType = Context.getPointerType(RequiredType);
12134
12135 bool mismatch = false;
12136 if (!TypeInfo.LayoutCompatible) {
12137 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12138
12139 // C++11 [basic.fundamental] p1:
12140 // Plain char, signed char, and unsigned char are three distinct types.
12141 //
12142 // But we treat plain `char' as equivalent to `signed char' or `unsigned
12143 // char' depending on the current char signedness mode.
12144 if (mismatch)
12145 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12146 RequiredType->getPointeeType())) ||
12147 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12148 mismatch = false;
12149 } else
12150 if (IsPointerAttr)
12151 mismatch = !isLayoutCompatible(Context,
12152 ArgumentType->getPointeeType(),
12153 RequiredType->getPointeeType());
12154 else
12155 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12156
12157 if (mismatch)
12158 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000012159 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012160 << TypeInfo.LayoutCompatible << RequiredType
12161 << ArgumentExpr->getSourceRange()
12162 << TypeTagExpr->getSourceRange();
12163}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012164
12165void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12166 CharUnits Alignment) {
12167 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12168}
12169
12170void Sema::DiagnoseMisalignedMembers() {
12171 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000012172 const NamedDecl *ND = m.RD;
12173 if (ND->getName().empty()) {
12174 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12175 ND = TD;
12176 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012177 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000012178 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012179 }
12180 MisalignedMembers.clear();
12181}
12182
12183void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012184 E = E->IgnoreParens();
12185 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012186 return;
12187 if (isa<UnaryOperator>(E) &&
12188 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12189 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12190 if (isa<MemberExpr>(Op)) {
12191 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12192 MisalignedMember(Op));
12193 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012194 (T->isIntegerType() ||
12195 (T->isPointerType() &&
12196 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012197 MisalignedMembers.erase(MA);
12198 }
12199 }
12200}
12201
12202void Sema::RefersToMemberWithReducedAlignment(
12203 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000012204 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12205 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012206 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012207 if (!ME)
12208 return;
12209
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000012210 // No need to check expressions with an __unaligned-qualified type.
12211 if (E->getType().getQualifiers().hasUnaligned())
12212 return;
12213
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012214 // For a chain of MemberExpr like "a.b.c.d" this list
12215 // will keep FieldDecl's like [d, c, b].
12216 SmallVector<FieldDecl *, 4> ReverseMemberChain;
12217 const MemberExpr *TopME = nullptr;
12218 bool AnyIsPacked = false;
12219 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012220 QualType BaseType = ME->getBase()->getType();
12221 if (ME->isArrow())
12222 BaseType = BaseType->getPointeeType();
12223 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000012224 if (RD->isInvalidDecl())
12225 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012226
12227 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012228 auto *FD = dyn_cast<FieldDecl>(MD);
12229 // We do not care about non-data members.
12230 if (!FD || FD->isInvalidDecl())
12231 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012232
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012233 AnyIsPacked =
12234 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12235 ReverseMemberChain.push_back(FD);
12236
12237 TopME = ME;
12238 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12239 } while (ME);
12240 assert(TopME && "We did not compute a topmost MemberExpr!");
12241
12242 // Not the scope of this diagnostic.
12243 if (!AnyIsPacked)
12244 return;
12245
12246 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12247 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12248 // TODO: The innermost base of the member expression may be too complicated.
12249 // For now, just disregard these cases. This is left for future
12250 // improvement.
12251 if (!DRE && !isa<CXXThisExpr>(TopBase))
12252 return;
12253
12254 // Alignment expected by the whole expression.
12255 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12256
12257 // No need to do anything else with this case.
12258 if (ExpectedAlignment.isOne())
12259 return;
12260
12261 // Synthesize offset of the whole access.
12262 CharUnits Offset;
12263 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12264 I++) {
12265 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12266 }
12267
12268 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12269 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12270 ReverseMemberChain.back()->getParent()->getTypeForDecl());
12271
12272 // The base expression of the innermost MemberExpr may give
12273 // stronger guarantees than the class containing the member.
12274 if (DRE && !TopME->isArrow()) {
12275 const ValueDecl *VD = DRE->getDecl();
12276 if (!VD->getType()->isReferenceType())
12277 CompleteObjectAlignment =
12278 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12279 }
12280
12281 // Check if the synthesized offset fulfills the alignment.
12282 if (Offset % ExpectedAlignment != 0 ||
12283 // It may fulfill the offset it but the effective alignment may still be
12284 // lower than the expected expression alignment.
12285 CompleteObjectAlignment < ExpectedAlignment) {
12286 // If this happens, we want to determine a sensible culprit of this.
12287 // Intuitively, watching the chain of member expressions from right to
12288 // left, we start with the required alignment (as required by the field
12289 // type) but some packed attribute in that chain has reduced the alignment.
12290 // It may happen that another packed structure increases it again. But if
12291 // we are here such increase has not been enough. So pointing the first
12292 // FieldDecl that either is packed or else its RecordDecl is,
12293 // seems reasonable.
12294 FieldDecl *FD = nullptr;
12295 CharUnits Alignment;
12296 for (FieldDecl *FDI : ReverseMemberChain) {
12297 if (FDI->hasAttr<PackedAttr>() ||
12298 FDI->getParent()->hasAttr<PackedAttr>()) {
12299 FD = FDI;
12300 Alignment = std::min(
12301 Context.getTypeAlignInChars(FD->getType()),
12302 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12303 break;
12304 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012305 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012306 assert(FD && "We did not find a packed FieldDecl!");
12307 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012308 }
12309}
12310
12311void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12312 using namespace std::placeholders;
12313 RefersToMemberWithReducedAlignment(
12314 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12315 _2, _3, _4));
12316}
12317