blob: 1828dc6c0408ae9a295852e02629b3f199c81d12 [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
Reid Kleckner30701ed2017-09-05 20:27:35 +0000102static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
103 // We need at least one argument.
104 if (TheCall->getNumArgs() < 1) {
105 S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
106 << 0 << 1 << TheCall->getNumArgs()
107 << TheCall->getCallee()->getSourceRange();
108 return true;
109 }
110
111 // All arguments should be wide string literals.
112 for (Expr *Arg : TheCall->arguments()) {
113 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
114 if (!Literal || !Literal->isWide()) {
115 S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str)
116 << Arg->getSourceRange();
117 return true;
118 }
119 }
120
121 return false;
122}
123
Richard Smith6cbd65d2013-07-11 02:27:57 +0000124/// Check that the argument to __builtin_addressof is a glvalue, and set the
125/// result type to the corresponding pointer type.
126static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
127 if (checkArgCount(S, TheCall, 1))
128 return true;
129
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000130 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000131 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
132 if (ResultType.isNull())
133 return true;
134
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000135 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000136 TheCall->setType(ResultType);
137 return false;
138}
139
John McCall03107a42015-10-29 20:48:01 +0000140static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
141 if (checkArgCount(S, TheCall, 3))
142 return true;
143
144 // First two arguments should be integers.
145 for (unsigned I = 0; I < 2; ++I) {
146 Expr *Arg = TheCall->getArg(I);
147 QualType Ty = Arg->getType();
148 if (!Ty->isIntegerType()) {
149 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
150 << Ty << Arg->getSourceRange();
151 return true;
152 }
153 }
154
155 // Third argument should be a pointer to a non-const integer.
156 // IRGen correctly handles volatile, restrict, and address spaces, and
157 // the other qualifiers aren't possible.
158 {
159 Expr *Arg = TheCall->getArg(2);
160 QualType Ty = Arg->getType();
161 const auto *PtrTy = Ty->getAs<PointerType>();
162 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
163 !PtrTy->getPointeeType().isConstQualified())) {
164 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
165 << Ty << Arg->getSourceRange();
166 return true;
167 }
168 }
169
170 return false;
171}
172
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000173static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
174 CallExpr *TheCall, unsigned SizeIdx,
175 unsigned DstSizeIdx) {
176 if (TheCall->getNumArgs() <= SizeIdx ||
177 TheCall->getNumArgs() <= DstSizeIdx)
178 return;
179
180 const Expr *SizeArg = TheCall->getArg(SizeIdx);
181 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
182
183 llvm::APSInt Size, DstSize;
184
185 // find out if both sizes are known at compile time
186 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
187 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
188 return;
189
190 if (Size.ule(DstSize))
191 return;
192
193 // confirmed overflow so generate the diagnostic.
194 IdentifierInfo *FnName = FDecl->getIdentifier();
195 SourceLocation SL = TheCall->getLocStart();
196 SourceRange SR = TheCall->getSourceRange();
197
198 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
199}
200
Peter Collingbournef7706832014-12-12 23:41:25 +0000201static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
202 if (checkArgCount(S, BuiltinCall, 2))
203 return true;
204
205 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
206 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
207 Expr *Call = BuiltinCall->getArg(0);
208 Expr *Chain = BuiltinCall->getArg(1);
209
210 if (Call->getStmtClass() != Stmt::CallExprClass) {
211 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
212 << Call->getSourceRange();
213 return true;
214 }
215
216 auto CE = cast<CallExpr>(Call);
217 if (CE->getCallee()->getType()->isBlockPointerType()) {
218 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
219 << Call->getSourceRange();
220 return true;
221 }
222
223 const Decl *TargetDecl = CE->getCalleeDecl();
224 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
225 if (FD->getBuiltinID()) {
226 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
227 << Call->getSourceRange();
228 return true;
229 }
230
231 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
232 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
233 << Call->getSourceRange();
234 return true;
235 }
236
237 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
238 if (ChainResult.isInvalid())
239 return true;
240 if (!ChainResult.get()->getType()->isPointerType()) {
241 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
242 << Chain->getSourceRange();
243 return true;
244 }
245
David Majnemerced8bdf2015-02-25 17:36:15 +0000246 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000247 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
248 QualType BuiltinTy = S.Context.getFunctionType(
249 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
250 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
251
252 Builtin =
253 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
254
255 BuiltinCall->setType(CE->getType());
256 BuiltinCall->setValueKind(CE->getValueKind());
257 BuiltinCall->setObjectKind(CE->getObjectKind());
258 BuiltinCall->setCallee(Builtin);
259 BuiltinCall->setArg(1, ChainResult.get());
260
261 return false;
262}
263
Reid Kleckner1d59f992015-01-22 01:36:17 +0000264static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
265 Scope::ScopeFlags NeededScopeFlags,
266 unsigned DiagID) {
267 // Scopes aren't available during instantiation. Fortunately, builtin
268 // functions cannot be template args so they cannot be formed through template
269 // instantiation. Therefore checking once during the parse is sufficient.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000270 if (SemaRef.inTemplateInstantiation())
Reid Kleckner1d59f992015-01-22 01:36:17 +0000271 return false;
272
273 Scope *S = SemaRef.getCurScope();
274 while (S && !S->isSEHExceptScope())
275 S = S->getParent();
276 if (!S || !(S->getFlags() & NeededScopeFlags)) {
277 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
278 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
279 << DRE->getDecl()->getIdentifier();
280 return true;
281 }
282
283 return false;
284}
285
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000286static inline bool isBlockPointer(Expr *Arg) {
287 return Arg->getType()->isBlockPointerType();
288}
289
290/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
291/// void*, which is a requirement of device side enqueue.
292static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
293 const BlockPointerType *BPT =
294 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
295 ArrayRef<QualType> Params =
296 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
297 unsigned ArgCounter = 0;
298 bool IllegalParams = false;
299 // Iterate through the block parameters until either one is found that is not
300 // a local void*, or the block is valid.
301 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
302 I != E; ++I, ++ArgCounter) {
303 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
304 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
305 LangAS::opencl_local) {
306 // Get the location of the error. If a block literal has been passed
307 // (BlockExpr) then we can point straight to the offending argument,
308 // else we just point to the variable reference.
309 SourceLocation ErrorLoc;
310 if (isa<BlockExpr>(BlockArg)) {
311 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
312 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
313 } else if (isa<DeclRefExpr>(BlockArg)) {
314 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
315 }
316 S.Diag(ErrorLoc,
317 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
318 IllegalParams = true;
319 }
320 }
321
322 return IllegalParams;
323}
324
Joey Gouly84ae3362017-07-31 15:15:59 +0000325static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
326 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
327 S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
328 << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
329 return true;
330 }
331 return false;
332}
333
Joey Goulyfa76b492017-08-01 13:27:09 +0000334static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
335 if (checkArgCount(S, TheCall, 2))
336 return true;
337
338 if (checkOpenCLSubgroupExt(S, TheCall))
339 return true;
340
341 // First argument is an ndrange_t type.
342 Expr *NDRangeArg = TheCall->getArg(0);
343 if (NDRangeArg->getType().getAsString() != "ndrange_t") {
344 S.Diag(NDRangeArg->getLocStart(),
345 diag::err_opencl_builtin_expected_type)
346 << TheCall->getDirectCallee() << "'ndrange_t'";
347 return true;
348 }
349
350 Expr *BlockArg = TheCall->getArg(1);
351 if (!isBlockPointer(BlockArg)) {
352 S.Diag(BlockArg->getLocStart(),
353 diag::err_opencl_builtin_expected_type)
354 << TheCall->getDirectCallee() << "block";
355 return true;
356 }
357 return checkOpenCLBlockArgs(S, BlockArg);
358}
359
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000360/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
361/// get_kernel_work_group_size
362/// and get_kernel_preferred_work_group_size_multiple builtin functions.
363static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
364 if (checkArgCount(S, TheCall, 1))
365 return true;
366
367 Expr *BlockArg = TheCall->getArg(0);
368 if (!isBlockPointer(BlockArg)) {
369 S.Diag(BlockArg->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000370 diag::err_opencl_builtin_expected_type)
371 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000372 return true;
373 }
374 return checkOpenCLBlockArgs(S, BlockArg);
375}
376
Simon Pilgrim2c518802017-03-30 14:13:19 +0000377/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000378static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
379 const QualType &IntType);
380
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000381static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000382 unsigned Start, unsigned End) {
383 bool IllegalParams = false;
384 for (unsigned I = Start; I <= End; ++I)
385 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
386 S.Context.getSizeType());
387 return IllegalParams;
388}
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000389
390/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
391/// 'local void*' parameter of passed block.
392static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
393 Expr *BlockArg,
394 unsigned NumNonVarArgs) {
395 const BlockPointerType *BPT =
396 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
397 unsigned NumBlockParams =
398 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
399 unsigned TotalNumArgs = TheCall->getNumArgs();
400
401 // For each argument passed to the block, a corresponding uint needs to
402 // be passed to describe the size of the local memory.
403 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
404 S.Diag(TheCall->getLocStart(),
405 diag::err_opencl_enqueue_kernel_local_size_args);
406 return true;
407 }
408
409 // Check that the sizes of the local memory are specified by integers.
410 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
411 TotalNumArgs - 1);
412}
413
414/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
415/// overload formats specified in Table 6.13.17.1.
416/// int enqueue_kernel(queue_t queue,
417/// kernel_enqueue_flags_t flags,
418/// const ndrange_t ndrange,
419/// void (^block)(void))
420/// int enqueue_kernel(queue_t queue,
421/// kernel_enqueue_flags_t flags,
422/// const ndrange_t ndrange,
423/// uint num_events_in_wait_list,
424/// clk_event_t *event_wait_list,
425/// clk_event_t *event_ret,
426/// void (^block)(void))
427/// int enqueue_kernel(queue_t queue,
428/// kernel_enqueue_flags_t flags,
429/// const ndrange_t ndrange,
430/// void (^block)(local void*, ...),
431/// uint size0, ...)
432/// int enqueue_kernel(queue_t queue,
433/// kernel_enqueue_flags_t flags,
434/// const ndrange_t ndrange,
435/// uint num_events_in_wait_list,
436/// clk_event_t *event_wait_list,
437/// clk_event_t *event_ret,
438/// void (^block)(local void*, ...),
439/// uint size0, ...)
440static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
441 unsigned NumArgs = TheCall->getNumArgs();
442
443 if (NumArgs < 4) {
444 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
445 return true;
446 }
447
448 Expr *Arg0 = TheCall->getArg(0);
449 Expr *Arg1 = TheCall->getArg(1);
450 Expr *Arg2 = TheCall->getArg(2);
451 Expr *Arg3 = TheCall->getArg(3);
452
453 // First argument always needs to be a queue_t type.
454 if (!Arg0->getType()->isQueueT()) {
455 S.Diag(TheCall->getArg(0)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000456 diag::err_opencl_builtin_expected_type)
457 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000458 return true;
459 }
460
461 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
462 if (!Arg1->getType()->isIntegerType()) {
463 S.Diag(TheCall->getArg(1)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000464 diag::err_opencl_builtin_expected_type)
465 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000466 return true;
467 }
468
469 // Third argument is always an ndrange_t type.
Anastasia Stulovab42f3c02017-04-21 15:13:24 +0000470 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000471 S.Diag(TheCall->getArg(2)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000472 diag::err_opencl_builtin_expected_type)
473 << TheCall->getDirectCallee() << "'ndrange_t'";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000474 return true;
475 }
476
477 // With four arguments, there is only one form that the function could be
478 // called in: no events and no variable arguments.
479 if (NumArgs == 4) {
480 // check that the last argument is the right block type.
481 if (!isBlockPointer(Arg3)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000482 S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
483 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000484 return true;
485 }
486 // we have a block type, check the prototype
487 const BlockPointerType *BPT =
488 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
489 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
490 S.Diag(Arg3->getLocStart(),
491 diag::err_opencl_enqueue_kernel_blocks_no_args);
492 return true;
493 }
494 return false;
495 }
496 // we can have block + varargs.
497 if (isBlockPointer(Arg3))
498 return (checkOpenCLBlockArgs(S, Arg3) ||
499 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
500 // last two cases with either exactly 7 args or 7 args and varargs.
501 if (NumArgs >= 7) {
502 // check common block argument.
503 Expr *Arg6 = TheCall->getArg(6);
504 if (!isBlockPointer(Arg6)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000505 S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
506 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000507 return true;
508 }
509 if (checkOpenCLBlockArgs(S, Arg6))
510 return true;
511
512 // Forth argument has to be any integer type.
513 if (!Arg3->getType()->isIntegerType()) {
514 S.Diag(TheCall->getArg(3)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000515 diag::err_opencl_builtin_expected_type)
516 << TheCall->getDirectCallee() << "integer";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000517 return true;
518 }
519 // check remaining common arguments.
520 Expr *Arg4 = TheCall->getArg(4);
521 Expr *Arg5 = TheCall->getArg(5);
522
Anastasia Stulova2b461202016-11-14 15:34:01 +0000523 // Fifth argument is always passed as a pointer to clk_event_t.
524 if (!Arg4->isNullPointerConstant(S.Context,
525 Expr::NPC_ValueDependentIsNotNull) &&
526 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000527 S.Diag(TheCall->getArg(4)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000528 diag::err_opencl_builtin_expected_type)
529 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000530 << S.Context.getPointerType(S.Context.OCLClkEventTy);
531 return true;
532 }
533
Anastasia Stulova2b461202016-11-14 15:34:01 +0000534 // Sixth argument is always passed as a pointer to clk_event_t.
535 if (!Arg5->isNullPointerConstant(S.Context,
536 Expr::NPC_ValueDependentIsNotNull) &&
537 !(Arg5->getType()->isPointerType() &&
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000538 Arg5->getType()->getPointeeType()->isClkEventT())) {
539 S.Diag(TheCall->getArg(5)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000540 diag::err_opencl_builtin_expected_type)
541 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000542 << S.Context.getPointerType(S.Context.OCLClkEventTy);
543 return true;
544 }
545
546 if (NumArgs == 7)
547 return false;
548
549 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
550 }
551
552 // None of the specific case has been detected, give generic error
553 S.Diag(TheCall->getLocStart(),
554 diag::err_opencl_enqueue_kernel_incorrect_args);
555 return true;
556}
557
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000558/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000559static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000560 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000561}
562
563/// Returns true if pipe element type is different from the pointer.
564static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
565 const Expr *Arg0 = Call->getArg(0);
566 // First argument type should always be pipe.
567 if (!Arg0->getType()->isPipeType()) {
568 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000569 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000570 return true;
571 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000572 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000573 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
574 // Validates the access qualifier is compatible with the call.
575 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
576 // read_only and write_only, and assumed to be read_only if no qualifier is
577 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000578 switch (Call->getDirectCallee()->getBuiltinID()) {
579 case Builtin::BIread_pipe:
580 case Builtin::BIreserve_read_pipe:
581 case Builtin::BIcommit_read_pipe:
582 case Builtin::BIwork_group_reserve_read_pipe:
583 case Builtin::BIsub_group_reserve_read_pipe:
584 case Builtin::BIwork_group_commit_read_pipe:
585 case Builtin::BIsub_group_commit_read_pipe:
586 if (!(!AccessQual || AccessQual->isReadOnly())) {
587 S.Diag(Arg0->getLocStart(),
588 diag::err_opencl_builtin_pipe_invalid_access_modifier)
589 << "read_only" << Arg0->getSourceRange();
590 return true;
591 }
592 break;
593 case Builtin::BIwrite_pipe:
594 case Builtin::BIreserve_write_pipe:
595 case Builtin::BIcommit_write_pipe:
596 case Builtin::BIwork_group_reserve_write_pipe:
597 case Builtin::BIsub_group_reserve_write_pipe:
598 case Builtin::BIwork_group_commit_write_pipe:
599 case Builtin::BIsub_group_commit_write_pipe:
600 if (!(AccessQual && AccessQual->isWriteOnly())) {
601 S.Diag(Arg0->getLocStart(),
602 diag::err_opencl_builtin_pipe_invalid_access_modifier)
603 << "write_only" << Arg0->getSourceRange();
604 return true;
605 }
606 break;
607 default:
608 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000609 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000610 return false;
611}
612
613/// Returns true if pipe element type is different from the pointer.
614static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
615 const Expr *Arg0 = Call->getArg(0);
616 const Expr *ArgIdx = Call->getArg(Idx);
617 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000618 const QualType EltTy = PipeTy->getElementType();
619 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000620 // The Idx argument should be a pointer and the type of the pointer and
621 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000622 if (!ArgTy ||
623 !S.Context.hasSameType(
624 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000625 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000626 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000627 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000628 return true;
629 }
630 return false;
631}
632
633// \brief Performs semantic analysis for the read/write_pipe call.
634// \param S Reference to the semantic analyzer.
635// \param Call A pointer to the builtin call.
636// \return True if a semantic error has been found, false otherwise.
637static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000638 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
639 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000640 switch (Call->getNumArgs()) {
641 case 2: {
642 if (checkOpenCLPipeArg(S, Call))
643 return true;
644 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000645 // read/write_pipe(pipe T, T*).
646 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000647 if (checkOpenCLPipePacketType(S, Call, 1))
648 return true;
649 } break;
650
651 case 4: {
652 if (checkOpenCLPipeArg(S, Call))
653 return true;
654 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000655 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
656 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000657 if (!Call->getArg(1)->getType()->isReserveIDT()) {
658 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000659 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000660 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000661 return true;
662 }
663
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000664 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000665 const Expr *Arg2 = Call->getArg(2);
666 if (!Arg2->getType()->isIntegerType() &&
667 !Arg2->getType()->isUnsignedIntegerType()) {
668 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000669 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000670 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000671 return true;
672 }
673
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000674 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000675 if (checkOpenCLPipePacketType(S, Call, 3))
676 return true;
677 } break;
678 default:
679 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000680 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000681 return true;
682 }
683
684 return false;
685}
686
687// \brief Performs a semantic analysis on the {work_group_/sub_group_
688// /_}reserve_{read/write}_pipe
689// \param S Reference to the semantic analyzer.
690// \param Call The call to the builtin function to be analyzed.
691// \return True if a semantic error was found, false otherwise.
692static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
693 if (checkArgCount(S, Call, 2))
694 return true;
695
696 if (checkOpenCLPipeArg(S, Call))
697 return true;
698
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000699 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000700 if (!Call->getArg(1)->getType()->isIntegerType() &&
701 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
702 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000703 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000704 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000705 return true;
706 }
707
Joey Gouly922ca232017-08-09 14:52:47 +0000708 // Since return type of reserve_read/write_pipe built-in function is
709 // reserve_id_t, which is not defined in the builtin def file , we used int
710 // as return type and need to override the return type of these functions.
711 Call->setType(S.Context.OCLReserveIDTy);
712
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000713 return false;
714}
715
716// \brief Performs a semantic analysis on {work_group_/sub_group_
717// /_}commit_{read/write}_pipe
718// \param S Reference to the semantic analyzer.
719// \param Call The call to the builtin function to be analyzed.
720// \return True if a semantic error was found, false otherwise.
721static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
722 if (checkArgCount(S, Call, 2))
723 return true;
724
725 if (checkOpenCLPipeArg(S, Call))
726 return true;
727
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000728 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000729 if (!Call->getArg(1)->getType()->isReserveIDT()) {
730 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000731 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000732 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000733 return true;
734 }
735
736 return false;
737}
738
739// \brief Performs a semantic analysis on the call to built-in Pipe
740// Query Functions.
741// \param S Reference to the semantic analyzer.
742// \param Call The call to the builtin function to be analyzed.
743// \return True if a semantic error was found, false otherwise.
744static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
745 if (checkArgCount(S, Call, 1))
746 return true;
747
748 if (!Call->getArg(0)->getType()->isPipeType()) {
749 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000750 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000751 return true;
752 }
753
754 return false;
755}
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +0000756// \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
Yaxun Liuf7449a12016-05-20 19:54:38 +0000757// \brief Performs semantic analysis for the to_global/local/private call.
758// \param S Reference to the semantic analyzer.
759// \param BuiltinID ID of the builtin function.
760// \param Call A pointer to the builtin call.
761// \return True if a semantic error has been found, false otherwise.
762static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
763 CallExpr *Call) {
Yaxun Liuf7449a12016-05-20 19:54:38 +0000764 if (Call->getNumArgs() != 1) {
765 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
766 << Call->getDirectCallee() << Call->getSourceRange();
767 return true;
768 }
769
770 auto RT = Call->getArg(0)->getType();
771 if (!RT->isPointerType() || RT->getPointeeType()
772 .getAddressSpace() == LangAS::opencl_constant) {
773 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
774 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
775 return true;
776 }
777
778 RT = RT->getPointeeType();
779 auto Qual = RT.getQualifiers();
780 switch (BuiltinID) {
781 case Builtin::BIto_global:
782 Qual.setAddressSpace(LangAS::opencl_global);
783 break;
784 case Builtin::BIto_local:
785 Qual.setAddressSpace(LangAS::opencl_local);
786 break;
787 default:
788 Qual.removeAddressSpace();
789 }
790 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
791 RT.getUnqualifiedType(), Qual)));
792
793 return false;
794}
795
John McCalldadc5752010-08-24 06:29:42 +0000796ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000797Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
798 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000799 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000800
Chris Lattner3be167f2010-10-01 23:23:24 +0000801 // Find out if any arguments are required to be integer constant expressions.
802 unsigned ICEArguments = 0;
803 ASTContext::GetBuiltinTypeError Error;
804 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
805 if (Error != ASTContext::GE_None)
806 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
807
808 // If any arguments are required to be ICE's, check and diagnose.
809 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
810 // Skip arguments not required to be ICE's.
811 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
812
813 llvm::APSInt Result;
814 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
815 return true;
816 ICEArguments &= ~(1 << ArgNo);
817 }
818
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000819 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000820 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000821 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000822 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000823 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000824 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000825 break;
Martin Storsjo022e7822017-07-17 20:49:45 +0000826 case Builtin::BI__builtin_ms_va_start:
Ted Kremeneka174c522008-07-09 17:58:53 +0000827 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000828 case Builtin::BI__builtin_va_start:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000829 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000830 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000831 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000832 case Builtin::BI__va_start: {
833 switch (Context.getTargetInfo().getTriple().getArch()) {
834 case llvm::Triple::arm:
835 case llvm::Triple::thumb:
836 if (SemaBuiltinVAStartARM(TheCall))
837 return ExprError();
838 break;
839 default:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000840 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000841 return ExprError();
842 break;
843 }
844 break;
845 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000846 case Builtin::BI__builtin_isgreater:
847 case Builtin::BI__builtin_isgreaterequal:
848 case Builtin::BI__builtin_isless:
849 case Builtin::BI__builtin_islessequal:
850 case Builtin::BI__builtin_islessgreater:
851 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000852 if (SemaBuiltinUnorderedCompare(TheCall))
853 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000854 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000855 case Builtin::BI__builtin_fpclassify:
856 if (SemaBuiltinFPClassification(TheCall, 6))
857 return ExprError();
858 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000859 case Builtin::BI__builtin_isfinite:
860 case Builtin::BI__builtin_isinf:
861 case Builtin::BI__builtin_isinf_sign:
862 case Builtin::BI__builtin_isnan:
863 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000864 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000865 return ExprError();
866 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000867 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000868 return SemaBuiltinShuffleVector(TheCall);
869 // TheCall will be freed by the smart pointer here, but that's fine, since
870 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000871 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000872 if (SemaBuiltinPrefetch(TheCall))
873 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000874 break;
David Majnemer51169932016-10-31 05:37:48 +0000875 case Builtin::BI__builtin_alloca_with_align:
876 if (SemaBuiltinAllocaWithAlign(TheCall))
877 return ExprError();
878 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000879 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000880 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000881 if (SemaBuiltinAssume(TheCall))
882 return ExprError();
883 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000884 case Builtin::BI__builtin_assume_aligned:
885 if (SemaBuiltinAssumeAligned(TheCall))
886 return ExprError();
887 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000888 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000889 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000890 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000891 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000892 case Builtin::BI__builtin_longjmp:
893 if (SemaBuiltinLongjmp(TheCall))
894 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000895 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000896 case Builtin::BI__builtin_setjmp:
897 if (SemaBuiltinSetjmp(TheCall))
898 return ExprError();
899 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000900 case Builtin::BI_setjmp:
901 case Builtin::BI_setjmpex:
902 if (checkArgCount(*this, TheCall, 1))
903 return true;
904 break;
John McCallbebede42011-02-26 05:39:39 +0000905
906 case Builtin::BI__builtin_classify_type:
907 if (checkArgCount(*this, TheCall, 1)) return true;
908 TheCall->setType(Context.IntTy);
909 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000910 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000911 if (checkArgCount(*this, TheCall, 1)) return true;
912 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000913 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000914 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000915 case Builtin::BI__sync_fetch_and_add_1:
916 case Builtin::BI__sync_fetch_and_add_2:
917 case Builtin::BI__sync_fetch_and_add_4:
918 case Builtin::BI__sync_fetch_and_add_8:
919 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000920 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000921 case Builtin::BI__sync_fetch_and_sub_1:
922 case Builtin::BI__sync_fetch_and_sub_2:
923 case Builtin::BI__sync_fetch_and_sub_4:
924 case Builtin::BI__sync_fetch_and_sub_8:
925 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000926 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000927 case Builtin::BI__sync_fetch_and_or_1:
928 case Builtin::BI__sync_fetch_and_or_2:
929 case Builtin::BI__sync_fetch_and_or_4:
930 case Builtin::BI__sync_fetch_and_or_8:
931 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000932 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000933 case Builtin::BI__sync_fetch_and_and_1:
934 case Builtin::BI__sync_fetch_and_and_2:
935 case Builtin::BI__sync_fetch_and_and_4:
936 case Builtin::BI__sync_fetch_and_and_8:
937 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000938 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000939 case Builtin::BI__sync_fetch_and_xor_1:
940 case Builtin::BI__sync_fetch_and_xor_2:
941 case Builtin::BI__sync_fetch_and_xor_4:
942 case Builtin::BI__sync_fetch_and_xor_8:
943 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000944 case Builtin::BI__sync_fetch_and_nand:
945 case Builtin::BI__sync_fetch_and_nand_1:
946 case Builtin::BI__sync_fetch_and_nand_2:
947 case Builtin::BI__sync_fetch_and_nand_4:
948 case Builtin::BI__sync_fetch_and_nand_8:
949 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000950 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000951 case Builtin::BI__sync_add_and_fetch_1:
952 case Builtin::BI__sync_add_and_fetch_2:
953 case Builtin::BI__sync_add_and_fetch_4:
954 case Builtin::BI__sync_add_and_fetch_8:
955 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000956 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000957 case Builtin::BI__sync_sub_and_fetch_1:
958 case Builtin::BI__sync_sub_and_fetch_2:
959 case Builtin::BI__sync_sub_and_fetch_4:
960 case Builtin::BI__sync_sub_and_fetch_8:
961 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000962 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000963 case Builtin::BI__sync_and_and_fetch_1:
964 case Builtin::BI__sync_and_and_fetch_2:
965 case Builtin::BI__sync_and_and_fetch_4:
966 case Builtin::BI__sync_and_and_fetch_8:
967 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000968 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000969 case Builtin::BI__sync_or_and_fetch_1:
970 case Builtin::BI__sync_or_and_fetch_2:
971 case Builtin::BI__sync_or_and_fetch_4:
972 case Builtin::BI__sync_or_and_fetch_8:
973 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000974 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000975 case Builtin::BI__sync_xor_and_fetch_1:
976 case Builtin::BI__sync_xor_and_fetch_2:
977 case Builtin::BI__sync_xor_and_fetch_4:
978 case Builtin::BI__sync_xor_and_fetch_8:
979 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000980 case Builtin::BI__sync_nand_and_fetch:
981 case Builtin::BI__sync_nand_and_fetch_1:
982 case Builtin::BI__sync_nand_and_fetch_2:
983 case Builtin::BI__sync_nand_and_fetch_4:
984 case Builtin::BI__sync_nand_and_fetch_8:
985 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000986 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000987 case Builtin::BI__sync_val_compare_and_swap_1:
988 case Builtin::BI__sync_val_compare_and_swap_2:
989 case Builtin::BI__sync_val_compare_and_swap_4:
990 case Builtin::BI__sync_val_compare_and_swap_8:
991 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000992 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000993 case Builtin::BI__sync_bool_compare_and_swap_1:
994 case Builtin::BI__sync_bool_compare_and_swap_2:
995 case Builtin::BI__sync_bool_compare_and_swap_4:
996 case Builtin::BI__sync_bool_compare_and_swap_8:
997 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000998 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000999 case Builtin::BI__sync_lock_test_and_set_1:
1000 case Builtin::BI__sync_lock_test_and_set_2:
1001 case Builtin::BI__sync_lock_test_and_set_4:
1002 case Builtin::BI__sync_lock_test_and_set_8:
1003 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001004 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001005 case Builtin::BI__sync_lock_release_1:
1006 case Builtin::BI__sync_lock_release_2:
1007 case Builtin::BI__sync_lock_release_4:
1008 case Builtin::BI__sync_lock_release_8:
1009 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001010 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001011 case Builtin::BI__sync_swap_1:
1012 case Builtin::BI__sync_swap_2:
1013 case Builtin::BI__sync_swap_4:
1014 case Builtin::BI__sync_swap_8:
1015 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001016 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001017 case Builtin::BI__builtin_nontemporal_load:
1018 case Builtin::BI__builtin_nontemporal_store:
1019 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +00001020#define BUILTIN(ID, TYPE, ATTRS)
1021#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1022 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001023 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +00001024#include "clang/Basic/Builtins.def"
Reid Kleckner30701ed2017-09-05 20:27:35 +00001025 case Builtin::BI__annotation:
1026 if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1027 return ExprError();
1028 break;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001029 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +00001030 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001031 return ExprError();
1032 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +00001033 case Builtin::BI__builtin_addressof:
1034 if (SemaBuiltinAddressof(*this, TheCall))
1035 return ExprError();
1036 break;
John McCall03107a42015-10-29 20:48:01 +00001037 case Builtin::BI__builtin_add_overflow:
1038 case Builtin::BI__builtin_sub_overflow:
1039 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +00001040 if (SemaBuiltinOverflow(*this, TheCall))
1041 return ExprError();
1042 break;
Richard Smith760520b2014-06-03 23:27:44 +00001043 case Builtin::BI__builtin_operator_new:
1044 case Builtin::BI__builtin_operator_delete:
1045 if (!getLangOpts().CPlusPlus) {
1046 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
1047 << (BuiltinID == Builtin::BI__builtin_operator_new
1048 ? "__builtin_operator_new"
1049 : "__builtin_operator_delete")
1050 << "C++";
1051 return ExprError();
1052 }
1053 // CodeGen assumes it can find the global new and delete to call,
1054 // so ensure that they are declared.
1055 DeclareGlobalNewDelete();
1056 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001057
1058 // check secure string manipulation functions where overflows
1059 // are detectable at compile time
1060 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001061 case Builtin::BI__builtin___memmove_chk:
1062 case Builtin::BI__builtin___memset_chk:
1063 case Builtin::BI__builtin___strlcat_chk:
1064 case Builtin::BI__builtin___strlcpy_chk:
1065 case Builtin::BI__builtin___strncat_chk:
1066 case Builtin::BI__builtin___strncpy_chk:
1067 case Builtin::BI__builtin___stpncpy_chk:
1068 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1069 break;
Steven Wu566c14e2014-09-24 04:37:33 +00001070 case Builtin::BI__builtin___memccpy_chk:
1071 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1072 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001073 case Builtin::BI__builtin___snprintf_chk:
1074 case Builtin::BI__builtin___vsnprintf_chk:
1075 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1076 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001077 case Builtin::BI__builtin_call_with_static_chain:
1078 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1079 return ExprError();
1080 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001081 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001082 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001083 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1084 diag::err_seh___except_block))
1085 return ExprError();
1086 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001087 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001088 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001089 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1090 diag::err_seh___except_filter))
1091 return ExprError();
1092 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001093 case Builtin::BI__GetExceptionInfo:
1094 if (checkArgCount(*this, TheCall, 1))
1095 return ExprError();
1096
1097 if (CheckCXXThrowOperand(
1098 TheCall->getLocStart(),
1099 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1100 TheCall))
1101 return ExprError();
1102
1103 TheCall->setType(Context.VoidPtrTy);
1104 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001105 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001106 case Builtin::BIread_pipe:
1107 case Builtin::BIwrite_pipe:
1108 // Since those two functions are declared with var args, we need a semantic
1109 // check for the argument.
1110 if (SemaBuiltinRWPipe(*this, TheCall))
1111 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001112 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001113 break;
1114 case Builtin::BIreserve_read_pipe:
1115 case Builtin::BIreserve_write_pipe:
1116 case Builtin::BIwork_group_reserve_read_pipe:
1117 case Builtin::BIwork_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001118 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1119 return ExprError();
Joey Gouly84ae3362017-07-31 15:15:59 +00001120 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001121 case Builtin::BIsub_group_reserve_read_pipe:
1122 case Builtin::BIsub_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001123 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1124 SemaBuiltinReserveRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001125 return ExprError();
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001126 break;
1127 case Builtin::BIcommit_read_pipe:
1128 case Builtin::BIcommit_write_pipe:
1129 case Builtin::BIwork_group_commit_read_pipe:
1130 case Builtin::BIwork_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001131 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1132 return ExprError();
1133 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001134 case Builtin::BIsub_group_commit_read_pipe:
1135 case Builtin::BIsub_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001136 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1137 SemaBuiltinCommitRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001138 return ExprError();
1139 break;
1140 case Builtin::BIget_pipe_num_packets:
1141 case Builtin::BIget_pipe_max_packets:
1142 if (SemaBuiltinPipePackets(*this, TheCall))
1143 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001144 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001145 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001146 case Builtin::BIto_global:
1147 case Builtin::BIto_local:
1148 case Builtin::BIto_private:
1149 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1150 return ExprError();
1151 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001152 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1153 case Builtin::BIenqueue_kernel:
1154 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1155 return ExprError();
1156 break;
1157 case Builtin::BIget_kernel_work_group_size:
1158 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1159 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1160 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001161 break;
Joey Goulyfa76b492017-08-01 13:27:09 +00001162 break;
1163 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1164 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1165 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1166 return ExprError();
1167 break;
Mehdi Amini06d367c2016-10-24 20:39:34 +00001168 case Builtin::BI__builtin_os_log_format:
1169 case Builtin::BI__builtin_os_log_format_buffer_size:
1170 if (SemaBuiltinOSLogFormat(TheCall)) {
1171 return ExprError();
1172 }
1173 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001174 }
Richard Smith760520b2014-06-03 23:27:44 +00001175
Nate Begeman4904e322010-06-08 02:47:44 +00001176 // Since the target specific builtins for each arch overlap, only check those
1177 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001178 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001179 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001180 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001181 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001182 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001183 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001184 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1185 return ExprError();
1186 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001187 case llvm::Triple::aarch64:
1188 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001189 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001190 return ExprError();
1191 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001192 case llvm::Triple::mips:
1193 case llvm::Triple::mipsel:
1194 case llvm::Triple::mips64:
1195 case llvm::Triple::mips64el:
1196 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1197 return ExprError();
1198 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001199 case llvm::Triple::systemz:
1200 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1201 return ExprError();
1202 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001203 case llvm::Triple::x86:
1204 case llvm::Triple::x86_64:
1205 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1206 return ExprError();
1207 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001208 case llvm::Triple::ppc:
1209 case llvm::Triple::ppc64:
1210 case llvm::Triple::ppc64le:
1211 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1212 return ExprError();
1213 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001214 default:
1215 break;
1216 }
1217 }
1218
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001219 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001220}
1221
Nate Begeman91e1fea2010-06-14 05:21:25 +00001222// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001223static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001224 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001225 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001226 switch (Type.getEltType()) {
1227 case NeonTypeFlags::Int8:
1228 case NeonTypeFlags::Poly8:
1229 return shift ? 7 : (8 << IsQuad) - 1;
1230 case NeonTypeFlags::Int16:
1231 case NeonTypeFlags::Poly16:
1232 return shift ? 15 : (4 << IsQuad) - 1;
1233 case NeonTypeFlags::Int32:
1234 return shift ? 31 : (2 << IsQuad) - 1;
1235 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001236 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001237 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001238 case NeonTypeFlags::Poly128:
1239 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001240 case NeonTypeFlags::Float16:
1241 assert(!shift && "cannot shift float types!");
1242 return (4 << IsQuad) - 1;
1243 case NeonTypeFlags::Float32:
1244 assert(!shift && "cannot shift float types!");
1245 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001246 case NeonTypeFlags::Float64:
1247 assert(!shift && "cannot shift float types!");
1248 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001249 }
David Blaikie8a40f702012-01-17 06:56:22 +00001250 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001251}
1252
Bob Wilsone4d77232011-11-08 05:04:11 +00001253/// getNeonEltType - Return the QualType corresponding to the elements of
1254/// the vector type specified by the NeonTypeFlags. This is used to check
1255/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001256static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001257 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001258 switch (Flags.getEltType()) {
1259 case NeonTypeFlags::Int8:
1260 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1261 case NeonTypeFlags::Int16:
1262 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1263 case NeonTypeFlags::Int32:
1264 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1265 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001266 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001267 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1268 else
1269 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1270 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001271 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001272 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001273 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001274 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001275 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001276 if (IsInt64Long)
1277 return Context.UnsignedLongTy;
1278 else
1279 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001280 case NeonTypeFlags::Poly128:
1281 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001282 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001283 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001284 case NeonTypeFlags::Float32:
1285 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001286 case NeonTypeFlags::Float64:
1287 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001288 }
David Blaikie8a40f702012-01-17 06:56:22 +00001289 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001290}
1291
Tim Northover12670412014-02-19 10:37:05 +00001292bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001293 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001294 uint64_t mask = 0;
1295 unsigned TV = 0;
1296 int PtrArgNum = -1;
1297 bool HasConstPtr = false;
1298 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001299#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001300#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001301#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001302 }
1303
1304 // For NEON intrinsics which are overloaded on vector element type, validate
1305 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001306 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001307 if (mask) {
1308 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1309 return true;
1310
1311 TV = Result.getLimitedValue(64);
1312 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1313 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001314 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001315 }
1316
1317 if (PtrArgNum >= 0) {
1318 // Check that pointer arguments have the specified type.
1319 Expr *Arg = TheCall->getArg(PtrArgNum);
1320 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1321 Arg = ICE->getSubExpr();
1322 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1323 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001324
Tim Northovera2ee4332014-03-29 15:09:45 +00001325 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001326 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1327 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001328 bool IsInt64Long =
1329 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1330 QualType EltTy =
1331 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001332 if (HasConstPtr)
1333 EltTy = EltTy.withConst();
1334 QualType LHSTy = Context.getPointerType(EltTy);
1335 AssignConvertType ConvTy;
1336 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1337 if (RHS.isInvalid())
1338 return true;
1339 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1340 RHS.get(), AA_Assigning))
1341 return true;
1342 }
1343
1344 // For NEON intrinsics which take an immediate value as part of the
1345 // instruction, range check them here.
1346 unsigned i = 0, l = 0, u = 0;
1347 switch (BuiltinID) {
1348 default:
1349 return false;
Tim Northover12670412014-02-19 10:37:05 +00001350#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001351#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001352#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001353 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001354
Richard Sandiford28940af2014-04-16 08:47:51 +00001355 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001356}
1357
Tim Northovera2ee4332014-03-29 15:09:45 +00001358bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1359 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001360 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001361 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001362 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001363 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001364 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001365 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1366 BuiltinID == AArch64::BI__builtin_arm_strex ||
1367 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001368 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001369 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001370 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1371 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1372 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001373
1374 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1375
1376 // Ensure that we have the proper number of arguments.
1377 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1378 return true;
1379
1380 // Inspect the pointer argument of the atomic builtin. This should always be
1381 // a pointer type, whose element is an integral scalar or pointer type.
1382 // Because it is a pointer type, we don't have to worry about any implicit
1383 // casts here.
1384 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1385 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1386 if (PointerArgRes.isInvalid())
1387 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001388 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001389
1390 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1391 if (!pointerType) {
1392 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1393 << PointerArg->getType() << PointerArg->getSourceRange();
1394 return true;
1395 }
1396
1397 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1398 // task is to insert the appropriate casts into the AST. First work out just
1399 // what the appropriate type is.
1400 QualType ValType = pointerType->getPointeeType();
1401 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1402 if (IsLdrex)
1403 AddrType.addConst();
1404
1405 // Issue a warning if the cast is dodgy.
1406 CastKind CastNeeded = CK_NoOp;
1407 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1408 CastNeeded = CK_BitCast;
1409 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1410 << PointerArg->getType()
1411 << Context.getPointerType(AddrType)
1412 << AA_Passing << PointerArg->getSourceRange();
1413 }
1414
1415 // Finally, do the cast and replace the argument with the corrected version.
1416 AddrType = Context.getPointerType(AddrType);
1417 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1418 if (PointerArgRes.isInvalid())
1419 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001420 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001421
1422 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1423
1424 // In general, we allow ints, floats and pointers to be loaded and stored.
1425 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1426 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1427 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1428 << PointerArg->getType() << PointerArg->getSourceRange();
1429 return true;
1430 }
1431
1432 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001433 if (Context.getTypeSize(ValType) > MaxWidth) {
1434 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001435 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1436 << PointerArg->getType() << PointerArg->getSourceRange();
1437 return true;
1438 }
1439
1440 switch (ValType.getObjCLifetime()) {
1441 case Qualifiers::OCL_None:
1442 case Qualifiers::OCL_ExplicitNone:
1443 // okay
1444 break;
1445
1446 case Qualifiers::OCL_Weak:
1447 case Qualifiers::OCL_Strong:
1448 case Qualifiers::OCL_Autoreleasing:
1449 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1450 << ValType << PointerArg->getSourceRange();
1451 return true;
1452 }
1453
Tim Northover6aacd492013-07-16 09:47:53 +00001454 if (IsLdrex) {
1455 TheCall->setType(ValType);
1456 return false;
1457 }
1458
1459 // Initialize the argument to be stored.
1460 ExprResult ValArg = TheCall->getArg(0);
1461 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1462 Context, ValType, /*consume*/ false);
1463 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1464 if (ValArg.isInvalid())
1465 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001466 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001467
1468 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1469 // but the custom checker bypasses all default analysis.
1470 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001471 return false;
1472}
1473
Nate Begeman4904e322010-06-08 02:47:44 +00001474bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover6aacd492013-07-16 09:47:53 +00001475 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001476 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1477 BuiltinID == ARM::BI__builtin_arm_strex ||
1478 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001479 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001480 }
1481
Yi Kong26d104a2014-08-13 19:18:14 +00001482 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1483 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1484 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1485 }
1486
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001487 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1488 BuiltinID == ARM::BI__builtin_arm_wsr64)
1489 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1490
1491 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1492 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1493 BuiltinID == ARM::BI__builtin_arm_wsr ||
1494 BuiltinID == ARM::BI__builtin_arm_wsrp)
1495 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1496
Tim Northover12670412014-02-19 10:37:05 +00001497 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1498 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001499
Yi Kong4efadfb2014-07-03 16:01:25 +00001500 // For intrinsics which take an immediate value as part of the instruction,
1501 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001502 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001503 switch (BuiltinID) {
1504 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001505 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1506 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001507 case ARM::BI__builtin_arm_vcvtr_f:
1508 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001509 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001510 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001511 case ARM::BI__builtin_arm_isb:
1512 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001513 }
Nate Begemand773fe62010-06-13 04:47:52 +00001514
Nate Begemanf568b072010-08-03 21:32:34 +00001515 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001516 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001517}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001518
Tim Northover573cbee2014-05-24 12:52:07 +00001519bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001520 CallExpr *TheCall) {
Tim Northover573cbee2014-05-24 12:52:07 +00001521 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001522 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1523 BuiltinID == AArch64::BI__builtin_arm_strex ||
1524 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001525 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1526 }
1527
Yi Konga5548432014-08-13 19:18:20 +00001528 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1529 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1530 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1531 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1532 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1533 }
1534
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001535 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1536 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001537 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001538
1539 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1540 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1541 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1542 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1543 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1544
Tim Northovera2ee4332014-03-29 15:09:45 +00001545 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1546 return true;
1547
Yi Kong19a29ac2014-07-17 10:52:06 +00001548 // For intrinsics which take an immediate value as part of the instruction,
1549 // range check them here.
1550 unsigned i = 0, l = 0, u = 0;
1551 switch (BuiltinID) {
1552 default: return false;
1553 case AArch64::BI__builtin_arm_dmb:
1554 case AArch64::BI__builtin_arm_dsb:
1555 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1556 }
1557
Yi Kong19a29ac2014-07-17 10:52:06 +00001558 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001559}
1560
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001561// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1562// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1563// ordering for DSP is unspecified. MSA is ordered by the data format used
1564// by the underlying instruction i.e., df/m, df/n and then by size.
1565//
1566// FIXME: The size tests here should instead be tablegen'd along with the
1567// definitions from include/clang/Basic/BuiltinsMips.def.
1568// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1569// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001570bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001571 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001572 switch (BuiltinID) {
1573 default: return false;
1574 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1575 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001576 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1577 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1578 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1579 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1580 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001581 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1582 // df/m field.
1583 // These intrinsics take an unsigned 3 bit immediate.
1584 case Mips::BI__builtin_msa_bclri_b:
1585 case Mips::BI__builtin_msa_bnegi_b:
1586 case Mips::BI__builtin_msa_bseti_b:
1587 case Mips::BI__builtin_msa_sat_s_b:
1588 case Mips::BI__builtin_msa_sat_u_b:
1589 case Mips::BI__builtin_msa_slli_b:
1590 case Mips::BI__builtin_msa_srai_b:
1591 case Mips::BI__builtin_msa_srari_b:
1592 case Mips::BI__builtin_msa_srli_b:
1593 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1594 case Mips::BI__builtin_msa_binsli_b:
1595 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1596 // These intrinsics take an unsigned 4 bit immediate.
1597 case Mips::BI__builtin_msa_bclri_h:
1598 case Mips::BI__builtin_msa_bnegi_h:
1599 case Mips::BI__builtin_msa_bseti_h:
1600 case Mips::BI__builtin_msa_sat_s_h:
1601 case Mips::BI__builtin_msa_sat_u_h:
1602 case Mips::BI__builtin_msa_slli_h:
1603 case Mips::BI__builtin_msa_srai_h:
1604 case Mips::BI__builtin_msa_srari_h:
1605 case Mips::BI__builtin_msa_srli_h:
1606 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1607 case Mips::BI__builtin_msa_binsli_h:
1608 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1609 // These intrinsics take an unsigned 5 bit immedate.
1610 // The first block of intrinsics actually have an unsigned 5 bit field,
1611 // not a df/n field.
1612 case Mips::BI__builtin_msa_clei_u_b:
1613 case Mips::BI__builtin_msa_clei_u_h:
1614 case Mips::BI__builtin_msa_clei_u_w:
1615 case Mips::BI__builtin_msa_clei_u_d:
1616 case Mips::BI__builtin_msa_clti_u_b:
1617 case Mips::BI__builtin_msa_clti_u_h:
1618 case Mips::BI__builtin_msa_clti_u_w:
1619 case Mips::BI__builtin_msa_clti_u_d:
1620 case Mips::BI__builtin_msa_maxi_u_b:
1621 case Mips::BI__builtin_msa_maxi_u_h:
1622 case Mips::BI__builtin_msa_maxi_u_w:
1623 case Mips::BI__builtin_msa_maxi_u_d:
1624 case Mips::BI__builtin_msa_mini_u_b:
1625 case Mips::BI__builtin_msa_mini_u_h:
1626 case Mips::BI__builtin_msa_mini_u_w:
1627 case Mips::BI__builtin_msa_mini_u_d:
1628 case Mips::BI__builtin_msa_addvi_b:
1629 case Mips::BI__builtin_msa_addvi_h:
1630 case Mips::BI__builtin_msa_addvi_w:
1631 case Mips::BI__builtin_msa_addvi_d:
1632 case Mips::BI__builtin_msa_bclri_w:
1633 case Mips::BI__builtin_msa_bnegi_w:
1634 case Mips::BI__builtin_msa_bseti_w:
1635 case Mips::BI__builtin_msa_sat_s_w:
1636 case Mips::BI__builtin_msa_sat_u_w:
1637 case Mips::BI__builtin_msa_slli_w:
1638 case Mips::BI__builtin_msa_srai_w:
1639 case Mips::BI__builtin_msa_srari_w:
1640 case Mips::BI__builtin_msa_srli_w:
1641 case Mips::BI__builtin_msa_srlri_w:
1642 case Mips::BI__builtin_msa_subvi_b:
1643 case Mips::BI__builtin_msa_subvi_h:
1644 case Mips::BI__builtin_msa_subvi_w:
1645 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1646 case Mips::BI__builtin_msa_binsli_w:
1647 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1648 // These intrinsics take an unsigned 6 bit immediate.
1649 case Mips::BI__builtin_msa_bclri_d:
1650 case Mips::BI__builtin_msa_bnegi_d:
1651 case Mips::BI__builtin_msa_bseti_d:
1652 case Mips::BI__builtin_msa_sat_s_d:
1653 case Mips::BI__builtin_msa_sat_u_d:
1654 case Mips::BI__builtin_msa_slli_d:
1655 case Mips::BI__builtin_msa_srai_d:
1656 case Mips::BI__builtin_msa_srari_d:
1657 case Mips::BI__builtin_msa_srli_d:
1658 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1659 case Mips::BI__builtin_msa_binsli_d:
1660 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1661 // These intrinsics take a signed 5 bit immediate.
1662 case Mips::BI__builtin_msa_ceqi_b:
1663 case Mips::BI__builtin_msa_ceqi_h:
1664 case Mips::BI__builtin_msa_ceqi_w:
1665 case Mips::BI__builtin_msa_ceqi_d:
1666 case Mips::BI__builtin_msa_clti_s_b:
1667 case Mips::BI__builtin_msa_clti_s_h:
1668 case Mips::BI__builtin_msa_clti_s_w:
1669 case Mips::BI__builtin_msa_clti_s_d:
1670 case Mips::BI__builtin_msa_clei_s_b:
1671 case Mips::BI__builtin_msa_clei_s_h:
1672 case Mips::BI__builtin_msa_clei_s_w:
1673 case Mips::BI__builtin_msa_clei_s_d:
1674 case Mips::BI__builtin_msa_maxi_s_b:
1675 case Mips::BI__builtin_msa_maxi_s_h:
1676 case Mips::BI__builtin_msa_maxi_s_w:
1677 case Mips::BI__builtin_msa_maxi_s_d:
1678 case Mips::BI__builtin_msa_mini_s_b:
1679 case Mips::BI__builtin_msa_mini_s_h:
1680 case Mips::BI__builtin_msa_mini_s_w:
1681 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1682 // These intrinsics take an unsigned 8 bit immediate.
1683 case Mips::BI__builtin_msa_andi_b:
1684 case Mips::BI__builtin_msa_nori_b:
1685 case Mips::BI__builtin_msa_ori_b:
1686 case Mips::BI__builtin_msa_shf_b:
1687 case Mips::BI__builtin_msa_shf_h:
1688 case Mips::BI__builtin_msa_shf_w:
1689 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1690 case Mips::BI__builtin_msa_bseli_b:
1691 case Mips::BI__builtin_msa_bmnzi_b:
1692 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1693 // df/n format
1694 // These intrinsics take an unsigned 4 bit immediate.
1695 case Mips::BI__builtin_msa_copy_s_b:
1696 case Mips::BI__builtin_msa_copy_u_b:
1697 case Mips::BI__builtin_msa_insve_b:
1698 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001699 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1700 // These intrinsics take an unsigned 3 bit immediate.
1701 case Mips::BI__builtin_msa_copy_s_h:
1702 case Mips::BI__builtin_msa_copy_u_h:
1703 case Mips::BI__builtin_msa_insve_h:
1704 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001705 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1706 // These intrinsics take an unsigned 2 bit immediate.
1707 case Mips::BI__builtin_msa_copy_s_w:
1708 case Mips::BI__builtin_msa_copy_u_w:
1709 case Mips::BI__builtin_msa_insve_w:
1710 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001711 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1712 // These intrinsics take an unsigned 1 bit immediate.
1713 case Mips::BI__builtin_msa_copy_s_d:
1714 case Mips::BI__builtin_msa_copy_u_d:
1715 case Mips::BI__builtin_msa_insve_d:
1716 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001717 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1718 // Memory offsets and immediate loads.
1719 // These intrinsics take a signed 10 bit immediate.
Petar Jovanovic9b8b9e82017-03-31 16:16:43 +00001720 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001721 case Mips::BI__builtin_msa_ldi_h:
1722 case Mips::BI__builtin_msa_ldi_w:
1723 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1724 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1725 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1726 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1727 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1728 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1729 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1730 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1731 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001732 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001733
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001734 if (!m)
1735 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1736
1737 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1738 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001739}
1740
Kit Bartone50adcb2015-03-30 19:40:59 +00001741bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1742 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001743 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1744 BuiltinID == PPC::BI__builtin_divdeu ||
1745 BuiltinID == PPC::BI__builtin_bpermd;
1746 bool IsTarget64Bit = Context.getTargetInfo()
1747 .getTypeWidth(Context
1748 .getTargetInfo()
1749 .getIntPtrType()) == 64;
1750 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1751 BuiltinID == PPC::BI__builtin_divweu ||
1752 BuiltinID == PPC::BI__builtin_divde ||
1753 BuiltinID == PPC::BI__builtin_divdeu;
1754
1755 if (Is64BitBltin && !IsTarget64Bit)
1756 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1757 << TheCall->getSourceRange();
1758
1759 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1760 (BuiltinID == PPC::BI__builtin_bpermd &&
1761 !Context.getTargetInfo().hasFeature("bpermd")))
1762 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1763 << TheCall->getSourceRange();
1764
Kit Bartone50adcb2015-03-30 19:40:59 +00001765 switch (BuiltinID) {
1766 default: return false;
1767 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1768 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1769 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1770 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1771 case PPC::BI__builtin_tbegin:
1772 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1773 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1774 case PPC::BI__builtin_tabortwc:
1775 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1776 case PPC::BI__builtin_tabortwci:
1777 case PPC::BI__builtin_tabortdci:
1778 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1779 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
Tony Jiangbbc48e92017-05-24 15:13:32 +00001780 case PPC::BI__builtin_vsx_xxpermdi:
Tony Jiang9aa2c032017-05-24 15:54:13 +00001781 case PPC::BI__builtin_vsx_xxsldwi:
Tony Jiangbbc48e92017-05-24 15:13:32 +00001782 return SemaBuiltinVSX(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00001783 }
1784 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1785}
1786
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001787bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1788 CallExpr *TheCall) {
1789 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1790 Expr *Arg = TheCall->getArg(0);
1791 llvm::APSInt AbortCode(32);
1792 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1793 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1794 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1795 << Arg->getSourceRange();
1796 }
1797
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001798 // For intrinsics which take an immediate value as part of the instruction,
1799 // range check them here.
1800 unsigned i = 0, l = 0, u = 0;
1801 switch (BuiltinID) {
1802 default: return false;
1803 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1804 case SystemZ::BI__builtin_s390_verimb:
1805 case SystemZ::BI__builtin_s390_verimh:
1806 case SystemZ::BI__builtin_s390_verimf:
1807 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1808 case SystemZ::BI__builtin_s390_vfaeb:
1809 case SystemZ::BI__builtin_s390_vfaeh:
1810 case SystemZ::BI__builtin_s390_vfaef:
1811 case SystemZ::BI__builtin_s390_vfaebs:
1812 case SystemZ::BI__builtin_s390_vfaehs:
1813 case SystemZ::BI__builtin_s390_vfaefs:
1814 case SystemZ::BI__builtin_s390_vfaezb:
1815 case SystemZ::BI__builtin_s390_vfaezh:
1816 case SystemZ::BI__builtin_s390_vfaezf:
1817 case SystemZ::BI__builtin_s390_vfaezbs:
1818 case SystemZ::BI__builtin_s390_vfaezhs:
1819 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001820 case SystemZ::BI__builtin_s390_vfisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001821 case SystemZ::BI__builtin_s390_vfidb:
1822 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1823 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001824 case SystemZ::BI__builtin_s390_vftcisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001825 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1826 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1827 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1828 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1829 case SystemZ::BI__builtin_s390_vstrcb:
1830 case SystemZ::BI__builtin_s390_vstrch:
1831 case SystemZ::BI__builtin_s390_vstrcf:
1832 case SystemZ::BI__builtin_s390_vstrczb:
1833 case SystemZ::BI__builtin_s390_vstrczh:
1834 case SystemZ::BI__builtin_s390_vstrczf:
1835 case SystemZ::BI__builtin_s390_vstrcbs:
1836 case SystemZ::BI__builtin_s390_vstrchs:
1837 case SystemZ::BI__builtin_s390_vstrcfs:
1838 case SystemZ::BI__builtin_s390_vstrczbs:
1839 case SystemZ::BI__builtin_s390_vstrczhs:
1840 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001841 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
1842 case SystemZ::BI__builtin_s390_vfminsb:
1843 case SystemZ::BI__builtin_s390_vfmaxsb:
1844 case SystemZ::BI__builtin_s390_vfmindb:
1845 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001846 }
1847 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001848}
1849
Craig Topper5ba2c502015-11-07 08:08:31 +00001850/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1851/// This checks that the target supports __builtin_cpu_supports and
1852/// that the string argument is constant and valid.
1853static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1854 Expr *Arg = TheCall->getArg(0);
1855
1856 // Check if the argument is a string literal.
1857 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1858 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1859 << Arg->getSourceRange();
1860
1861 // Check the contents of the string.
1862 StringRef Feature =
1863 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1864 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1865 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1866 << Arg->getSourceRange();
1867 return false;
1868}
1869
Craig Topper699ae0c2017-08-10 20:28:30 +00001870/// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
1871/// This checks that the target supports __builtin_cpu_is and
1872/// that the string argument is constant and valid.
1873static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
1874 Expr *Arg = TheCall->getArg(0);
1875
1876 // Check if the argument is a string literal.
1877 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1878 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1879 << Arg->getSourceRange();
1880
1881 // Check the contents of the string.
1882 StringRef Feature =
1883 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1884 if (!S.Context.getTargetInfo().validateCpuIs(Feature))
1885 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
1886 << Arg->getSourceRange();
1887 return false;
1888}
1889
Craig Toppera7e253e2016-09-23 04:48:31 +00001890// Check if the rounding mode is legal.
1891bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1892 // Indicates if this instruction has rounding control or just SAE.
1893 bool HasRC = false;
1894
1895 unsigned ArgNum = 0;
1896 switch (BuiltinID) {
1897 default:
1898 return false;
1899 case X86::BI__builtin_ia32_vcvttsd2si32:
1900 case X86::BI__builtin_ia32_vcvttsd2si64:
1901 case X86::BI__builtin_ia32_vcvttsd2usi32:
1902 case X86::BI__builtin_ia32_vcvttsd2usi64:
1903 case X86::BI__builtin_ia32_vcvttss2si32:
1904 case X86::BI__builtin_ia32_vcvttss2si64:
1905 case X86::BI__builtin_ia32_vcvttss2usi32:
1906 case X86::BI__builtin_ia32_vcvttss2usi64:
1907 ArgNum = 1;
1908 break;
1909 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1910 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1911 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1912 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1913 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1914 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1915 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1916 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1917 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1918 case X86::BI__builtin_ia32_exp2pd_mask:
1919 case X86::BI__builtin_ia32_exp2ps_mask:
1920 case X86::BI__builtin_ia32_getexppd512_mask:
1921 case X86::BI__builtin_ia32_getexpps512_mask:
1922 case X86::BI__builtin_ia32_rcp28pd_mask:
1923 case X86::BI__builtin_ia32_rcp28ps_mask:
1924 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1925 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1926 case X86::BI__builtin_ia32_vcomisd:
1927 case X86::BI__builtin_ia32_vcomiss:
1928 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1929 ArgNum = 3;
1930 break;
1931 case X86::BI__builtin_ia32_cmppd512_mask:
1932 case X86::BI__builtin_ia32_cmpps512_mask:
1933 case X86::BI__builtin_ia32_cmpsd_mask:
1934 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001935 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001936 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1937 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001938 case X86::BI__builtin_ia32_maxpd512_mask:
1939 case X86::BI__builtin_ia32_maxps512_mask:
1940 case X86::BI__builtin_ia32_maxsd_round_mask:
1941 case X86::BI__builtin_ia32_maxss_round_mask:
1942 case X86::BI__builtin_ia32_minpd512_mask:
1943 case X86::BI__builtin_ia32_minps512_mask:
1944 case X86::BI__builtin_ia32_minsd_round_mask:
1945 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001946 case X86::BI__builtin_ia32_rcp28sd_round_mask:
1947 case X86::BI__builtin_ia32_rcp28ss_round_mask:
1948 case X86::BI__builtin_ia32_reducepd512_mask:
1949 case X86::BI__builtin_ia32_reduceps512_mask:
1950 case X86::BI__builtin_ia32_rndscalepd_mask:
1951 case X86::BI__builtin_ia32_rndscaleps_mask:
1952 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1953 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1954 ArgNum = 4;
1955 break;
1956 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001957 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001958 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001959 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001960 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001961 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001962 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001963 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001964 case X86::BI__builtin_ia32_rangepd512_mask:
1965 case X86::BI__builtin_ia32_rangeps512_mask:
1966 case X86::BI__builtin_ia32_rangesd128_round_mask:
1967 case X86::BI__builtin_ia32_rangess128_round_mask:
1968 case X86::BI__builtin_ia32_reducesd_mask:
1969 case X86::BI__builtin_ia32_reducess_mask:
1970 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1971 case X86::BI__builtin_ia32_rndscaless_round_mask:
1972 ArgNum = 5;
1973 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00001974 case X86::BI__builtin_ia32_vcvtsd2si64:
1975 case X86::BI__builtin_ia32_vcvtsd2si32:
1976 case X86::BI__builtin_ia32_vcvtsd2usi32:
1977 case X86::BI__builtin_ia32_vcvtsd2usi64:
1978 case X86::BI__builtin_ia32_vcvtss2si32:
1979 case X86::BI__builtin_ia32_vcvtss2si64:
1980 case X86::BI__builtin_ia32_vcvtss2usi32:
1981 case X86::BI__builtin_ia32_vcvtss2usi64:
1982 ArgNum = 1;
1983 HasRC = true;
1984 break;
Craig Topper8e066312016-11-07 07:01:09 +00001985 case X86::BI__builtin_ia32_cvtsi2sd64:
1986 case X86::BI__builtin_ia32_cvtsi2ss32:
1987 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00001988 case X86::BI__builtin_ia32_cvtusi2sd64:
1989 case X86::BI__builtin_ia32_cvtusi2ss32:
1990 case X86::BI__builtin_ia32_cvtusi2ss64:
1991 ArgNum = 2;
1992 HasRC = true;
1993 break;
1994 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1995 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1996 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1997 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1998 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1999 case X86::BI__builtin_ia32_cvtps2qq512_mask:
2000 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2001 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2002 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2003 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2004 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002005 case X86::BI__builtin_ia32_sqrtpd512_mask:
2006 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002007 ArgNum = 3;
2008 HasRC = true;
2009 break;
2010 case X86::BI__builtin_ia32_addpd512_mask:
2011 case X86::BI__builtin_ia32_addps512_mask:
2012 case X86::BI__builtin_ia32_divpd512_mask:
2013 case X86::BI__builtin_ia32_divps512_mask:
2014 case X86::BI__builtin_ia32_mulpd512_mask:
2015 case X86::BI__builtin_ia32_mulps512_mask:
2016 case X86::BI__builtin_ia32_subpd512_mask:
2017 case X86::BI__builtin_ia32_subps512_mask:
2018 case X86::BI__builtin_ia32_addss_round_mask:
2019 case X86::BI__builtin_ia32_addsd_round_mask:
2020 case X86::BI__builtin_ia32_divss_round_mask:
2021 case X86::BI__builtin_ia32_divsd_round_mask:
2022 case X86::BI__builtin_ia32_mulss_round_mask:
2023 case X86::BI__builtin_ia32_mulsd_round_mask:
2024 case X86::BI__builtin_ia32_subss_round_mask:
2025 case X86::BI__builtin_ia32_subsd_round_mask:
2026 case X86::BI__builtin_ia32_scalefpd512_mask:
2027 case X86::BI__builtin_ia32_scalefps512_mask:
2028 case X86::BI__builtin_ia32_scalefsd_round_mask:
2029 case X86::BI__builtin_ia32_scalefss_round_mask:
2030 case X86::BI__builtin_ia32_getmantpd512_mask:
2031 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002032 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2033 case X86::BI__builtin_ia32_sqrtsd_round_mask:
2034 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002035 case X86::BI__builtin_ia32_vfmaddpd512_mask:
2036 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2037 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2038 case X86::BI__builtin_ia32_vfmaddps512_mask:
2039 case X86::BI__builtin_ia32_vfmaddps512_mask3:
2040 case X86::BI__builtin_ia32_vfmaddps512_maskz:
2041 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2042 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2043 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2044 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2045 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2046 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2047 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2048 case X86::BI__builtin_ia32_vfmsubps512_mask3:
2049 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2050 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
2051 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
2052 case X86::BI__builtin_ia32_vfnmaddps512_mask:
2053 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
2054 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
2055 case X86::BI__builtin_ia32_vfnmsubps512_mask:
2056 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
2057 case X86::BI__builtin_ia32_vfmaddsd3_mask:
2058 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2059 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2060 case X86::BI__builtin_ia32_vfmaddss3_mask:
2061 case X86::BI__builtin_ia32_vfmaddss3_maskz:
2062 case X86::BI__builtin_ia32_vfmaddss3_mask3:
2063 ArgNum = 4;
2064 HasRC = true;
2065 break;
2066 case X86::BI__builtin_ia32_getmantsd_round_mask:
2067 case X86::BI__builtin_ia32_getmantss_round_mask:
2068 ArgNum = 5;
2069 HasRC = true;
2070 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00002071 }
2072
2073 llvm::APSInt Result;
2074
2075 // We can't check the value of a dependent argument.
2076 Expr *Arg = TheCall->getArg(ArgNum);
2077 if (Arg->isTypeDependent() || Arg->isValueDependent())
2078 return false;
2079
2080 // Check constant-ness first.
2081 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2082 return true;
2083
2084 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2085 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2086 // combined with ROUND_NO_EXC.
2087 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2088 Result == 8/*ROUND_NO_EXC*/ ||
2089 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2090 return false;
2091
2092 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2093 << Arg->getSourceRange();
2094}
2095
Craig Topperdf5beb22017-03-13 17:16:50 +00002096// Check if the gather/scatter scale is legal.
2097bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2098 CallExpr *TheCall) {
2099 unsigned ArgNum = 0;
2100 switch (BuiltinID) {
2101 default:
2102 return false;
2103 case X86::BI__builtin_ia32_gatherpfdpd:
2104 case X86::BI__builtin_ia32_gatherpfdps:
2105 case X86::BI__builtin_ia32_gatherpfqpd:
2106 case X86::BI__builtin_ia32_gatherpfqps:
2107 case X86::BI__builtin_ia32_scatterpfdpd:
2108 case X86::BI__builtin_ia32_scatterpfdps:
2109 case X86::BI__builtin_ia32_scatterpfqpd:
2110 case X86::BI__builtin_ia32_scatterpfqps:
2111 ArgNum = 3;
2112 break;
2113 case X86::BI__builtin_ia32_gatherd_pd:
2114 case X86::BI__builtin_ia32_gatherd_pd256:
2115 case X86::BI__builtin_ia32_gatherq_pd:
2116 case X86::BI__builtin_ia32_gatherq_pd256:
2117 case X86::BI__builtin_ia32_gatherd_ps:
2118 case X86::BI__builtin_ia32_gatherd_ps256:
2119 case X86::BI__builtin_ia32_gatherq_ps:
2120 case X86::BI__builtin_ia32_gatherq_ps256:
2121 case X86::BI__builtin_ia32_gatherd_q:
2122 case X86::BI__builtin_ia32_gatherd_q256:
2123 case X86::BI__builtin_ia32_gatherq_q:
2124 case X86::BI__builtin_ia32_gatherq_q256:
2125 case X86::BI__builtin_ia32_gatherd_d:
2126 case X86::BI__builtin_ia32_gatherd_d256:
2127 case X86::BI__builtin_ia32_gatherq_d:
2128 case X86::BI__builtin_ia32_gatherq_d256:
2129 case X86::BI__builtin_ia32_gather3div2df:
2130 case X86::BI__builtin_ia32_gather3div2di:
2131 case X86::BI__builtin_ia32_gather3div4df:
2132 case X86::BI__builtin_ia32_gather3div4di:
2133 case X86::BI__builtin_ia32_gather3div4sf:
2134 case X86::BI__builtin_ia32_gather3div4si:
2135 case X86::BI__builtin_ia32_gather3div8sf:
2136 case X86::BI__builtin_ia32_gather3div8si:
2137 case X86::BI__builtin_ia32_gather3siv2df:
2138 case X86::BI__builtin_ia32_gather3siv2di:
2139 case X86::BI__builtin_ia32_gather3siv4df:
2140 case X86::BI__builtin_ia32_gather3siv4di:
2141 case X86::BI__builtin_ia32_gather3siv4sf:
2142 case X86::BI__builtin_ia32_gather3siv4si:
2143 case X86::BI__builtin_ia32_gather3siv8sf:
2144 case X86::BI__builtin_ia32_gather3siv8si:
2145 case X86::BI__builtin_ia32_gathersiv8df:
2146 case X86::BI__builtin_ia32_gathersiv16sf:
2147 case X86::BI__builtin_ia32_gatherdiv8df:
2148 case X86::BI__builtin_ia32_gatherdiv16sf:
2149 case X86::BI__builtin_ia32_gathersiv8di:
2150 case X86::BI__builtin_ia32_gathersiv16si:
2151 case X86::BI__builtin_ia32_gatherdiv8di:
2152 case X86::BI__builtin_ia32_gatherdiv16si:
2153 case X86::BI__builtin_ia32_scatterdiv2df:
2154 case X86::BI__builtin_ia32_scatterdiv2di:
2155 case X86::BI__builtin_ia32_scatterdiv4df:
2156 case X86::BI__builtin_ia32_scatterdiv4di:
2157 case X86::BI__builtin_ia32_scatterdiv4sf:
2158 case X86::BI__builtin_ia32_scatterdiv4si:
2159 case X86::BI__builtin_ia32_scatterdiv8sf:
2160 case X86::BI__builtin_ia32_scatterdiv8si:
2161 case X86::BI__builtin_ia32_scattersiv2df:
2162 case X86::BI__builtin_ia32_scattersiv2di:
2163 case X86::BI__builtin_ia32_scattersiv4df:
2164 case X86::BI__builtin_ia32_scattersiv4di:
2165 case X86::BI__builtin_ia32_scattersiv4sf:
2166 case X86::BI__builtin_ia32_scattersiv4si:
2167 case X86::BI__builtin_ia32_scattersiv8sf:
2168 case X86::BI__builtin_ia32_scattersiv8si:
2169 case X86::BI__builtin_ia32_scattersiv8df:
2170 case X86::BI__builtin_ia32_scattersiv16sf:
2171 case X86::BI__builtin_ia32_scatterdiv8df:
2172 case X86::BI__builtin_ia32_scatterdiv16sf:
2173 case X86::BI__builtin_ia32_scattersiv8di:
2174 case X86::BI__builtin_ia32_scattersiv16si:
2175 case X86::BI__builtin_ia32_scatterdiv8di:
2176 case X86::BI__builtin_ia32_scatterdiv16si:
2177 ArgNum = 4;
2178 break;
2179 }
2180
2181 llvm::APSInt Result;
2182
2183 // We can't check the value of a dependent argument.
2184 Expr *Arg = TheCall->getArg(ArgNum);
2185 if (Arg->isTypeDependent() || Arg->isValueDependent())
2186 return false;
2187
2188 // Check constant-ness first.
2189 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2190 return true;
2191
2192 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2193 return false;
2194
2195 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2196 << Arg->getSourceRange();
2197}
2198
Craig Topperf0ddc892016-09-23 04:48:27 +00002199bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2200 if (BuiltinID == X86::BI__builtin_cpu_supports)
2201 return SemaBuiltinCpuSupports(*this, TheCall);
2202
Craig Topper699ae0c2017-08-10 20:28:30 +00002203 if (BuiltinID == X86::BI__builtin_cpu_is)
2204 return SemaBuiltinCpuIs(*this, TheCall);
2205
Craig Toppera7e253e2016-09-23 04:48:31 +00002206 // If the intrinsic has rounding or SAE make sure its valid.
2207 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2208 return true;
2209
Craig Topperdf5beb22017-03-13 17:16:50 +00002210 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2211 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2212 return true;
2213
Craig Topperf0ddc892016-09-23 04:48:27 +00002214 // For intrinsics which take an immediate value as part of the instruction,
2215 // range check them here.
2216 int i = 0, l = 0, u = 0;
2217 switch (BuiltinID) {
2218 default:
2219 return false;
Richard Trieucc3949d2016-02-18 22:34:54 +00002220 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00002221 i = 1; l = 0; u = 3;
2222 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002223 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00002224 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2225 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2226 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2227 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002228 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002229 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002230 case X86::BI__builtin_ia32_vpermil2pd:
2231 case X86::BI__builtin_ia32_vpermil2pd256:
2232 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002233 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002234 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002235 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002236 case X86::BI__builtin_ia32_cmpb128_mask:
2237 case X86::BI__builtin_ia32_cmpw128_mask:
2238 case X86::BI__builtin_ia32_cmpd128_mask:
2239 case X86::BI__builtin_ia32_cmpq128_mask:
2240 case X86::BI__builtin_ia32_cmpb256_mask:
2241 case X86::BI__builtin_ia32_cmpw256_mask:
2242 case X86::BI__builtin_ia32_cmpd256_mask:
2243 case X86::BI__builtin_ia32_cmpq256_mask:
2244 case X86::BI__builtin_ia32_cmpb512_mask:
2245 case X86::BI__builtin_ia32_cmpw512_mask:
2246 case X86::BI__builtin_ia32_cmpd512_mask:
2247 case X86::BI__builtin_ia32_cmpq512_mask:
2248 case X86::BI__builtin_ia32_ucmpb128_mask:
2249 case X86::BI__builtin_ia32_ucmpw128_mask:
2250 case X86::BI__builtin_ia32_ucmpd128_mask:
2251 case X86::BI__builtin_ia32_ucmpq128_mask:
2252 case X86::BI__builtin_ia32_ucmpb256_mask:
2253 case X86::BI__builtin_ia32_ucmpw256_mask:
2254 case X86::BI__builtin_ia32_ucmpd256_mask:
2255 case X86::BI__builtin_ia32_ucmpq256_mask:
2256 case X86::BI__builtin_ia32_ucmpb512_mask:
2257 case X86::BI__builtin_ia32_ucmpw512_mask:
2258 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002259 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002260 case X86::BI__builtin_ia32_vpcomub:
2261 case X86::BI__builtin_ia32_vpcomuw:
2262 case X86::BI__builtin_ia32_vpcomud:
2263 case X86::BI__builtin_ia32_vpcomuq:
2264 case X86::BI__builtin_ia32_vpcomb:
2265 case X86::BI__builtin_ia32_vpcomw:
2266 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002267 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00002268 i = 2; l = 0; u = 7;
2269 break;
2270 case X86::BI__builtin_ia32_roundps:
2271 case X86::BI__builtin_ia32_roundpd:
2272 case X86::BI__builtin_ia32_roundps256:
2273 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002274 i = 1; l = 0; u = 15;
2275 break;
2276 case X86::BI__builtin_ia32_roundss:
2277 case X86::BI__builtin_ia32_roundsd:
2278 case X86::BI__builtin_ia32_rangepd128_mask:
2279 case X86::BI__builtin_ia32_rangepd256_mask:
2280 case X86::BI__builtin_ia32_rangepd512_mask:
2281 case X86::BI__builtin_ia32_rangeps128_mask:
2282 case X86::BI__builtin_ia32_rangeps256_mask:
2283 case X86::BI__builtin_ia32_rangeps512_mask:
2284 case X86::BI__builtin_ia32_getmantsd_round_mask:
2285 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002286 i = 2; l = 0; u = 15;
2287 break;
2288 case X86::BI__builtin_ia32_cmpps:
2289 case X86::BI__builtin_ia32_cmpss:
2290 case X86::BI__builtin_ia32_cmppd:
2291 case X86::BI__builtin_ia32_cmpsd:
2292 case X86::BI__builtin_ia32_cmpps256:
2293 case X86::BI__builtin_ia32_cmppd256:
2294 case X86::BI__builtin_ia32_cmpps128_mask:
2295 case X86::BI__builtin_ia32_cmppd128_mask:
2296 case X86::BI__builtin_ia32_cmpps256_mask:
2297 case X86::BI__builtin_ia32_cmppd256_mask:
2298 case X86::BI__builtin_ia32_cmpps512_mask:
2299 case X86::BI__builtin_ia32_cmppd512_mask:
2300 case X86::BI__builtin_ia32_cmpsd_mask:
2301 case X86::BI__builtin_ia32_cmpss_mask:
2302 i = 2; l = 0; u = 31;
2303 break;
2304 case X86::BI__builtin_ia32_xabort:
2305 i = 0; l = -128; u = 255;
2306 break;
2307 case X86::BI__builtin_ia32_pshufw:
2308 case X86::BI__builtin_ia32_aeskeygenassist128:
2309 i = 1; l = -128; u = 255;
2310 break;
2311 case X86::BI__builtin_ia32_vcvtps2ph:
2312 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper39c87102016-05-18 03:18:12 +00002313 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2314 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2315 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2316 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2317 case X86::BI__builtin_ia32_rndscaleps_mask:
2318 case X86::BI__builtin_ia32_rndscalepd_mask:
2319 case X86::BI__builtin_ia32_reducepd128_mask:
2320 case X86::BI__builtin_ia32_reducepd256_mask:
2321 case X86::BI__builtin_ia32_reducepd512_mask:
2322 case X86::BI__builtin_ia32_reduceps128_mask:
2323 case X86::BI__builtin_ia32_reduceps256_mask:
2324 case X86::BI__builtin_ia32_reduceps512_mask:
2325 case X86::BI__builtin_ia32_prold512_mask:
2326 case X86::BI__builtin_ia32_prolq512_mask:
2327 case X86::BI__builtin_ia32_prold128_mask:
2328 case X86::BI__builtin_ia32_prold256_mask:
2329 case X86::BI__builtin_ia32_prolq128_mask:
2330 case X86::BI__builtin_ia32_prolq256_mask:
2331 case X86::BI__builtin_ia32_prord128_mask:
2332 case X86::BI__builtin_ia32_prord256_mask:
2333 case X86::BI__builtin_ia32_prorq128_mask:
2334 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002335 case X86::BI__builtin_ia32_fpclasspd128_mask:
2336 case X86::BI__builtin_ia32_fpclasspd256_mask:
2337 case X86::BI__builtin_ia32_fpclassps128_mask:
2338 case X86::BI__builtin_ia32_fpclassps256_mask:
2339 case X86::BI__builtin_ia32_fpclassps512_mask:
2340 case X86::BI__builtin_ia32_fpclasspd512_mask:
2341 case X86::BI__builtin_ia32_fpclasssd_mask:
2342 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002343 i = 1; l = 0; u = 255;
2344 break;
2345 case X86::BI__builtin_ia32_palignr:
2346 case X86::BI__builtin_ia32_insertps128:
2347 case X86::BI__builtin_ia32_dpps:
2348 case X86::BI__builtin_ia32_dppd:
2349 case X86::BI__builtin_ia32_dpps256:
2350 case X86::BI__builtin_ia32_mpsadbw128:
2351 case X86::BI__builtin_ia32_mpsadbw256:
2352 case X86::BI__builtin_ia32_pcmpistrm128:
2353 case X86::BI__builtin_ia32_pcmpistri128:
2354 case X86::BI__builtin_ia32_pcmpistria128:
2355 case X86::BI__builtin_ia32_pcmpistric128:
2356 case X86::BI__builtin_ia32_pcmpistrio128:
2357 case X86::BI__builtin_ia32_pcmpistris128:
2358 case X86::BI__builtin_ia32_pcmpistriz128:
2359 case X86::BI__builtin_ia32_pclmulqdq128:
2360 case X86::BI__builtin_ia32_vperm2f128_pd256:
2361 case X86::BI__builtin_ia32_vperm2f128_ps256:
2362 case X86::BI__builtin_ia32_vperm2f128_si256:
2363 case X86::BI__builtin_ia32_permti256:
2364 i = 2; l = -128; u = 255;
2365 break;
2366 case X86::BI__builtin_ia32_palignr128:
2367 case X86::BI__builtin_ia32_palignr256:
Craig Topper39c87102016-05-18 03:18:12 +00002368 case X86::BI__builtin_ia32_palignr512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002369 case X86::BI__builtin_ia32_vcomisd:
2370 case X86::BI__builtin_ia32_vcomiss:
2371 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2372 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2373 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2374 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002375 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2376 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2377 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2378 i = 2; l = 0; u = 255;
2379 break;
2380 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2381 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2382 case X86::BI__builtin_ia32_fixupimmps512_mask:
2383 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2384 case X86::BI__builtin_ia32_fixupimmsd_mask:
2385 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2386 case X86::BI__builtin_ia32_fixupimmss_mask:
2387 case X86::BI__builtin_ia32_fixupimmss_maskz:
2388 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2389 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2390 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2391 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2392 case X86::BI__builtin_ia32_fixupimmps128_mask:
2393 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2394 case X86::BI__builtin_ia32_fixupimmps256_mask:
2395 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2396 case X86::BI__builtin_ia32_pternlogd512_mask:
2397 case X86::BI__builtin_ia32_pternlogd512_maskz:
2398 case X86::BI__builtin_ia32_pternlogq512_mask:
2399 case X86::BI__builtin_ia32_pternlogq512_maskz:
2400 case X86::BI__builtin_ia32_pternlogd128_mask:
2401 case X86::BI__builtin_ia32_pternlogd128_maskz:
2402 case X86::BI__builtin_ia32_pternlogd256_mask:
2403 case X86::BI__builtin_ia32_pternlogd256_maskz:
2404 case X86::BI__builtin_ia32_pternlogq128_mask:
2405 case X86::BI__builtin_ia32_pternlogq128_maskz:
2406 case X86::BI__builtin_ia32_pternlogq256_mask:
2407 case X86::BI__builtin_ia32_pternlogq256_maskz:
2408 i = 3; l = 0; u = 255;
2409 break;
Craig Topper9625db02017-03-12 22:19:10 +00002410 case X86::BI__builtin_ia32_gatherpfdpd:
2411 case X86::BI__builtin_ia32_gatherpfdps:
2412 case X86::BI__builtin_ia32_gatherpfqpd:
2413 case X86::BI__builtin_ia32_gatherpfqps:
2414 case X86::BI__builtin_ia32_scatterpfdpd:
2415 case X86::BI__builtin_ia32_scatterpfdps:
2416 case X86::BI__builtin_ia32_scatterpfqpd:
2417 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00002418 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00002419 break;
Craig Topper39c87102016-05-18 03:18:12 +00002420 case X86::BI__builtin_ia32_pcmpestrm128:
2421 case X86::BI__builtin_ia32_pcmpestri128:
2422 case X86::BI__builtin_ia32_pcmpestria128:
2423 case X86::BI__builtin_ia32_pcmpestric128:
2424 case X86::BI__builtin_ia32_pcmpestrio128:
2425 case X86::BI__builtin_ia32_pcmpestris128:
2426 case X86::BI__builtin_ia32_pcmpestriz128:
2427 i = 4; l = -128; u = 255;
2428 break;
2429 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2430 case X86::BI__builtin_ia32_rndscaless_round_mask:
2431 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002432 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002433 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002434 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002435}
2436
Richard Smith55ce3522012-06-25 20:30:08 +00002437/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2438/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2439/// Returns true when the format fits the function and the FormatStringInfo has
2440/// been populated.
2441bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2442 FormatStringInfo *FSI) {
2443 FSI->HasVAListArg = Format->getFirstArg() == 0;
2444 FSI->FormatIdx = Format->getFormatIdx() - 1;
2445 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002446
Richard Smith55ce3522012-06-25 20:30:08 +00002447 // The way the format attribute works in GCC, the implicit this argument
2448 // of member functions is counted. However, it doesn't appear in our own
2449 // lists, so decrement format_idx in that case.
2450 if (IsCXXMember) {
2451 if(FSI->FormatIdx == 0)
2452 return false;
2453 --FSI->FormatIdx;
2454 if (FSI->FirstDataArg != 0)
2455 --FSI->FirstDataArg;
2456 }
2457 return true;
2458}
Mike Stump11289f42009-09-09 15:08:12 +00002459
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002460/// Checks if a the given expression evaluates to null.
2461///
2462/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002463static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002464 // If the expression has non-null type, it doesn't evaluate to null.
2465 if (auto nullability
2466 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2467 if (*nullability == NullabilityKind::NonNull)
2468 return false;
2469 }
2470
Ted Kremeneka146db32014-01-17 06:24:47 +00002471 // As a special case, transparent unions initialized with zero are
2472 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002473 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002474 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2475 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002476 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002477 if (const InitListExpr *ILE =
2478 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002479 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002480 }
2481
2482 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002483 return (!Expr->isValueDependent() &&
2484 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2485 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002486}
2487
2488static void CheckNonNullArgument(Sema &S,
2489 const Expr *ArgExpr,
2490 SourceLocation CallSiteLoc) {
2491 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002492 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2493 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002494}
2495
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002496bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2497 FormatStringInfo FSI;
2498 if ((GetFormatStringType(Format) == FST_NSString) &&
2499 getFormatStringInfo(Format, false, &FSI)) {
2500 Idx = FSI.FormatIdx;
2501 return true;
2502 }
2503 return false;
2504}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002505/// \brief Diagnose use of %s directive in an NSString which is being passed
2506/// as formatting string to formatting method.
2507static void
2508DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2509 const NamedDecl *FDecl,
2510 Expr **Args,
2511 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002512 unsigned Idx = 0;
2513 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002514 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2515 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002516 Idx = 2;
2517 Format = true;
2518 }
2519 else
2520 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2521 if (S.GetFormatNSStringIdx(I, Idx)) {
2522 Format = true;
2523 break;
2524 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002525 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002526 if (!Format || NumArgs <= Idx)
2527 return;
2528 const Expr *FormatExpr = Args[Idx];
2529 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2530 FormatExpr = CSCE->getSubExpr();
2531 const StringLiteral *FormatString;
2532 if (const ObjCStringLiteral *OSL =
2533 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2534 FormatString = OSL->getString();
2535 else
2536 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2537 if (!FormatString)
2538 return;
2539 if (S.FormatStringHasSArg(FormatString)) {
2540 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2541 << "%s" << 1 << 1;
2542 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2543 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002544 }
2545}
2546
Douglas Gregorb4866e82015-06-19 18:13:19 +00002547/// Determine whether the given type has a non-null nullability annotation.
2548static bool isNonNullType(ASTContext &ctx, QualType type) {
2549 if (auto nullability = type->getNullability(ctx))
2550 return *nullability == NullabilityKind::NonNull;
2551
2552 return false;
2553}
2554
Ted Kremenek2bc73332014-01-17 06:24:43 +00002555static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002556 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002557 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002558 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002559 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002560 assert((FDecl || Proto) && "Need a function declaration or prototype");
2561
Ted Kremenek9aedc152014-01-17 06:24:56 +00002562 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002563 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002564 if (FDecl) {
2565 // Handle the nonnull attribute on the function/method declaration itself.
2566 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2567 if (!NonNull->args_size()) {
2568 // Easy case: all pointer arguments are nonnull.
2569 for (const auto *Arg : Args)
2570 if (S.isValidPointerAttrType(Arg->getType()))
2571 CheckNonNullArgument(S, Arg, CallSiteLoc);
2572 return;
2573 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002574
Douglas Gregorb4866e82015-06-19 18:13:19 +00002575 for (unsigned Val : NonNull->args()) {
2576 if (Val >= Args.size())
2577 continue;
2578 if (NonNullArgs.empty())
2579 NonNullArgs.resize(Args.size());
2580 NonNullArgs.set(Val);
2581 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002582 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002583 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002584
Douglas Gregorb4866e82015-06-19 18:13:19 +00002585 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2586 // Handle the nonnull attribute on the parameters of the
2587 // function/method.
2588 ArrayRef<ParmVarDecl*> parms;
2589 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2590 parms = FD->parameters();
2591 else
2592 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2593
2594 unsigned ParamIndex = 0;
2595 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2596 I != E; ++I, ++ParamIndex) {
2597 const ParmVarDecl *PVD = *I;
2598 if (PVD->hasAttr<NonNullAttr>() ||
2599 isNonNullType(S.Context, PVD->getType())) {
2600 if (NonNullArgs.empty())
2601 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002602
Douglas Gregorb4866e82015-06-19 18:13:19 +00002603 NonNullArgs.set(ParamIndex);
2604 }
2605 }
2606 } else {
2607 // If we have a non-function, non-method declaration but no
2608 // function prototype, try to dig out the function prototype.
2609 if (!Proto) {
2610 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2611 QualType type = VD->getType().getNonReferenceType();
2612 if (auto pointerType = type->getAs<PointerType>())
2613 type = pointerType->getPointeeType();
2614 else if (auto blockType = type->getAs<BlockPointerType>())
2615 type = blockType->getPointeeType();
2616 // FIXME: data member pointers?
2617
2618 // Dig out the function prototype, if there is one.
2619 Proto = type->getAs<FunctionProtoType>();
2620 }
2621 }
2622
2623 // Fill in non-null argument information from the nullability
2624 // information on the parameter types (if we have them).
2625 if (Proto) {
2626 unsigned Index = 0;
2627 for (auto paramType : Proto->getParamTypes()) {
2628 if (isNonNullType(S.Context, paramType)) {
2629 if (NonNullArgs.empty())
2630 NonNullArgs.resize(Args.size());
2631
2632 NonNullArgs.set(Index);
2633 }
2634
2635 ++Index;
2636 }
2637 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002638 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002639
Douglas Gregorb4866e82015-06-19 18:13:19 +00002640 // Check for non-null arguments.
2641 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2642 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002643 if (NonNullArgs[ArgIndex])
2644 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002645 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002646}
2647
Richard Smith55ce3522012-06-25 20:30:08 +00002648/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00002649/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2650/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002651void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00002652 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2653 bool IsMemberFunction, SourceLocation Loc,
2654 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002655 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002656 if (CurContext->isDependentContext())
2657 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002658
Ted Kremenekb8176da2010-09-09 04:33:05 +00002659 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002660 llvm::SmallBitVector CheckedVarArgs;
2661 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002662 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002663 // Only create vector if there are format attributes.
2664 CheckedVarArgs.resize(Args.size());
2665
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002666 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002667 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002668 }
Richard Smithd7293d72013-08-05 18:49:43 +00002669 }
Richard Smith55ce3522012-06-25 20:30:08 +00002670
2671 // Refuse POD arguments that weren't caught by the format string
2672 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00002673 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2674 if (CallType != VariadicDoesNotApply &&
2675 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002676 unsigned NumParams = Proto ? Proto->getNumParams()
2677 : FDecl && isa<FunctionDecl>(FDecl)
2678 ? cast<FunctionDecl>(FDecl)->getNumParams()
2679 : FDecl && isa<ObjCMethodDecl>(FDecl)
2680 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2681 : 0;
2682
Alp Toker9cacbab2014-01-20 20:26:09 +00002683 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002684 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002685 if (const Expr *Arg = Args[ArgIdx]) {
2686 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2687 checkVariadicArgument(Arg, CallType);
2688 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002689 }
Richard Smithd7293d72013-08-05 18:49:43 +00002690 }
Mike Stump11289f42009-09-09 15:08:12 +00002691
Douglas Gregorb4866e82015-06-19 18:13:19 +00002692 if (FDecl || Proto) {
2693 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002694
Richard Trieu41bc0992013-06-22 00:20:41 +00002695 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002696 if (FDecl) {
2697 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2698 CheckArgumentWithTypeTag(I, Args.data());
2699 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002700 }
George Burgess IVce6284b2017-01-28 02:19:40 +00002701
2702 if (FD)
2703 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00002704}
2705
2706/// CheckConstructorCall - Check a constructor call for correctness and safety
2707/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002708void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2709 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002710 const FunctionProtoType *Proto,
2711 SourceLocation Loc) {
2712 VariadicCallType CallType =
2713 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00002714 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2715 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002716}
2717
2718/// CheckFunctionCall - Check a direct function call for various correctness
2719/// and safety properties not strictly enforced by the C type system.
2720bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2721 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002722 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2723 isa<CXXMethodDecl>(FDecl);
2724 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2725 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002726 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2727 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002728 Expr** Args = TheCall->getArgs();
2729 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00002730
2731 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00002732 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002733 // If this is a call to a member operator, hide the first argument
2734 // from checkCall.
2735 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00002736 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00002737 ++Args;
2738 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00002739 } else if (IsMemberFunction)
2740 ImplicitThis =
2741 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2742
2743 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002744 IsMemberFunction, TheCall->getRParenLoc(),
2745 TheCall->getCallee()->getSourceRange(), CallType);
2746
2747 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2748 // None of the checks below are needed for functions that don't have
2749 // simple names (e.g., C++ conversion functions).
2750 if (!FnInfo)
2751 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002752
Richard Trieua7f30b12016-12-06 01:42:28 +00002753 CheckAbsoluteValueFunction(TheCall, FDecl);
2754 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00002755
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002756 if (getLangOpts().ObjC1)
2757 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002758
Anna Zaks22122702012-01-17 00:37:07 +00002759 unsigned CMId = FDecl->getMemoryFunctionKind();
2760 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002761 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002762
Anna Zaks201d4892012-01-13 21:52:01 +00002763 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002764 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002765 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002766 else if (CMId == Builtin::BIstrncat)
2767 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002768 else
Anna Zaks22122702012-01-17 00:37:07 +00002769 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002770
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002771 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002772}
2773
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002774bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002775 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002776 VariadicCallType CallType =
2777 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002778
George Burgess IVce6284b2017-01-28 02:19:40 +00002779 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2780 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002781 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002782
2783 return false;
2784}
2785
Richard Trieu664c4c62013-06-20 21:03:13 +00002786bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2787 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002788 QualType Ty;
2789 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002790 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002791 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002792 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002793 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002794 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002795
Douglas Gregorb4866e82015-06-19 18:13:19 +00002796 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2797 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002798 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002799
Richard Trieu664c4c62013-06-20 21:03:13 +00002800 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002801 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002802 CallType = VariadicDoesNotApply;
2803 } else if (Ty->isBlockPointerType()) {
2804 CallType = VariadicBlock;
2805 } else { // Ty->isFunctionPointerType()
2806 CallType = VariadicFunction;
2807 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002808
George Burgess IVce6284b2017-01-28 02:19:40 +00002809 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002810 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2811 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002812 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002813
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002814 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002815}
2816
Richard Trieu41bc0992013-06-22 00:20:41 +00002817/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2818/// such as function pointers returned from functions.
2819bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002820 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002821 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00002822 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002823 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002824 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002825 TheCall->getCallee()->getSourceRange(), CallType);
2826
2827 return false;
2828}
2829
Tim Northovere94a34c2014-03-11 10:49:14 +00002830static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002831 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002832 return false;
2833
JF Bastiendda2cb12016-04-18 18:01:49 +00002834 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002835 switch (Op) {
2836 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00002837 case AtomicExpr::AO__opencl_atomic_init:
Tim Northovere94a34c2014-03-11 10:49:14 +00002838 llvm_unreachable("There is no ordering argument for an init");
2839
2840 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00002841 case AtomicExpr::AO__opencl_atomic_load:
Tim Northovere94a34c2014-03-11 10:49:14 +00002842 case AtomicExpr::AO__atomic_load_n:
2843 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002844 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2845 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002846
2847 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00002848 case AtomicExpr::AO__opencl_atomic_store:
Tim Northovere94a34c2014-03-11 10:49:14 +00002849 case AtomicExpr::AO__atomic_store:
2850 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002851 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2852 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2853 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002854
2855 default:
2856 return true;
2857 }
2858}
2859
Richard Smithfeea8832012-04-12 05:08:17 +00002860ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2861 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002862 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2863 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002864
Yaxun Liu39195062017-08-04 18:16:31 +00002865 // All the non-OpenCL operations take one of the following forms.
2866 // The OpenCL operations take the __c11 forms with one extra argument for
2867 // synchronization scope.
Richard Smithfeea8832012-04-12 05:08:17 +00002868 enum {
2869 // C __c11_atomic_init(A *, C)
2870 Init,
2871 // C __c11_atomic_load(A *, int)
2872 Load,
2873 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002874 LoadCopy,
2875 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002876 Copy,
2877 // C __c11_atomic_add(A *, M, int)
2878 Arithmetic,
2879 // C __atomic_exchange_n(A *, CP, int)
2880 Xchg,
2881 // void __atomic_exchange(A *, C *, CP, int)
2882 GNUXchg,
2883 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2884 C11CmpXchg,
2885 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2886 GNUCmpXchg
2887 } Form = Init;
Yaxun Liu39195062017-08-04 18:16:31 +00002888 const unsigned NumForm = GNUCmpXchg + 1;
Eric Fiselier8d662442016-03-30 23:39:56 +00002889 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2890 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002891 // where:
2892 // C is an appropriate type,
2893 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2894 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2895 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2896 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002897
Yaxun Liu39195062017-08-04 18:16:31 +00002898 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
2899 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
2900 "need to update code for modified forms");
Gabor Horvath98bd0982015-03-16 09:59:54 +00002901 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2902 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2903 AtomicExpr::AO__atomic_load,
2904 "need to update code for modified C11 atomics");
Yaxun Liu39195062017-08-04 18:16:31 +00002905 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
2906 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
2907 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
2908 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
2909 IsOpenCL;
Richard Smithfeea8832012-04-12 05:08:17 +00002910 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2911 Op == AtomicExpr::AO__atomic_store_n ||
2912 Op == AtomicExpr::AO__atomic_exchange_n ||
2913 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2914 bool IsAddSub = false;
2915
2916 switch (Op) {
2917 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00002918 case AtomicExpr::AO__opencl_atomic_init:
Richard Smithfeea8832012-04-12 05:08:17 +00002919 Form = Init;
2920 break;
2921
2922 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00002923 case AtomicExpr::AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00002924 case AtomicExpr::AO__atomic_load_n:
2925 Form = Load;
2926 break;
2927
Richard Smithfeea8832012-04-12 05:08:17 +00002928 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002929 Form = LoadCopy;
2930 break;
2931
2932 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00002933 case AtomicExpr::AO__opencl_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002934 case AtomicExpr::AO__atomic_store:
2935 case AtomicExpr::AO__atomic_store_n:
2936 Form = Copy;
2937 break;
2938
2939 case AtomicExpr::AO__c11_atomic_fetch_add:
2940 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00002941 case AtomicExpr::AO__opencl_atomic_fetch_add:
2942 case AtomicExpr::AO__opencl_atomic_fetch_sub:
2943 case AtomicExpr::AO__opencl_atomic_fetch_min:
2944 case AtomicExpr::AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00002945 case AtomicExpr::AO__atomic_fetch_add:
2946 case AtomicExpr::AO__atomic_fetch_sub:
2947 case AtomicExpr::AO__atomic_add_fetch:
2948 case AtomicExpr::AO__atomic_sub_fetch:
2949 IsAddSub = true;
2950 // Fall through.
2951 case AtomicExpr::AO__c11_atomic_fetch_and:
2952 case AtomicExpr::AO__c11_atomic_fetch_or:
2953 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00002954 case AtomicExpr::AO__opencl_atomic_fetch_and:
2955 case AtomicExpr::AO__opencl_atomic_fetch_or:
2956 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Richard Smithfeea8832012-04-12 05:08:17 +00002957 case AtomicExpr::AO__atomic_fetch_and:
2958 case AtomicExpr::AO__atomic_fetch_or:
2959 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00002960 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00002961 case AtomicExpr::AO__atomic_and_fetch:
2962 case AtomicExpr::AO__atomic_or_fetch:
2963 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00002964 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00002965 Form = Arithmetic;
2966 break;
2967
2968 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00002969 case AtomicExpr::AO__opencl_atomic_exchange:
Richard Smithfeea8832012-04-12 05:08:17 +00002970 case AtomicExpr::AO__atomic_exchange_n:
2971 Form = Xchg;
2972 break;
2973
2974 case AtomicExpr::AO__atomic_exchange:
2975 Form = GNUXchg;
2976 break;
2977
2978 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2979 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +00002980 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
2981 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00002982 Form = C11CmpXchg;
2983 break;
2984
2985 case AtomicExpr::AO__atomic_compare_exchange:
2986 case AtomicExpr::AO__atomic_compare_exchange_n:
2987 Form = GNUCmpXchg;
2988 break;
2989 }
2990
Yaxun Liu39195062017-08-04 18:16:31 +00002991 unsigned AdjustedNumArgs = NumArgs[Form];
2992 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
2993 ++AdjustedNumArgs;
Richard Smithfeea8832012-04-12 05:08:17 +00002994 // Check we have the right number of arguments.
Yaxun Liu39195062017-08-04 18:16:31 +00002995 if (TheCall->getNumArgs() < AdjustedNumArgs) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002996 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Yaxun Liu39195062017-08-04 18:16:31 +00002997 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002998 << TheCall->getCallee()->getSourceRange();
2999 return ExprError();
Yaxun Liu39195062017-08-04 18:16:31 +00003000 } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3001 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003002 diag::err_typecheck_call_too_many_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003003 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003004 << TheCall->getCallee()->getSourceRange();
3005 return ExprError();
3006 }
3007
Richard Smithfeea8832012-04-12 05:08:17 +00003008 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003009 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00003010 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3011 if (ConvertedPtr.isInvalid())
3012 return ExprError();
3013
3014 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003015 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3016 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00003017 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003018 << Ptr->getType() << Ptr->getSourceRange();
3019 return ExprError();
3020 }
3021
Richard Smithfeea8832012-04-12 05:08:17 +00003022 // For a __c11 builtin, this should be a pointer to an _Atomic type.
3023 QualType AtomTy = pointerType->getPointeeType(); // 'A'
3024 QualType ValType = AtomTy; // 'C'
3025 if (IsC11) {
3026 if (!AtomTy->isAtomicType()) {
3027 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3028 << Ptr->getType() << Ptr->getSourceRange();
3029 return ExprError();
3030 }
Yaxun Liu39195062017-08-04 18:16:31 +00003031 if (AtomTy.isConstQualified() ||
3032 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
Richard Smithe00921a2012-09-15 06:09:58 +00003033 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
Yaxun Liu39195062017-08-04 18:16:31 +00003034 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3035 << Ptr->getSourceRange();
Richard Smithe00921a2012-09-15 06:09:58 +00003036 return ExprError();
3037 }
Richard Smithfeea8832012-04-12 05:08:17 +00003038 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00003039 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00003040 if (ValType.isConstQualified()) {
3041 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3042 << Ptr->getType() << Ptr->getSourceRange();
3043 return ExprError();
3044 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003045 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003046
Richard Smithfeea8832012-04-12 05:08:17 +00003047 // For an arithmetic operation, the implied arithmetic must be well-formed.
3048 if (Form == Arithmetic) {
3049 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
3050 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
3051 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3052 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3053 return ExprError();
3054 }
3055 if (!IsAddSub && !ValType->isIntegerType()) {
3056 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3057 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3058 return ExprError();
3059 }
David Majnemere85cff82015-01-28 05:48:06 +00003060 if (IsC11 && ValType->isPointerType() &&
3061 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3062 diag::err_incomplete_type)) {
3063 return ExprError();
3064 }
Richard Smithfeea8832012-04-12 05:08:17 +00003065 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3066 // For __atomic_*_n operations, the value type must be a scalar integral or
3067 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003068 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00003069 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3070 return ExprError();
3071 }
3072
Eli Friedmanaa769812013-09-11 03:49:34 +00003073 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3074 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003075 // For GNU atomics, require a trivially-copyable type. This is not part of
3076 // the GNU atomics specification, but we enforce it for sanity.
3077 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003078 << Ptr->getType() << Ptr->getSourceRange();
3079 return ExprError();
3080 }
3081
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003082 switch (ValType.getObjCLifetime()) {
3083 case Qualifiers::OCL_None:
3084 case Qualifiers::OCL_ExplicitNone:
3085 // okay
3086 break;
3087
3088 case Qualifiers::OCL_Weak:
3089 case Qualifiers::OCL_Strong:
3090 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00003091 // FIXME: Can this happen? By this point, ValType should be known
3092 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003093 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3094 << ValType << Ptr->getSourceRange();
3095 return ExprError();
3096 }
3097
David Majnemerc6eb6502015-06-03 00:26:35 +00003098 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
3099 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00003100 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00003101 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00003102 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003103 QualType ResultType = ValType;
Yaxun Liu39195062017-08-04 18:16:31 +00003104 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3105 Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003106 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00003107 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003108 ResultType = Context.BoolTy;
3109
Richard Smithfeea8832012-04-12 05:08:17 +00003110 // The type of a parameter passed 'by value'. In the GNU atomics, such
3111 // arguments are actually passed as pointers.
3112 QualType ByValType = ValType; // 'CP'
3113 if (!IsC11 && !IsN)
3114 ByValType = Ptr->getType();
3115
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003116 // The first argument --- the pointer --- has a fixed type; we
3117 // deduce the types of the rest of the arguments accordingly. Walk
3118 // the remaining arguments, converting them to the deduced value type.
Yaxun Liu39195062017-08-04 18:16:31 +00003119 for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003120 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00003121 if (i < NumVals[Form] + 1) {
3122 switch (i) {
3123 case 1:
3124 // The second argument is the non-atomic operand. For arithmetic, this
3125 // is always passed by value, and for a compare_exchange it is always
3126 // passed by address. For the rest, GNU uses by-address and C11 uses
3127 // by-value.
3128 assert(Form != Load);
3129 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3130 Ty = ValType;
3131 else if (Form == Copy || Form == Xchg)
3132 Ty = ByValType;
3133 else if (Form == Arithmetic)
3134 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003135 else {
3136 Expr *ValArg = TheCall->getArg(i);
Alex Lorenz67522152016-11-23 16:57:03 +00003137 // Treat this argument as _Nonnull as we want to show a warning if
3138 // NULL is passed into it.
3139 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003140 unsigned AS = 0;
3141 // Keep address space of non-atomic pointer type.
3142 if (const PointerType *PtrTy =
3143 ValArg->getType()->getAs<PointerType>()) {
3144 AS = PtrTy->getPointeeType().getAddressSpace();
3145 }
3146 Ty = Context.getPointerType(
3147 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3148 }
Richard Smithfeea8832012-04-12 05:08:17 +00003149 break;
3150 case 2:
3151 // The third argument to compare_exchange / GNU exchange is a
3152 // (pointer to a) desired value.
3153 Ty = ByValType;
3154 break;
3155 case 3:
3156 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3157 Ty = Context.BoolTy;
3158 break;
3159 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003160 } else {
Yaxun Liu39195062017-08-04 18:16:31 +00003161 // The order(s) and scope are always converted to int.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003162 Ty = Context.IntTy;
3163 }
Richard Smithfeea8832012-04-12 05:08:17 +00003164
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003165 InitializedEntity Entity =
3166 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00003167 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003168 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3169 if (Arg.isInvalid())
3170 return true;
3171 TheCall->setArg(i, Arg.get());
3172 }
3173
Richard Smithfeea8832012-04-12 05:08:17 +00003174 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003175 SmallVector<Expr*, 5> SubExprs;
3176 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00003177 switch (Form) {
3178 case Init:
3179 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00003180 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003181 break;
3182 case Load:
3183 SubExprs.push_back(TheCall->getArg(1)); // Order
3184 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00003185 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00003186 case Copy:
3187 case Arithmetic:
3188 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003189 SubExprs.push_back(TheCall->getArg(2)); // Order
3190 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003191 break;
3192 case GNUXchg:
3193 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3194 SubExprs.push_back(TheCall->getArg(3)); // Order
3195 SubExprs.push_back(TheCall->getArg(1)); // Val1
3196 SubExprs.push_back(TheCall->getArg(2)); // Val2
3197 break;
3198 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003199 SubExprs.push_back(TheCall->getArg(3)); // Order
3200 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003201 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00003202 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00003203 break;
3204 case GNUCmpXchg:
3205 SubExprs.push_back(TheCall->getArg(4)); // Order
3206 SubExprs.push_back(TheCall->getArg(1)); // Val1
3207 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3208 SubExprs.push_back(TheCall->getArg(2)); // Val2
3209 SubExprs.push_back(TheCall->getArg(3)); // Weak
3210 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003211 }
Tim Northovere94a34c2014-03-11 10:49:14 +00003212
3213 if (SubExprs.size() >= 2 && Form != Init) {
3214 llvm::APSInt Result(32);
3215 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3216 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00003217 Diag(SubExprs[1]->getLocStart(),
3218 diag::warn_atomic_op_has_invalid_memory_order)
3219 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00003220 }
3221
Yaxun Liu30d652a2017-08-15 16:02:49 +00003222 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3223 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3224 llvm::APSInt Result(32);
3225 if (Scope->isIntegerConstantExpr(Result, Context) &&
3226 !ScopeModel->isValid(Result.getZExtValue())) {
3227 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3228 << Scope->getSourceRange();
3229 }
3230 SubExprs.push_back(Scope);
3231 }
3232
Fariborz Jahanian615de762013-05-28 17:37:39 +00003233 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3234 SubExprs, ResultType, Op,
3235 TheCall->getRParenLoc());
3236
3237 if ((Op == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00003238 Op == AtomicExpr::AO__c11_atomic_store ||
3239 Op == AtomicExpr::AO__opencl_atomic_load ||
3240 Op == AtomicExpr::AO__opencl_atomic_store ) &&
Fariborz Jahanian615de762013-05-28 17:37:39 +00003241 Context.AtomicUsesUnsupportedLibcall(AE))
Yaxun Liu39195062017-08-04 18:16:31 +00003242 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3243 << ((Op == AtomicExpr::AO__c11_atomic_load ||
3244 Op == AtomicExpr::AO__opencl_atomic_load)
3245 ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003246
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003247 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003248}
3249
John McCall29ad95b2011-08-27 01:09:30 +00003250/// checkBuiltinArgument - Given a call to a builtin function, perform
3251/// normal type-checking on the given argument, updating the call in
3252/// place. This is useful when a builtin function requires custom
3253/// type-checking for some of its arguments but not necessarily all of
3254/// them.
3255///
3256/// Returns true on error.
3257static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3258 FunctionDecl *Fn = E->getDirectCallee();
3259 assert(Fn && "builtin call without direct callee!");
3260
3261 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3262 InitializedEntity Entity =
3263 InitializedEntity::InitializeParameter(S.Context, Param);
3264
3265 ExprResult Arg = E->getArg(0);
3266 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3267 if (Arg.isInvalid())
3268 return true;
3269
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003270 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003271 return false;
3272}
3273
Chris Lattnerdc046542009-05-08 06:58:22 +00003274/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3275/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3276/// type of its first argument. The main ActOnCallExpr routines have already
3277/// promoted the types of arguments because all of these calls are prototyped as
3278/// void(...).
3279///
3280/// This function goes through and does final semantic checking for these
3281/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003282ExprResult
3283Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003284 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003285 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3286 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3287
3288 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003289 if (TheCall->getNumArgs() < 1) {
3290 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3291 << 0 << 1 << TheCall->getNumArgs()
3292 << TheCall->getCallee()->getSourceRange();
3293 return ExprError();
3294 }
Mike Stump11289f42009-09-09 15:08:12 +00003295
Chris Lattnerdc046542009-05-08 06:58:22 +00003296 // Inspect the first argument of the atomic builtin. This should always be
3297 // a pointer type, whose element is an integral scalar or pointer type.
3298 // Because it is a pointer type, we don't have to worry about any implicit
3299 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003300 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003301 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003302 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3303 if (FirstArgResult.isInvalid())
3304 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003305 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003306 TheCall->setArg(0, FirstArg);
3307
John McCall31168b02011-06-15 23:02:42 +00003308 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3309 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003310 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3311 << FirstArg->getType() << FirstArg->getSourceRange();
3312 return ExprError();
3313 }
Mike Stump11289f42009-09-09 15:08:12 +00003314
John McCall31168b02011-06-15 23:02:42 +00003315 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003316 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003317 !ValType->isBlockPointerType()) {
3318 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3319 << FirstArg->getType() << FirstArg->getSourceRange();
3320 return ExprError();
3321 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003322
John McCall31168b02011-06-15 23:02:42 +00003323 switch (ValType.getObjCLifetime()) {
3324 case Qualifiers::OCL_None:
3325 case Qualifiers::OCL_ExplicitNone:
3326 // okay
3327 break;
3328
3329 case Qualifiers::OCL_Weak:
3330 case Qualifiers::OCL_Strong:
3331 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003332 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003333 << ValType << FirstArg->getSourceRange();
3334 return ExprError();
3335 }
3336
John McCallb50451a2011-10-05 07:41:44 +00003337 // Strip any qualifiers off ValType.
3338 ValType = ValType.getUnqualifiedType();
3339
Chandler Carruth3973af72010-07-18 20:54:12 +00003340 // The majority of builtins return a value, but a few have special return
3341 // types, so allow them to override appropriately below.
3342 QualType ResultType = ValType;
3343
Chris Lattnerdc046542009-05-08 06:58:22 +00003344 // We need to figure out which concrete builtin this maps onto. For example,
3345 // __sync_fetch_and_add with a 2 byte object turns into
3346 // __sync_fetch_and_add_2.
3347#define BUILTIN_ROW(x) \
3348 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3349 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003350
Chris Lattnerdc046542009-05-08 06:58:22 +00003351 static const unsigned BuiltinIndices[][5] = {
3352 BUILTIN_ROW(__sync_fetch_and_add),
3353 BUILTIN_ROW(__sync_fetch_and_sub),
3354 BUILTIN_ROW(__sync_fetch_and_or),
3355 BUILTIN_ROW(__sync_fetch_and_and),
3356 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003357 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003358
Chris Lattnerdc046542009-05-08 06:58:22 +00003359 BUILTIN_ROW(__sync_add_and_fetch),
3360 BUILTIN_ROW(__sync_sub_and_fetch),
3361 BUILTIN_ROW(__sync_and_and_fetch),
3362 BUILTIN_ROW(__sync_or_and_fetch),
3363 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003364 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003365
Chris Lattnerdc046542009-05-08 06:58:22 +00003366 BUILTIN_ROW(__sync_val_compare_and_swap),
3367 BUILTIN_ROW(__sync_bool_compare_and_swap),
3368 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003369 BUILTIN_ROW(__sync_lock_release),
3370 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003371 };
Mike Stump11289f42009-09-09 15:08:12 +00003372#undef BUILTIN_ROW
3373
Chris Lattnerdc046542009-05-08 06:58:22 +00003374 // Determine the index of the size.
3375 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003376 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003377 case 1: SizeIndex = 0; break;
3378 case 2: SizeIndex = 1; break;
3379 case 4: SizeIndex = 2; break;
3380 case 8: SizeIndex = 3; break;
3381 case 16: SizeIndex = 4; break;
3382 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003383 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3384 << FirstArg->getType() << FirstArg->getSourceRange();
3385 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003386 }
Mike Stump11289f42009-09-09 15:08:12 +00003387
Chris Lattnerdc046542009-05-08 06:58:22 +00003388 // Each of these builtins has one pointer argument, followed by some number of
3389 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3390 // that we ignore. Find out which row of BuiltinIndices to read from as well
3391 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003392 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003393 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003394 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003395 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003396 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003397 case Builtin::BI__sync_fetch_and_add:
3398 case Builtin::BI__sync_fetch_and_add_1:
3399 case Builtin::BI__sync_fetch_and_add_2:
3400 case Builtin::BI__sync_fetch_and_add_4:
3401 case Builtin::BI__sync_fetch_and_add_8:
3402 case Builtin::BI__sync_fetch_and_add_16:
3403 BuiltinIndex = 0;
3404 break;
3405
3406 case Builtin::BI__sync_fetch_and_sub:
3407 case Builtin::BI__sync_fetch_and_sub_1:
3408 case Builtin::BI__sync_fetch_and_sub_2:
3409 case Builtin::BI__sync_fetch_and_sub_4:
3410 case Builtin::BI__sync_fetch_and_sub_8:
3411 case Builtin::BI__sync_fetch_and_sub_16:
3412 BuiltinIndex = 1;
3413 break;
3414
3415 case Builtin::BI__sync_fetch_and_or:
3416 case Builtin::BI__sync_fetch_and_or_1:
3417 case Builtin::BI__sync_fetch_and_or_2:
3418 case Builtin::BI__sync_fetch_and_or_4:
3419 case Builtin::BI__sync_fetch_and_or_8:
3420 case Builtin::BI__sync_fetch_and_or_16:
3421 BuiltinIndex = 2;
3422 break;
3423
3424 case Builtin::BI__sync_fetch_and_and:
3425 case Builtin::BI__sync_fetch_and_and_1:
3426 case Builtin::BI__sync_fetch_and_and_2:
3427 case Builtin::BI__sync_fetch_and_and_4:
3428 case Builtin::BI__sync_fetch_and_and_8:
3429 case Builtin::BI__sync_fetch_and_and_16:
3430 BuiltinIndex = 3;
3431 break;
Mike Stump11289f42009-09-09 15:08:12 +00003432
Douglas Gregor73722482011-11-28 16:30:08 +00003433 case Builtin::BI__sync_fetch_and_xor:
3434 case Builtin::BI__sync_fetch_and_xor_1:
3435 case Builtin::BI__sync_fetch_and_xor_2:
3436 case Builtin::BI__sync_fetch_and_xor_4:
3437 case Builtin::BI__sync_fetch_and_xor_8:
3438 case Builtin::BI__sync_fetch_and_xor_16:
3439 BuiltinIndex = 4;
3440 break;
3441
Hal Finkeld2208b52014-10-02 20:53:50 +00003442 case Builtin::BI__sync_fetch_and_nand:
3443 case Builtin::BI__sync_fetch_and_nand_1:
3444 case Builtin::BI__sync_fetch_and_nand_2:
3445 case Builtin::BI__sync_fetch_and_nand_4:
3446 case Builtin::BI__sync_fetch_and_nand_8:
3447 case Builtin::BI__sync_fetch_and_nand_16:
3448 BuiltinIndex = 5;
3449 WarnAboutSemanticsChange = true;
3450 break;
3451
Douglas Gregor73722482011-11-28 16:30:08 +00003452 case Builtin::BI__sync_add_and_fetch:
3453 case Builtin::BI__sync_add_and_fetch_1:
3454 case Builtin::BI__sync_add_and_fetch_2:
3455 case Builtin::BI__sync_add_and_fetch_4:
3456 case Builtin::BI__sync_add_and_fetch_8:
3457 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003458 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003459 break;
3460
3461 case Builtin::BI__sync_sub_and_fetch:
3462 case Builtin::BI__sync_sub_and_fetch_1:
3463 case Builtin::BI__sync_sub_and_fetch_2:
3464 case Builtin::BI__sync_sub_and_fetch_4:
3465 case Builtin::BI__sync_sub_and_fetch_8:
3466 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003467 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003468 break;
3469
3470 case Builtin::BI__sync_and_and_fetch:
3471 case Builtin::BI__sync_and_and_fetch_1:
3472 case Builtin::BI__sync_and_and_fetch_2:
3473 case Builtin::BI__sync_and_and_fetch_4:
3474 case Builtin::BI__sync_and_and_fetch_8:
3475 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003476 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003477 break;
3478
3479 case Builtin::BI__sync_or_and_fetch:
3480 case Builtin::BI__sync_or_and_fetch_1:
3481 case Builtin::BI__sync_or_and_fetch_2:
3482 case Builtin::BI__sync_or_and_fetch_4:
3483 case Builtin::BI__sync_or_and_fetch_8:
3484 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003485 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003486 break;
3487
3488 case Builtin::BI__sync_xor_and_fetch:
3489 case Builtin::BI__sync_xor_and_fetch_1:
3490 case Builtin::BI__sync_xor_and_fetch_2:
3491 case Builtin::BI__sync_xor_and_fetch_4:
3492 case Builtin::BI__sync_xor_and_fetch_8:
3493 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003494 BuiltinIndex = 10;
3495 break;
3496
3497 case Builtin::BI__sync_nand_and_fetch:
3498 case Builtin::BI__sync_nand_and_fetch_1:
3499 case Builtin::BI__sync_nand_and_fetch_2:
3500 case Builtin::BI__sync_nand_and_fetch_4:
3501 case Builtin::BI__sync_nand_and_fetch_8:
3502 case Builtin::BI__sync_nand_and_fetch_16:
3503 BuiltinIndex = 11;
3504 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003505 break;
Mike Stump11289f42009-09-09 15:08:12 +00003506
Chris Lattnerdc046542009-05-08 06:58:22 +00003507 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003508 case Builtin::BI__sync_val_compare_and_swap_1:
3509 case Builtin::BI__sync_val_compare_and_swap_2:
3510 case Builtin::BI__sync_val_compare_and_swap_4:
3511 case Builtin::BI__sync_val_compare_and_swap_8:
3512 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003513 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003514 NumFixed = 2;
3515 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003516
Chris Lattnerdc046542009-05-08 06:58:22 +00003517 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003518 case Builtin::BI__sync_bool_compare_and_swap_1:
3519 case Builtin::BI__sync_bool_compare_and_swap_2:
3520 case Builtin::BI__sync_bool_compare_and_swap_4:
3521 case Builtin::BI__sync_bool_compare_and_swap_8:
3522 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003523 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003524 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003525 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003526 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003527
3528 case Builtin::BI__sync_lock_test_and_set:
3529 case Builtin::BI__sync_lock_test_and_set_1:
3530 case Builtin::BI__sync_lock_test_and_set_2:
3531 case Builtin::BI__sync_lock_test_and_set_4:
3532 case Builtin::BI__sync_lock_test_and_set_8:
3533 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003534 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003535 break;
3536
Chris Lattnerdc046542009-05-08 06:58:22 +00003537 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003538 case Builtin::BI__sync_lock_release_1:
3539 case Builtin::BI__sync_lock_release_2:
3540 case Builtin::BI__sync_lock_release_4:
3541 case Builtin::BI__sync_lock_release_8:
3542 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003543 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003544 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003545 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003546 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003547
3548 case Builtin::BI__sync_swap:
3549 case Builtin::BI__sync_swap_1:
3550 case Builtin::BI__sync_swap_2:
3551 case Builtin::BI__sync_swap_4:
3552 case Builtin::BI__sync_swap_8:
3553 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003554 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003555 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003556 }
Mike Stump11289f42009-09-09 15:08:12 +00003557
Chris Lattnerdc046542009-05-08 06:58:22 +00003558 // Now that we know how many fixed arguments we expect, first check that we
3559 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003560 if (TheCall->getNumArgs() < 1+NumFixed) {
3561 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3562 << 0 << 1+NumFixed << TheCall->getNumArgs()
3563 << TheCall->getCallee()->getSourceRange();
3564 return ExprError();
3565 }
Mike Stump11289f42009-09-09 15:08:12 +00003566
Hal Finkeld2208b52014-10-02 20:53:50 +00003567 if (WarnAboutSemanticsChange) {
3568 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3569 << TheCall->getCallee()->getSourceRange();
3570 }
3571
Chris Lattner5b9241b2009-05-08 15:36:58 +00003572 // Get the decl for the concrete builtin from this, we can tell what the
3573 // concrete integer type we should convert to is.
3574 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003575 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003576 FunctionDecl *NewBuiltinDecl;
3577 if (NewBuiltinID == BuiltinID)
3578 NewBuiltinDecl = FDecl;
3579 else {
3580 // Perform builtin lookup to avoid redeclaring it.
3581 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3582 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3583 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3584 assert(Res.getFoundDecl());
3585 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003586 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003587 return ExprError();
3588 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003589
John McCallcf142162010-08-07 06:22:56 +00003590 // The first argument --- the pointer --- has a fixed type; we
3591 // deduce the types of the rest of the arguments accordingly. Walk
3592 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003593 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003594 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003595
Chris Lattnerdc046542009-05-08 06:58:22 +00003596 // GCC does an implicit conversion to the pointer or integer ValType. This
3597 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003598 // Initialize the argument.
3599 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3600 ValType, /*consume*/ false);
3601 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003602 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003603 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003604
Chris Lattnerdc046542009-05-08 06:58:22 +00003605 // Okay, we have something that *can* be converted to the right type. Check
3606 // to see if there is a potentially weird extension going on here. This can
3607 // happen when you do an atomic operation on something like an char* and
3608 // pass in 42. The 42 gets converted to char. This is even more strange
3609 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003610 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003611 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003612 }
Mike Stump11289f42009-09-09 15:08:12 +00003613
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003614 ASTContext& Context = this->getASTContext();
3615
3616 // Create a new DeclRefExpr to refer to the new decl.
3617 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3618 Context,
3619 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003620 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003621 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003622 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003623 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003624 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003625 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003626
Chris Lattnerdc046542009-05-08 06:58:22 +00003627 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003628 // FIXME: This loses syntactic information.
3629 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3630 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3631 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003632 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003633
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003634 // Change the result type of the call to match the original value type. This
3635 // is arbitrary, but the codegen for these builtins ins design to handle it
3636 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003637 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003638
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003639 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003640}
3641
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003642/// SemaBuiltinNontemporalOverloaded - We have a call to
3643/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3644/// overloaded function based on the pointer type of its last argument.
3645///
3646/// This function goes through and does final semantic checking for these
3647/// builtins.
3648ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3649 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3650 DeclRefExpr *DRE =
3651 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3652 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3653 unsigned BuiltinID = FDecl->getBuiltinID();
3654 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3655 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3656 "Unexpected nontemporal load/store builtin!");
3657 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3658 unsigned numArgs = isStore ? 2 : 1;
3659
3660 // Ensure that we have the proper number of arguments.
3661 if (checkArgCount(*this, TheCall, numArgs))
3662 return ExprError();
3663
3664 // Inspect the last argument of the nontemporal builtin. This should always
3665 // be a pointer type, from which we imply the type of the memory access.
3666 // Because it is a pointer type, we don't have to worry about any implicit
3667 // casts here.
3668 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3669 ExprResult PointerArgResult =
3670 DefaultFunctionArrayLvalueConversion(PointerArg);
3671
3672 if (PointerArgResult.isInvalid())
3673 return ExprError();
3674 PointerArg = PointerArgResult.get();
3675 TheCall->setArg(numArgs - 1, PointerArg);
3676
3677 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3678 if (!pointerType) {
3679 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3680 << PointerArg->getType() << PointerArg->getSourceRange();
3681 return ExprError();
3682 }
3683
3684 QualType ValType = pointerType->getPointeeType();
3685
3686 // Strip any qualifiers off ValType.
3687 ValType = ValType.getUnqualifiedType();
3688 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3689 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3690 !ValType->isVectorType()) {
3691 Diag(DRE->getLocStart(),
3692 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3693 << PointerArg->getType() << PointerArg->getSourceRange();
3694 return ExprError();
3695 }
3696
3697 if (!isStore) {
3698 TheCall->setType(ValType);
3699 return TheCallResult;
3700 }
3701
3702 ExprResult ValArg = TheCall->getArg(0);
3703 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3704 Context, ValType, /*consume*/ false);
3705 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3706 if (ValArg.isInvalid())
3707 return ExprError();
3708
3709 TheCall->setArg(0, ValArg.get());
3710 TheCall->setType(Context.VoidTy);
3711 return TheCallResult;
3712}
3713
Chris Lattner6436fb62009-02-18 06:01:06 +00003714/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003715/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003716/// Note: It might also make sense to do the UTF-16 conversion here (would
3717/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003718bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003719 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003720 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3721
Douglas Gregorfb65e592011-07-27 05:40:30 +00003722 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003723 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3724 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003725 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003726 }
Mike Stump11289f42009-09-09 15:08:12 +00003727
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003728 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003729 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003730 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00003731 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3732 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3733 llvm::UTF16 *ToPtr = &ToBuf[0];
3734
3735 llvm::ConversionResult Result =
3736 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3737 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003738 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00003739 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003740 Diag(Arg->getLocStart(),
3741 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3742 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003743 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003744}
3745
Mehdi Amini06d367c2016-10-24 20:39:34 +00003746/// CheckObjCString - Checks that the format string argument to the os_log()
3747/// and os_trace() functions is correct, and converts it to const char *.
3748ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3749 Arg = Arg->IgnoreParenCasts();
3750 auto *Literal = dyn_cast<StringLiteral>(Arg);
3751 if (!Literal) {
3752 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3753 Literal = ObjcLiteral->getString();
3754 }
3755 }
3756
3757 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3758 return ExprError(
3759 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3760 << Arg->getSourceRange());
3761 }
3762
3763 ExprResult Result(Literal);
3764 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3765 InitializedEntity Entity =
3766 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3767 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3768 return Result;
3769}
3770
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003771/// Check that the user is calling the appropriate va_start builtin for the
3772/// target and calling convention.
3773static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3774 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3775 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
Martin Storsjo022e7822017-07-17 20:49:45 +00003776 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003777 bool IsWindows = TT.isOSWindows();
Martin Storsjo022e7822017-07-17 20:49:45 +00003778 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
3779 if (IsX64 || IsAArch64) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003780 clang::CallingConv CC = CC_C;
3781 if (const FunctionDecl *FD = S.getCurFunctionDecl())
3782 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3783 if (IsMSVAStart) {
3784 // Don't allow this in System V ABI functions.
Martin Storsjo022e7822017-07-17 20:49:45 +00003785 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003786 return S.Diag(Fn->getLocStart(),
3787 diag::err_ms_va_start_used_in_sysv_function);
3788 } else {
Martin Storsjo022e7822017-07-17 20:49:45 +00003789 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003790 // On x64 Windows, don't allow this in System V ABI functions.
3791 // (Yes, that means there's no corresponding way to support variadic
3792 // System V ABI functions on Windows.)
3793 if ((IsWindows && CC == CC_X86_64SysV) ||
Martin Storsjo022e7822017-07-17 20:49:45 +00003794 (!IsWindows && CC == CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003795 return S.Diag(Fn->getLocStart(),
3796 diag::err_va_start_used_in_wrong_abi_function)
3797 << !IsWindows;
3798 }
3799 return false;
3800 }
3801
3802 if (IsMSVAStart)
Martin Storsjo022e7822017-07-17 20:49:45 +00003803 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003804 return false;
3805}
3806
3807static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3808 ParmVarDecl **LastParam = nullptr) {
3809 // Determine whether the current function, block, or obj-c method is variadic
3810 // and get its parameter list.
3811 bool IsVariadic = false;
3812 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00003813 DeclContext *Caller = S.CurContext;
3814 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3815 IsVariadic = Block->isVariadic();
3816 Params = Block->parameters();
3817 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003818 IsVariadic = FD->isVariadic();
3819 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003820 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003821 IsVariadic = MD->isVariadic();
3822 // FIXME: This isn't correct for methods (results in bogus warning).
3823 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003824 } else if (isa<CapturedDecl>(Caller)) {
3825 // We don't support va_start in a CapturedDecl.
3826 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3827 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003828 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003829 // This must be some other declcontext that parses exprs.
3830 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3831 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003832 }
3833
3834 if (!IsVariadic) {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003835 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003836 return true;
3837 }
3838
3839 if (LastParam)
3840 *LastParam = Params.empty() ? nullptr : Params.back();
3841
3842 return false;
3843}
3844
Charles Davisc7d5c942015-09-17 20:55:33 +00003845/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3846/// for validity. Emit an error and return true on failure; return false
3847/// on success.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003848bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003849 Expr *Fn = TheCall->getCallee();
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003850
3851 if (checkVAStartABI(*this, BuiltinID, Fn))
3852 return true;
3853
Chris Lattner08464942007-12-28 05:29:59 +00003854 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003855 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003856 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003857 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3858 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003859 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003860 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003861 return true;
3862 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003863
3864 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003865 return Diag(TheCall->getLocEnd(),
3866 diag::err_typecheck_call_too_few_args_at_least)
3867 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003868 }
3869
John McCall29ad95b2011-08-27 01:09:30 +00003870 // Type-check the first argument normally.
3871 if (checkBuiltinArgument(*this, TheCall, 0))
3872 return true;
3873
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003874 // Check that the current function is variadic, and get its last parameter.
3875 ParmVarDecl *LastParam;
3876 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
Chris Lattner43be2e62007-12-19 23:59:04 +00003877 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003878
Chris Lattner43be2e62007-12-19 23:59:04 +00003879 // Verify that the second argument to the builtin is the last argument of the
3880 // current function or method.
3881 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003882 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003883
Nico Weber9eea7642013-05-24 23:31:57 +00003884 // These are valid if SecondArgIsLastNamedArgument is false after the next
3885 // block.
3886 QualType Type;
3887 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003888 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003889
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003890 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3891 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003892 SecondArgIsLastNamedArgument = PV == LastParam;
Nico Weber9eea7642013-05-24 23:31:57 +00003893
3894 Type = PV->getType();
3895 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003896 IsCRegister =
3897 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003898 }
3899 }
Mike Stump11289f42009-09-09 15:08:12 +00003900
Chris Lattner43be2e62007-12-19 23:59:04 +00003901 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003902 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003903 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003904 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00003905 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3906 // Promotable integers are UB, but enumerations need a bit of
3907 // extra checking to see what their promotable type actually is.
3908 if (!Type->isPromotableIntegerType())
3909 return false;
3910 if (!Type->isEnumeralType())
3911 return true;
3912 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3913 return !(ED &&
3914 Context.typesAreCompatible(ED->getPromotionType(), Type));
3915 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00003916 unsigned Reason = 0;
3917 if (Type->isReferenceType()) Reason = 1;
3918 else if (IsCRegister) Reason = 2;
3919 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003920 Diag(ParamLoc, diag::note_parameter_type) << Type;
3921 }
3922
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003923 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003924 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003925}
Chris Lattner43be2e62007-12-19 23:59:04 +00003926
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003927bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3928 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3929 // const char *named_addr);
3930
3931 Expr *Func = Call->getCallee();
3932
3933 if (Call->getNumArgs() < 3)
3934 return Diag(Call->getLocEnd(),
3935 diag::err_typecheck_call_too_few_args_at_least)
3936 << 0 /*function call*/ << 3 << Call->getNumArgs();
3937
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003938 // Type-check the first argument normally.
3939 if (checkBuiltinArgument(*this, Call, 0))
3940 return true;
3941
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003942 // Check that the current function is variadic.
3943 if (checkVAStartIsInVariadicFunction(*this, Func))
3944 return true;
3945
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003946 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003947 unsigned ArgNo;
3948 QualType Type;
3949 } ArgumentTypes[] = {
3950 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3951 { 2, Context.getSizeType() },
3952 };
3953
3954 for (const auto &AT : ArgumentTypes) {
3955 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3956 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3957 continue;
3958 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3959 << Arg->getType() << AT.Type << 1 /* different class */
3960 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3961 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3962 }
3963
3964 return false;
3965}
3966
Chris Lattner2da14fb2007-12-20 00:26:33 +00003967/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3968/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003969bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3970 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003971 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003972 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003973 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003974 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003975 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003976 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003977 << SourceRange(TheCall->getArg(2)->getLocStart(),
3978 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003979
John Wiegley01296292011-04-08 18:41:53 +00003980 ExprResult OrigArg0 = TheCall->getArg(0);
3981 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003982
Chris Lattner2da14fb2007-12-20 00:26:33 +00003983 // Do standard promotions between the two arguments, returning their common
3984 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003985 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003986 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3987 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003988
3989 // Make sure any conversions are pushed back into the call; this is
3990 // type safe since unordered compare builtins are declared as "_Bool
3991 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003992 TheCall->setArg(0, OrigArg0.get());
3993 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003994
John Wiegley01296292011-04-08 18:41:53 +00003995 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003996 return false;
3997
Chris Lattner2da14fb2007-12-20 00:26:33 +00003998 // If the common type isn't a real floating type, then the arguments were
3999 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00004000 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00004001 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004002 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00004003 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4004 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004005
Chris Lattner2da14fb2007-12-20 00:26:33 +00004006 return false;
4007}
4008
Benjamin Kramer634fc102010-02-15 22:42:31 +00004009/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4010/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00004011/// to check everything. We expect the last argument to be a floating point
4012/// value.
4013bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4014 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00004015 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004016 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00004017 if (TheCall->getNumArgs() > NumArgs)
4018 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004019 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004020 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00004021 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004022 (*(TheCall->arg_end()-1))->getLocEnd());
4023
Benjamin Kramer64aae502010-02-16 10:07:31 +00004024 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00004025
Eli Friedman7e4faac2009-08-31 20:06:00 +00004026 if (OrigArg->isTypeDependent())
4027 return false;
4028
Chris Lattner68784ef2010-05-06 05:50:07 +00004029 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00004030 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00004031 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004032 diag::err_typecheck_call_invalid_unary_fp)
4033 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004034
Neil Hickey88c0fac2016-12-13 16:22:50 +00004035 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00004036 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00004037 // Only remove standard FloatCasts, leaving other casts inplace
4038 if (Cast->getCastKind() == CK_FloatingCast) {
4039 Expr *CastArg = Cast->getSubExpr();
4040 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4041 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4042 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4043 "promotion from float to either float or double is the only expected cast here");
4044 Cast->setSubExpr(nullptr);
4045 TheCall->setArg(NumArgs-1, CastArg);
4046 }
Chris Lattner68784ef2010-05-06 05:50:07 +00004047 }
4048 }
4049
Eli Friedman7e4faac2009-08-31 20:06:00 +00004050 return false;
4051}
4052
Tony Jiangbbc48e92017-05-24 15:13:32 +00004053// Customized Sema Checking for VSX builtins that have the following signature:
4054// vector [...] builtinName(vector [...], vector [...], const int);
4055// Which takes the same type of vectors (any legal vector type) for the first
4056// two arguments and takes compile time constant for the third argument.
4057// Example builtins are :
4058// vector double vec_xxpermdi(vector double, vector double, int);
4059// vector short vec_xxsldwi(vector short, vector short, int);
4060bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4061 unsigned ExpectedNumArgs = 3;
4062 if (TheCall->getNumArgs() < ExpectedNumArgs)
4063 return Diag(TheCall->getLocEnd(),
4064 diag::err_typecheck_call_too_few_args_at_least)
4065 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4066 << TheCall->getSourceRange();
4067
4068 if (TheCall->getNumArgs() > ExpectedNumArgs)
4069 return Diag(TheCall->getLocEnd(),
4070 diag::err_typecheck_call_too_many_args_at_most)
4071 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4072 << TheCall->getSourceRange();
4073
4074 // Check the third argument is a compile time constant
4075 llvm::APSInt Value;
4076 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4077 return Diag(TheCall->getLocStart(),
4078 diag::err_vsx_builtin_nonconstant_argument)
4079 << 3 /* argument index */ << TheCall->getDirectCallee()
4080 << SourceRange(TheCall->getArg(2)->getLocStart(),
4081 TheCall->getArg(2)->getLocEnd());
4082
4083 QualType Arg1Ty = TheCall->getArg(0)->getType();
4084 QualType Arg2Ty = TheCall->getArg(1)->getType();
4085
4086 // Check the type of argument 1 and argument 2 are vectors.
4087 SourceLocation BuiltinLoc = TheCall->getLocStart();
4088 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4089 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4090 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4091 << TheCall->getDirectCallee()
4092 << SourceRange(TheCall->getArg(0)->getLocStart(),
4093 TheCall->getArg(1)->getLocEnd());
4094 }
4095
4096 // Check the first two arguments are the same type.
4097 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4098 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4099 << TheCall->getDirectCallee()
4100 << SourceRange(TheCall->getArg(0)->getLocStart(),
4101 TheCall->getArg(1)->getLocEnd());
4102 }
4103
4104 // When default clang type checking is turned off and the customized type
4105 // checking is used, the returning type of the function must be explicitly
4106 // set. Otherwise it is _Bool by default.
4107 TheCall->setType(Arg1Ty);
4108
4109 return false;
4110}
4111
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004112/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4113// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00004114ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00004115 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004116 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00004117 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00004118 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4119 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004120
Nate Begemana0110022010-06-08 00:16:34 +00004121 // Determine which of the following types of shufflevector we're checking:
4122 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00004123 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00004124 QualType resType = TheCall->getArg(0)->getType();
4125 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00004126
Douglas Gregorc25f7662009-05-19 22:10:17 +00004127 if (!TheCall->getArg(0)->isTypeDependent() &&
4128 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00004129 QualType LHSType = TheCall->getArg(0)->getType();
4130 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00004131
Craig Topperbaca3892013-07-29 06:47:04 +00004132 if (!LHSType->isVectorType() || !RHSType->isVectorType())
4133 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004134 diag::err_vec_builtin_non_vector)
4135 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004136 << SourceRange(TheCall->getArg(0)->getLocStart(),
4137 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004138
Nate Begemana0110022010-06-08 00:16:34 +00004139 numElements = LHSType->getAs<VectorType>()->getNumElements();
4140 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00004141
Nate Begemana0110022010-06-08 00:16:34 +00004142 // Check to see if we have a call with 2 vector arguments, the unary shuffle
4143 // with mask. If so, verify that RHS is an integer vector type with the
4144 // same number of elts as lhs.
4145 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00004146 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00004147 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00004148 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004149 diag::err_vec_builtin_incompatible_vector)
4150 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004151 << SourceRange(TheCall->getArg(1)->getLocStart(),
4152 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004153 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00004154 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004155 diag::err_vec_builtin_incompatible_vector)
4156 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004157 << SourceRange(TheCall->getArg(0)->getLocStart(),
4158 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00004159 } else if (numElements != numResElements) {
4160 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00004161 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00004162 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004163 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004164 }
4165
4166 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00004167 if (TheCall->getArg(i)->isTypeDependent() ||
4168 TheCall->getArg(i)->isValueDependent())
4169 continue;
4170
Nate Begemana0110022010-06-08 00:16:34 +00004171 llvm::APSInt Result(32);
4172 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4173 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004174 diag::err_shufflevector_nonconstant_argument)
4175 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004176
Craig Topper50ad5b72013-08-03 17:40:38 +00004177 // Allow -1 which will be translated to undef in the IR.
4178 if (Result.isSigned() && Result.isAllOnesValue())
4179 continue;
4180
Chris Lattner7ab824e2008-08-10 02:05:13 +00004181 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004182 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004183 diag::err_shufflevector_argument_too_large)
4184 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004185 }
4186
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004187 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004188
Chris Lattner7ab824e2008-08-10 02:05:13 +00004189 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004190 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00004191 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004192 }
4193
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004194 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4195 TheCall->getCallee()->getLocStart(),
4196 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004197}
Chris Lattner43be2e62007-12-19 23:59:04 +00004198
Hal Finkelc4d7c822013-09-18 03:29:45 +00004199/// SemaConvertVectorExpr - Handle __builtin_convertvector
4200ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4201 SourceLocation BuiltinLoc,
4202 SourceLocation RParenLoc) {
4203 ExprValueKind VK = VK_RValue;
4204 ExprObjectKind OK = OK_Ordinary;
4205 QualType DstTy = TInfo->getType();
4206 QualType SrcTy = E->getType();
4207
4208 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4209 return ExprError(Diag(BuiltinLoc,
4210 diag::err_convertvector_non_vector)
4211 << E->getSourceRange());
4212 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4213 return ExprError(Diag(BuiltinLoc,
4214 diag::err_convertvector_non_vector_type));
4215
4216 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4217 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4218 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4219 if (SrcElts != DstElts)
4220 return ExprError(Diag(BuiltinLoc,
4221 diag::err_convertvector_incompatible_vector)
4222 << E->getSourceRange());
4223 }
4224
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004225 return new (Context)
4226 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00004227}
4228
Daniel Dunbarb7257262008-07-21 22:59:13 +00004229/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4230// This is declared to take (const void*, ...) and can take two
4231// optional constant int args.
4232bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00004233 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004234
Chris Lattner3b054132008-11-19 05:08:23 +00004235 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004236 return Diag(TheCall->getLocEnd(),
4237 diag::err_typecheck_call_too_many_args_at_most)
4238 << 0 /*function call*/ << 3 << NumArgs
4239 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004240
4241 // Argument 0 is checked for us and the remaining arguments must be
4242 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00004243 for (unsigned i = 1; i != NumArgs; ++i)
4244 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004245 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004246
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004247 return false;
4248}
4249
Hal Finkelf0417332014-07-17 14:25:55 +00004250/// SemaBuiltinAssume - Handle __assume (MS Extension).
4251// __assume does not evaluate its arguments, and should warn if its argument
4252// has side effects.
4253bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4254 Expr *Arg = TheCall->getArg(0);
4255 if (Arg->isInstantiationDependent()) return false;
4256
4257 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00004258 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00004259 << Arg->getSourceRange()
4260 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4261
4262 return false;
4263}
4264
David Majnemer86b1bfa2016-10-31 18:07:57 +00004265/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00004266/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4267/// than 8.
4268bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4269 // The alignment must be a constant integer.
4270 Expr *Arg = TheCall->getArg(1);
4271
4272 // We can't check the value of a dependent argument.
4273 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00004274 if (const auto *UE =
4275 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4276 if (UE->getKind() == UETT_AlignOf)
4277 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4278 << Arg->getSourceRange();
4279
David Majnemer51169932016-10-31 05:37:48 +00004280 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4281
4282 if (!Result.isPowerOf2())
4283 return Diag(TheCall->getLocStart(),
4284 diag::err_alignment_not_power_of_two)
4285 << Arg->getSourceRange();
4286
4287 if (Result < Context.getCharWidth())
4288 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4289 << (unsigned)Context.getCharWidth()
4290 << Arg->getSourceRange();
4291
4292 if (Result > INT32_MAX)
4293 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4294 << INT32_MAX
4295 << Arg->getSourceRange();
4296 }
4297
4298 return false;
4299}
4300
4301/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00004302/// as (const void*, size_t, ...) and can take one optional constant int arg.
4303bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4304 unsigned NumArgs = TheCall->getNumArgs();
4305
4306 if (NumArgs > 3)
4307 return Diag(TheCall->getLocEnd(),
4308 diag::err_typecheck_call_too_many_args_at_most)
4309 << 0 /*function call*/ << 3 << NumArgs
4310 << TheCall->getSourceRange();
4311
4312 // The alignment must be a constant integer.
4313 Expr *Arg = TheCall->getArg(1);
4314
4315 // We can't check the value of a dependent argument.
4316 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4317 llvm::APSInt Result;
4318 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4319 return true;
4320
4321 if (!Result.isPowerOf2())
4322 return Diag(TheCall->getLocStart(),
4323 diag::err_alignment_not_power_of_two)
4324 << Arg->getSourceRange();
4325 }
4326
4327 if (NumArgs > 2) {
4328 ExprResult Arg(TheCall->getArg(2));
4329 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4330 Context.getSizeType(), false);
4331 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4332 if (Arg.isInvalid()) return true;
4333 TheCall->setArg(2, Arg.get());
4334 }
Hal Finkelf0417332014-07-17 14:25:55 +00004335
4336 return false;
4337}
4338
Mehdi Amini06d367c2016-10-24 20:39:34 +00004339bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4340 unsigned BuiltinID =
4341 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4342 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4343
4344 unsigned NumArgs = TheCall->getNumArgs();
4345 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4346 if (NumArgs < NumRequiredArgs) {
4347 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4348 << 0 /* function call */ << NumRequiredArgs << NumArgs
4349 << TheCall->getSourceRange();
4350 }
4351 if (NumArgs >= NumRequiredArgs + 0x100) {
4352 return Diag(TheCall->getLocEnd(),
4353 diag::err_typecheck_call_too_many_args_at_most)
4354 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4355 << TheCall->getSourceRange();
4356 }
4357 unsigned i = 0;
4358
4359 // For formatting call, check buffer arg.
4360 if (!IsSizeCall) {
4361 ExprResult Arg(TheCall->getArg(i));
4362 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4363 Context, Context.VoidPtrTy, false);
4364 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4365 if (Arg.isInvalid())
4366 return true;
4367 TheCall->setArg(i, Arg.get());
4368 i++;
4369 }
4370
4371 // Check string literal arg.
4372 unsigned FormatIdx = i;
4373 {
4374 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4375 if (Arg.isInvalid())
4376 return true;
4377 TheCall->setArg(i, Arg.get());
4378 i++;
4379 }
4380
4381 // Make sure variadic args are scalar.
4382 unsigned FirstDataArg = i;
4383 while (i < NumArgs) {
4384 ExprResult Arg = DefaultVariadicArgumentPromotion(
4385 TheCall->getArg(i), VariadicFunction, nullptr);
4386 if (Arg.isInvalid())
4387 return true;
4388 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4389 if (ArgSize.getQuantity() >= 0x100) {
4390 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4391 << i << (int)ArgSize.getQuantity() << 0xff
4392 << TheCall->getSourceRange();
4393 }
4394 TheCall->setArg(i, Arg.get());
4395 i++;
4396 }
4397
4398 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4399 // call to avoid duplicate diagnostics.
4400 if (!IsSizeCall) {
4401 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4402 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4403 bool Success = CheckFormatArguments(
4404 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4405 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4406 CheckedVarArgs);
4407 if (!Success)
4408 return true;
4409 }
4410
4411 if (IsSizeCall) {
4412 TheCall->setType(Context.getSizeType());
4413 } else {
4414 TheCall->setType(Context.VoidPtrTy);
4415 }
4416 return false;
4417}
4418
Eric Christopher8d0c6212010-04-17 02:26:23 +00004419/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4420/// TheCall is a constant expression.
4421bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4422 llvm::APSInt &Result) {
4423 Expr *Arg = TheCall->getArg(ArgNum);
4424 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4425 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4426
4427 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4428
4429 if (!Arg->isIntegerConstantExpr(Result, Context))
4430 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004431 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004432
Chris Lattnerd545ad12009-09-23 06:06:36 +00004433 return false;
4434}
4435
Richard Sandiford28940af2014-04-16 08:47:51 +00004436/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4437/// TheCall is a constant expression in the range [Low, High].
4438bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4439 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004440 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004441
4442 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004443 Expr *Arg = TheCall->getArg(ArgNum);
4444 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004445 return false;
4446
Eric Christopher8d0c6212010-04-17 02:26:23 +00004447 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004448 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004449 return true;
4450
Richard Sandiford28940af2014-04-16 08:47:51 +00004451 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004452 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004453 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004454
4455 return false;
4456}
4457
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004458/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4459/// TheCall is a constant expression is a multiple of Num..
4460bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4461 unsigned Num) {
4462 llvm::APSInt Result;
4463
4464 // We can't check the value of a dependent argument.
4465 Expr *Arg = TheCall->getArg(ArgNum);
4466 if (Arg->isTypeDependent() || Arg->isValueDependent())
4467 return false;
4468
4469 // Check constant-ness first.
4470 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4471 return true;
4472
4473 if (Result.getSExtValue() % Num != 0)
4474 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4475 << Num << Arg->getSourceRange();
4476
4477 return false;
4478}
4479
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004480/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4481/// TheCall is an ARM/AArch64 special register string literal.
4482bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4483 int ArgNum, unsigned ExpectedFieldNum,
4484 bool AllowName) {
4485 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4486 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4487 BuiltinID == ARM::BI__builtin_arm_rsr ||
4488 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4489 BuiltinID == ARM::BI__builtin_arm_wsr ||
4490 BuiltinID == ARM::BI__builtin_arm_wsrp;
4491 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4492 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4493 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4494 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4495 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4496 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4497 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4498
4499 // We can't check the value of a dependent argument.
4500 Expr *Arg = TheCall->getArg(ArgNum);
4501 if (Arg->isTypeDependent() || Arg->isValueDependent())
4502 return false;
4503
4504 // Check if the argument is a string literal.
4505 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4506 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4507 << Arg->getSourceRange();
4508
4509 // Check the type of special register given.
4510 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4511 SmallVector<StringRef, 6> Fields;
4512 Reg.split(Fields, ":");
4513
4514 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4515 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4516 << Arg->getSourceRange();
4517
4518 // If the string is the name of a register then we cannot check that it is
4519 // valid here but if the string is of one the forms described in ACLE then we
4520 // can check that the supplied fields are integers and within the valid
4521 // ranges.
4522 if (Fields.size() > 1) {
4523 bool FiveFields = Fields.size() == 5;
4524
4525 bool ValidString = true;
4526 if (IsARMBuiltin) {
4527 ValidString &= Fields[0].startswith_lower("cp") ||
4528 Fields[0].startswith_lower("p");
4529 if (ValidString)
4530 Fields[0] =
4531 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4532
4533 ValidString &= Fields[2].startswith_lower("c");
4534 if (ValidString)
4535 Fields[2] = Fields[2].drop_front(1);
4536
4537 if (FiveFields) {
4538 ValidString &= Fields[3].startswith_lower("c");
4539 if (ValidString)
4540 Fields[3] = Fields[3].drop_front(1);
4541 }
4542 }
4543
4544 SmallVector<int, 5> Ranges;
4545 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00004546 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004547 else
4548 Ranges.append({15, 7, 15});
4549
4550 for (unsigned i=0; i<Fields.size(); ++i) {
4551 int IntField;
4552 ValidString &= !Fields[i].getAsInteger(10, IntField);
4553 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4554 }
4555
4556 if (!ValidString)
4557 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4558 << Arg->getSourceRange();
4559
4560 } else if (IsAArch64Builtin && Fields.size() == 1) {
4561 // If the register name is one of those that appear in the condition below
4562 // and the special register builtin being used is one of the write builtins,
4563 // then we require that the argument provided for writing to the register
4564 // is an integer constant expression. This is because it will be lowered to
4565 // an MSR (immediate) instruction, so we need to know the immediate at
4566 // compile time.
4567 if (TheCall->getNumArgs() != 2)
4568 return false;
4569
4570 std::string RegLower = Reg.lower();
4571 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4572 RegLower != "pan" && RegLower != "uao")
4573 return false;
4574
4575 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4576 }
4577
4578 return false;
4579}
4580
Eli Friedmanc97d0142009-05-03 06:04:26 +00004581/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004582/// This checks that the target supports __builtin_longjmp and
4583/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004584bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004585 if (!Context.getTargetInfo().hasSjLjLowering())
4586 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4587 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4588
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004589 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004590 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004591
Eric Christopher8d0c6212010-04-17 02:26:23 +00004592 // TODO: This is less than ideal. Overload this to take a value.
4593 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4594 return true;
4595
4596 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004597 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4598 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4599
4600 return false;
4601}
4602
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004603/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4604/// This checks that the target supports __builtin_setjmp.
4605bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4606 if (!Context.getTargetInfo().hasSjLjLowering())
4607 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4608 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4609 return false;
4610}
4611
Richard Smithd7293d72013-08-05 18:49:43 +00004612namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004613class UncoveredArgHandler {
4614 enum { Unknown = -1, AllCovered = -2 };
4615 signed FirstUncoveredArg;
4616 SmallVector<const Expr *, 4> DiagnosticExprs;
4617
4618public:
4619 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4620
4621 bool hasUncoveredArg() const {
4622 return (FirstUncoveredArg >= 0);
4623 }
4624
4625 unsigned getUncoveredArg() const {
4626 assert(hasUncoveredArg() && "no uncovered argument");
4627 return FirstUncoveredArg;
4628 }
4629
4630 void setAllCovered() {
4631 // A string has been found with all arguments covered, so clear out
4632 // the diagnostics.
4633 DiagnosticExprs.clear();
4634 FirstUncoveredArg = AllCovered;
4635 }
4636
4637 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4638 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4639
4640 // Don't update if a previous string covers all arguments.
4641 if (FirstUncoveredArg == AllCovered)
4642 return;
4643
4644 // UncoveredArgHandler tracks the highest uncovered argument index
4645 // and with it all the strings that match this index.
4646 if (NewFirstUncoveredArg == FirstUncoveredArg)
4647 DiagnosticExprs.push_back(StrExpr);
4648 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4649 DiagnosticExprs.clear();
4650 DiagnosticExprs.push_back(StrExpr);
4651 FirstUncoveredArg = NewFirstUncoveredArg;
4652 }
4653 }
4654
4655 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4656};
4657
Richard Smithd7293d72013-08-05 18:49:43 +00004658enum StringLiteralCheckType {
4659 SLCT_NotALiteral,
4660 SLCT_UncheckedLiteral,
4661 SLCT_CheckedLiteral
4662};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004663} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00004664
Stephen Hines648c3692016-09-16 01:07:04 +00004665static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4666 BinaryOperatorKind BinOpKind,
4667 bool AddendIsRight) {
4668 unsigned BitWidth = Offset.getBitWidth();
4669 unsigned AddendBitWidth = Addend.getBitWidth();
4670 // There might be negative interim results.
4671 if (Addend.isUnsigned()) {
4672 Addend = Addend.zext(++AddendBitWidth);
4673 Addend.setIsSigned(true);
4674 }
4675 // Adjust the bit width of the APSInts.
4676 if (AddendBitWidth > BitWidth) {
4677 Offset = Offset.sext(AddendBitWidth);
4678 BitWidth = AddendBitWidth;
4679 } else if (BitWidth > AddendBitWidth) {
4680 Addend = Addend.sext(BitWidth);
4681 }
4682
4683 bool Ov = false;
4684 llvm::APSInt ResOffset = Offset;
4685 if (BinOpKind == BO_Add)
4686 ResOffset = Offset.sadd_ov(Addend, Ov);
4687 else {
4688 assert(AddendIsRight && BinOpKind == BO_Sub &&
4689 "operator must be add or sub with addend on the right");
4690 ResOffset = Offset.ssub_ov(Addend, Ov);
4691 }
4692
4693 // We add an offset to a pointer here so we should support an offset as big as
4694 // possible.
4695 if (Ov) {
4696 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00004697 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00004698 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4699 return;
4700 }
4701
4702 Offset = ResOffset;
4703}
4704
4705namespace {
4706// This is a wrapper class around StringLiteral to support offsetted string
4707// literals as format strings. It takes the offset into account when returning
4708// the string and its length or the source locations to display notes correctly.
4709class FormatStringLiteral {
4710 const StringLiteral *FExpr;
4711 int64_t Offset;
4712
4713 public:
4714 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4715 : FExpr(fexpr), Offset(Offset) {}
4716
4717 StringRef getString() const {
4718 return FExpr->getString().drop_front(Offset);
4719 }
4720
4721 unsigned getByteLength() const {
4722 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4723 }
4724 unsigned getLength() const { return FExpr->getLength() - Offset; }
4725 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4726
4727 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4728
4729 QualType getType() const { return FExpr->getType(); }
4730
4731 bool isAscii() const { return FExpr->isAscii(); }
4732 bool isWide() const { return FExpr->isWide(); }
4733 bool isUTF8() const { return FExpr->isUTF8(); }
4734 bool isUTF16() const { return FExpr->isUTF16(); }
4735 bool isUTF32() const { return FExpr->isUTF32(); }
4736 bool isPascal() const { return FExpr->isPascal(); }
4737
4738 SourceLocation getLocationOfByte(
4739 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4740 const TargetInfo &Target, unsigned *StartToken = nullptr,
4741 unsigned *StartTokenByteOffset = nullptr) const {
4742 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4743 StartToken, StartTokenByteOffset);
4744 }
4745
4746 SourceLocation getLocStart() const LLVM_READONLY {
4747 return FExpr->getLocStart().getLocWithOffset(Offset);
4748 }
4749 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4750};
4751} // end anonymous namespace
4752
4753static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004754 const Expr *OrigFormatExpr,
4755 ArrayRef<const Expr *> Args,
4756 bool HasVAListArg, unsigned format_idx,
4757 unsigned firstDataArg,
4758 Sema::FormatStringType Type,
4759 bool inFunctionCall,
4760 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004761 llvm::SmallBitVector &CheckedVarArgs,
4762 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004763
Richard Smith55ce3522012-06-25 20:30:08 +00004764// Determine if an expression is a string literal or constant string.
4765// If this function returns false on the arguments to a function expecting a
4766// format string, we will usually need to emit a warning.
4767// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00004768static StringLiteralCheckType
4769checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4770 bool HasVAListArg, unsigned format_idx,
4771 unsigned firstDataArg, Sema::FormatStringType Type,
4772 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004773 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004774 UncoveredArgHandler &UncoveredArg,
4775 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00004776 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00004777 assert(Offset.isSigned() && "invalid offset");
4778
Douglas Gregorc25f7662009-05-19 22:10:17 +00004779 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00004780 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004781
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004782 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00004783
Richard Smithd7293d72013-08-05 18:49:43 +00004784 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00004785 // Technically -Wformat-nonliteral does not warn about this case.
4786 // The behavior of printf and friends in this case is implementation
4787 // dependent. Ideally if the format string cannot be null then
4788 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00004789 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00004790
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004791 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00004792 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004793 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00004794 // The expression is a literal if both sub-expressions were, and it was
4795 // completely checked only if both sub-expressions were checked.
4796 const AbstractConditionalOperator *C =
4797 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004798
4799 // Determine whether it is necessary to check both sub-expressions, for
4800 // example, because the condition expression is a constant that can be
4801 // evaluated at compile time.
4802 bool CheckLeft = true, CheckRight = true;
4803
4804 bool Cond;
4805 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4806 if (Cond)
4807 CheckRight = false;
4808 else
4809 CheckLeft = false;
4810 }
4811
Stephen Hines648c3692016-09-16 01:07:04 +00004812 // We need to maintain the offsets for the right and the left hand side
4813 // separately to check if every possible indexed expression is a valid
4814 // string literal. They might have different offsets for different string
4815 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004816 StringLiteralCheckType Left;
4817 if (!CheckLeft)
4818 Left = SLCT_UncheckedLiteral;
4819 else {
4820 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4821 HasVAListArg, format_idx, firstDataArg,
4822 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004823 CheckedVarArgs, UncoveredArg, Offset);
4824 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004825 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004826 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004827 }
4828
Richard Smith55ce3522012-06-25 20:30:08 +00004829 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004830 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004831 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004832 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004833 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004834
4835 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004836 }
4837
4838 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00004839 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4840 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004841 }
4842
John McCallc07a0c72011-02-17 10:25:35 +00004843 case Stmt::OpaqueValueExprClass:
4844 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4845 E = src;
4846 goto tryAgain;
4847 }
Richard Smith55ce3522012-06-25 20:30:08 +00004848 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004849
Ted Kremeneka8890832011-02-24 23:03:04 +00004850 case Stmt::PredefinedExprClass:
4851 // While __func__, etc., are technically not string literals, they
4852 // cannot contain format specifiers and thus are not a security
4853 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004854 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004855
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004856 case Stmt::DeclRefExprClass: {
4857 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004858
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004859 // As an exception, do not flag errors for variables binding to
4860 // const string literals.
4861 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4862 bool isConstant = false;
4863 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004864
Richard Smithd7293d72013-08-05 18:49:43 +00004865 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4866 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004867 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004868 isConstant = T.isConstant(S.Context) &&
4869 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004870 } else if (T->isObjCObjectPointerType()) {
4871 // In ObjC, there is usually no "const ObjectPointer" type,
4872 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004873 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004874 }
Mike Stump11289f42009-09-09 15:08:12 +00004875
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004876 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004877 if (const Expr *Init = VD->getAnyInitializer()) {
4878 // Look through initializers like const char c[] = { "foo" }
4879 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4880 if (InitList->isStringLiteralInit())
4881 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4882 }
Richard Smithd7293d72013-08-05 18:49:43 +00004883 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004884 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004885 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004886 /*InFunctionCall*/ false, CheckedVarArgs,
4887 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004888 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004889 }
Mike Stump11289f42009-09-09 15:08:12 +00004890
Anders Carlssonb012ca92009-06-28 19:55:58 +00004891 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4892 // special check to see if the format string is a function parameter
4893 // of the function calling the printf function. If the function
4894 // has an attribute indicating it is a printf-like function, then we
4895 // should suppress warnings concerning non-literals being used in a call
4896 // to a vprintf function. For example:
4897 //
4898 // void
4899 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4900 // va_list ap;
4901 // va_start(ap, fmt);
4902 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4903 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00004904 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004905 if (HasVAListArg) {
4906 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4907 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4908 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004909 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004910 // adjust for implicit parameter
4911 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4912 if (MD->isInstance())
4913 ++PVIndex;
4914 // We also check if the formats are compatible.
4915 // We can't pass a 'scanf' string to a 'printf' function.
4916 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00004917 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00004918 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004919 }
4920 }
4921 }
4922 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004923 }
Mike Stump11289f42009-09-09 15:08:12 +00004924
Richard Smith55ce3522012-06-25 20:30:08 +00004925 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004926 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004927
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004928 case Stmt::CallExprClass:
4929 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004930 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004931 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4932 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4933 unsigned ArgIndex = FA->getFormatIdx();
4934 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4935 if (MD->isInstance())
4936 --ArgIndex;
4937 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00004938
Richard Smithd7293d72013-08-05 18:49:43 +00004939 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004940 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00004941 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004942 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004943 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4944 unsigned BuiltinID = FD->getBuiltinID();
4945 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4946 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4947 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00004948 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004949 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004950 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004951 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004952 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004953 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004954 }
4955 }
Mike Stump11289f42009-09-09 15:08:12 +00004956
Richard Smith55ce3522012-06-25 20:30:08 +00004957 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004958 }
Alex Lorenzd9007142016-10-24 09:42:34 +00004959 case Stmt::ObjCMessageExprClass: {
4960 const auto *ME = cast<ObjCMessageExpr>(E);
4961 if (const auto *ND = ME->getMethodDecl()) {
4962 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4963 unsigned ArgIndex = FA->getFormatIdx();
4964 const Expr *Arg = ME->getArg(ArgIndex - 1);
4965 return checkFormatStringExpr(
4966 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4967 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4968 }
4969 }
4970
4971 return SLCT_NotALiteral;
4972 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004973 case Stmt::ObjCStringLiteralClass:
4974 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00004975 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004976
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004977 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004978 StrE = ObjCFExpr->getString();
4979 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004980 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004981
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004982 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00004983 if (Offset.isNegative() || Offset > StrE->getLength()) {
4984 // TODO: It would be better to have an explicit warning for out of
4985 // bounds literals.
4986 return SLCT_NotALiteral;
4987 }
4988 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4989 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004990 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004991 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00004992 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004993 }
Mike Stump11289f42009-09-09 15:08:12 +00004994
Richard Smith55ce3522012-06-25 20:30:08 +00004995 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004996 }
Stephen Hines648c3692016-09-16 01:07:04 +00004997 case Stmt::BinaryOperatorClass: {
4998 llvm::APSInt LResult;
4999 llvm::APSInt RResult;
5000
5001 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5002
5003 // A string literal + an int offset is still a string literal.
5004 if (BinOp->isAdditiveOp()) {
5005 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5006 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5007
5008 if (LIsInt != RIsInt) {
5009 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5010
5011 if (LIsInt) {
5012 if (BinOpKind == BO_Add) {
5013 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5014 E = BinOp->getRHS();
5015 goto tryAgain;
5016 }
5017 } else {
5018 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5019 E = BinOp->getLHS();
5020 goto tryAgain;
5021 }
5022 }
Stephen Hines648c3692016-09-16 01:07:04 +00005023 }
George Burgess IVd273aab2016-09-22 00:00:26 +00005024
5025 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00005026 }
5027 case Stmt::UnaryOperatorClass: {
5028 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5029 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
5030 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
5031 llvm::APSInt IndexResult;
5032 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5033 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5034 E = ASE->getBase();
5035 goto tryAgain;
5036 }
5037 }
5038
5039 return SLCT_NotALiteral;
5040 }
Mike Stump11289f42009-09-09 15:08:12 +00005041
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005042 default:
Richard Smith55ce3522012-06-25 20:30:08 +00005043 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005044 }
5045}
5046
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005047Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00005048 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00005049 .Case("scanf", FST_Scanf)
5050 .Cases("printf", "printf0", FST_Printf)
5051 .Cases("NSString", "CFString", FST_NSString)
5052 .Case("strftime", FST_Strftime)
5053 .Case("strfmon", FST_Strfmon)
5054 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5055 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5056 .Case("os_trace", FST_OSLog)
5057 .Case("os_log", FST_OSLog)
5058 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005059}
5060
Jordan Rose3e0ec582012-07-19 18:10:23 +00005061/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00005062/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00005063/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005064bool Sema::CheckFormatArguments(const FormatAttr *Format,
5065 ArrayRef<const Expr *> Args,
5066 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005067 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005068 SourceLocation Loc, SourceRange Range,
5069 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00005070 FormatStringInfo FSI;
5071 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005072 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00005073 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00005074 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00005075 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005076}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00005077
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005078bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005079 bool HasVAListArg, unsigned format_idx,
5080 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005081 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005082 SourceLocation Loc, SourceRange Range,
5083 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00005084 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005085 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005086 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00005087 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005088 }
Mike Stump11289f42009-09-09 15:08:12 +00005089
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005090 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005091
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005092 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00005093 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005094 // Dynamically generated format strings are difficult to
5095 // automatically vet at compile time. Requiring that format strings
5096 // are string literals: (1) permits the checking of format strings by
5097 // the compiler and thereby (2) can practically remove the source of
5098 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00005099
Mike Stump11289f42009-09-09 15:08:12 +00005100 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00005101 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00005102 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00005103 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005104 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00005105 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00005106 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5107 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005108 /*IsFunctionCall*/ true, CheckedVarArgs,
5109 UncoveredArg,
5110 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005111
5112 // Generate a diagnostic where an uncovered argument is detected.
5113 if (UncoveredArg.hasUncoveredArg()) {
5114 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5115 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5116 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5117 }
5118
Richard Smith55ce3522012-06-25 20:30:08 +00005119 if (CT != SLCT_NotALiteral)
5120 // Literal format string found, check done!
5121 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00005122
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005123 // Strftime is particular as it always uses a single 'time' argument,
5124 // so it is safe to pass a non-literal string.
5125 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00005126 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005127
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005128 // Do not emit diag when the string param is a macro expansion and the
5129 // format is either NSString or CFString. This is a hack to prevent
5130 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5131 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005132 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5133 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00005134 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005135
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005136 // If there are no arguments specified, warn with -Wformat-security, otherwise
5137 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005138 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00005139 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5140 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005141 switch (Type) {
5142 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005143 break;
5144 case FST_Kprintf:
5145 case FST_FreeBSDKPrintf:
5146 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00005147 Diag(FormatLoc, diag::note_format_security_fixit)
5148 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005149 break;
5150 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00005151 Diag(FormatLoc, diag::note_format_security_fixit)
5152 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005153 break;
5154 }
5155 } else {
5156 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005157 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005158 }
Richard Smith55ce3522012-06-25 20:30:08 +00005159 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005160}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005161
Ted Kremenekab278de2010-01-28 23:39:18 +00005162namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00005163class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5164protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00005165 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00005166 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00005167 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005168 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00005169 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00005170 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00005171 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00005172 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005173 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00005174 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00005175 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00005176 bool usesPositionalArgs;
5177 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005178 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00005179 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00005180 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005181 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005182
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005183public:
Stephen Hines648c3692016-09-16 01:07:04 +00005184 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005185 const Expr *origFormatExpr,
5186 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005187 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005188 ArrayRef<const Expr *> Args, unsigned formatIdx,
5189 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005190 llvm::SmallBitVector &CheckedVarArgs,
5191 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005192 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5193 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5194 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5195 usesPositionalArgs(false), atFirstArg(true),
5196 inFunctionCall(inFunctionCall), CallType(callType),
5197 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00005198 CoveredArgs.resize(numDataArgs);
5199 CoveredArgs.reset();
5200 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005201
Ted Kremenek019d2242010-01-29 01:50:07 +00005202 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005203
Ted Kremenek02087932010-07-16 02:11:22 +00005204 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005205 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005206
Jordan Rose92303592012-09-08 04:00:03 +00005207 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005208 const analyze_format_string::FormatSpecifier &FS,
5209 const analyze_format_string::ConversionSpecifier &CS,
5210 const char *startSpecifier, unsigned specifierLen,
5211 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00005212
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005213 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005214 const analyze_format_string::FormatSpecifier &FS,
5215 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005216
5217 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005218 const analyze_format_string::ConversionSpecifier &CS,
5219 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005220
Craig Toppere14c0f82014-03-12 04:55:44 +00005221 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005222
Craig Toppere14c0f82014-03-12 04:55:44 +00005223 void HandleInvalidPosition(const char *startSpecifier,
5224 unsigned specifierLen,
5225 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005226
Craig Toppere14c0f82014-03-12 04:55:44 +00005227 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005228
Craig Toppere14c0f82014-03-12 04:55:44 +00005229 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005230
Richard Trieu03cf7b72011-10-28 00:41:25 +00005231 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00005232 static void
5233 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5234 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5235 bool IsStringLocation, Range StringRange,
5236 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005237
Ted Kremenek02087932010-07-16 02:11:22 +00005238protected:
Ted Kremenekce815422010-07-19 21:25:57 +00005239 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5240 const char *startSpec,
5241 unsigned specifierLen,
5242 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005243
5244 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5245 const char *startSpec,
5246 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00005247
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005248 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00005249 CharSourceRange getSpecifierRange(const char *startSpecifier,
5250 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00005251 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005252
Ted Kremenek5739de72010-01-29 01:06:55 +00005253 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005254
5255 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5256 const analyze_format_string::ConversionSpecifier &CS,
5257 const char *startSpecifier, unsigned specifierLen,
5258 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005259
5260 template <typename Range>
5261 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5262 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005263 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00005264};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005265} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005266
Ted Kremenek02087932010-07-16 02:11:22 +00005267SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00005268 return OrigFormatExpr->getSourceRange();
5269}
5270
Ted Kremenek02087932010-07-16 02:11:22 +00005271CharSourceRange CheckFormatHandler::
5272getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00005273 SourceLocation Start = getLocationOfByte(startSpecifier);
5274 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5275
5276 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00005277 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00005278
5279 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005280}
5281
Ted Kremenek02087932010-07-16 02:11:22 +00005282SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00005283 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5284 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00005285}
5286
Ted Kremenek02087932010-07-16 02:11:22 +00005287void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5288 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00005289 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5290 getLocationOfByte(startSpecifier),
5291 /*IsStringLocation*/true,
5292 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00005293}
5294
Jordan Rose92303592012-09-08 04:00:03 +00005295void CheckFormatHandler::HandleInvalidLengthModifier(
5296 const analyze_format_string::FormatSpecifier &FS,
5297 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00005298 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00005299 using namespace analyze_format_string;
5300
5301 const LengthModifier &LM = FS.getLengthModifier();
5302 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5303
5304 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005305 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00005306 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005307 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005308 getLocationOfByte(LM.getStart()),
5309 /*IsStringLocation*/true,
5310 getSpecifierRange(startSpecifier, specifierLen));
5311
5312 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5313 << FixedLM->toString()
5314 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5315
5316 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005317 FixItHint Hint;
5318 if (DiagID == diag::warn_format_nonsensical_length)
5319 Hint = FixItHint::CreateRemoval(LMRange);
5320
5321 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005322 getLocationOfByte(LM.getStart()),
5323 /*IsStringLocation*/true,
5324 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00005325 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00005326 }
5327}
5328
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005329void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005330 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005331 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005332 using namespace analyze_format_string;
5333
5334 const LengthModifier &LM = FS.getLengthModifier();
5335 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5336
5337 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005338 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005339 if (FixedLM) {
5340 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5341 << LM.toString() << 0,
5342 getLocationOfByte(LM.getStart()),
5343 /*IsStringLocation*/true,
5344 getSpecifierRange(startSpecifier, specifierLen));
5345
5346 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5347 << FixedLM->toString()
5348 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5349
5350 } else {
5351 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5352 << LM.toString() << 0,
5353 getLocationOfByte(LM.getStart()),
5354 /*IsStringLocation*/true,
5355 getSpecifierRange(startSpecifier, specifierLen));
5356 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005357}
5358
5359void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5360 const analyze_format_string::ConversionSpecifier &CS,
5361 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005362 using namespace analyze_format_string;
5363
5364 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005365 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005366 if (FixedCS) {
5367 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5368 << CS.toString() << /*conversion specifier*/1,
5369 getLocationOfByte(CS.getStart()),
5370 /*IsStringLocation*/true,
5371 getSpecifierRange(startSpecifier, specifierLen));
5372
5373 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5374 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5375 << FixedCS->toString()
5376 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5377 } else {
5378 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5379 << CS.toString() << /*conversion specifier*/1,
5380 getLocationOfByte(CS.getStart()),
5381 /*IsStringLocation*/true,
5382 getSpecifierRange(startSpecifier, specifierLen));
5383 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005384}
5385
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005386void CheckFormatHandler::HandlePosition(const char *startPos,
5387 unsigned posLen) {
5388 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5389 getLocationOfByte(startPos),
5390 /*IsStringLocation*/true,
5391 getSpecifierRange(startPos, posLen));
5392}
5393
Ted Kremenekd1668192010-02-27 01:41:03 +00005394void
Ted Kremenek02087932010-07-16 02:11:22 +00005395CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5396 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005397 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5398 << (unsigned) p,
5399 getLocationOfByte(startPos), /*IsStringLocation*/true,
5400 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005401}
5402
Ted Kremenek02087932010-07-16 02:11:22 +00005403void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005404 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005405 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5406 getLocationOfByte(startPos),
5407 /*IsStringLocation*/true,
5408 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005409}
5410
Ted Kremenek02087932010-07-16 02:11:22 +00005411void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005412 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005413 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005414 EmitFormatDiagnostic(
5415 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5416 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5417 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005418 }
Ted Kremenek02087932010-07-16 02:11:22 +00005419}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005420
Jordan Rose58bbe422012-07-19 18:10:08 +00005421// Note that this may return NULL if there was an error parsing or building
5422// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005423const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005424 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005425}
5426
5427void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005428 // Does the number of data arguments exceed the number of
5429 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005430 if (!HasVAListArg) {
5431 // Find any arguments that weren't covered.
5432 CoveredArgs.flip();
5433 signed notCoveredArg = CoveredArgs.find_first();
5434 if (notCoveredArg >= 0) {
5435 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005436 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5437 } else {
5438 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005439 }
5440 }
5441}
5442
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005443void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5444 const Expr *ArgExpr) {
5445 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5446 "Invalid state");
5447
5448 if (!ArgExpr)
5449 return;
5450
5451 SourceLocation Loc = ArgExpr->getLocStart();
5452
5453 if (S.getSourceManager().isInSystemMacro(Loc))
5454 return;
5455
5456 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5457 for (auto E : DiagnosticExprs)
5458 PDiag << E->getSourceRange();
5459
5460 CheckFormatHandler::EmitFormatDiagnostic(
5461 S, IsFunctionCall, DiagnosticExprs[0],
5462 PDiag, Loc, /*IsStringLocation*/false,
5463 DiagnosticExprs[0]->getSourceRange());
5464}
5465
Ted Kremenekce815422010-07-19 21:25:57 +00005466bool
5467CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5468 SourceLocation Loc,
5469 const char *startSpec,
5470 unsigned specifierLen,
5471 const char *csStart,
5472 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005473 bool keepGoing = true;
5474 if (argIndex < NumDataArgs) {
5475 // Consider the argument coverered, even though the specifier doesn't
5476 // make sense.
5477 CoveredArgs.set(argIndex);
5478 }
5479 else {
5480 // If argIndex exceeds the number of data arguments we
5481 // don't issue a warning because that is just a cascade of warnings (and
5482 // they may have intended '%%' anyway). We don't want to continue processing
5483 // the format string after this point, however, as we will like just get
5484 // gibberish when trying to match arguments.
5485 keepGoing = false;
5486 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005487
5488 StringRef Specifier(csStart, csLen);
5489
5490 // If the specifier in non-printable, it could be the first byte of a UTF-8
5491 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5492 // hex value.
5493 std::string CodePointStr;
5494 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005495 llvm::UTF32 CodePoint;
5496 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5497 const llvm::UTF8 *E =
5498 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5499 llvm::ConversionResult Result =
5500 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005501
Justin Lebar90910552016-09-30 00:38:45 +00005502 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005503 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005504 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005505 }
5506
5507 llvm::raw_string_ostream OS(CodePointStr);
5508 if (CodePoint < 256)
5509 OS << "\\x" << llvm::format("%02x", CodePoint);
5510 else if (CodePoint <= 0xFFFF)
5511 OS << "\\u" << llvm::format("%04x", CodePoint);
5512 else
5513 OS << "\\U" << llvm::format("%08x", CodePoint);
5514 OS.flush();
5515 Specifier = CodePointStr;
5516 }
5517
5518 EmitFormatDiagnostic(
5519 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5520 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5521
Ted Kremenekce815422010-07-19 21:25:57 +00005522 return keepGoing;
5523}
5524
Richard Trieu03cf7b72011-10-28 00:41:25 +00005525void
5526CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5527 const char *startSpec,
5528 unsigned specifierLen) {
5529 EmitFormatDiagnostic(
5530 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5531 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5532}
5533
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005534bool
5535CheckFormatHandler::CheckNumArgs(
5536 const analyze_format_string::FormatSpecifier &FS,
5537 const analyze_format_string::ConversionSpecifier &CS,
5538 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5539
5540 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005541 PartialDiagnostic PDiag = FS.usesPositionalArg()
5542 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5543 << (argIndex+1) << NumDataArgs)
5544 : S.PDiag(diag::warn_printf_insufficient_data_args);
5545 EmitFormatDiagnostic(
5546 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5547 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005548
5549 // Since more arguments than conversion tokens are given, by extension
5550 // all arguments are covered, so mark this as so.
5551 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005552 return false;
5553 }
5554 return true;
5555}
5556
Richard Trieu03cf7b72011-10-28 00:41:25 +00005557template<typename Range>
5558void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5559 SourceLocation Loc,
5560 bool IsStringLocation,
5561 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005562 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005563 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005564 Loc, IsStringLocation, StringRange, FixIt);
5565}
5566
5567/// \brief If the format string is not within the funcion call, emit a note
5568/// so that the function call and string are in diagnostic messages.
5569///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005570/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005571/// call and only one diagnostic message will be produced. Otherwise, an
5572/// extra note will be emitted pointing to location of the format string.
5573///
5574/// \param ArgumentExpr the expression that is passed as the format string
5575/// argument in the function call. Used for getting locations when two
5576/// diagnostics are emitted.
5577///
5578/// \param PDiag the callee should already have provided any strings for the
5579/// diagnostic message. This function only adds locations and fixits
5580/// to diagnostics.
5581///
5582/// \param Loc primary location for diagnostic. If two diagnostics are
5583/// required, one will be at Loc and a new SourceLocation will be created for
5584/// the other one.
5585///
5586/// \param IsStringLocation if true, Loc points to the format string should be
5587/// used for the note. Otherwise, Loc points to the argument list and will
5588/// be used with PDiag.
5589///
5590/// \param StringRange some or all of the string to highlight. This is
5591/// templated so it can accept either a CharSourceRange or a SourceRange.
5592///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005593/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005594template <typename Range>
5595void CheckFormatHandler::EmitFormatDiagnostic(
5596 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5597 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5598 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005599 if (InFunctionCall) {
5600 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5601 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005602 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00005603 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005604 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5605 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00005606
5607 const Sema::SemaDiagnosticBuilder &Note =
5608 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5609 diag::note_format_string_defined);
5610
5611 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005612 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005613 }
5614}
5615
Ted Kremenek02087932010-07-16 02:11:22 +00005616//===--- CHECK: Printf format string checking ------------------------------===//
5617
5618namespace {
5619class CheckPrintfHandler : public CheckFormatHandler {
5620public:
Stephen Hines648c3692016-09-16 01:07:04 +00005621 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005622 const Expr *origFormatExpr,
5623 const Sema::FormatStringType type, unsigned firstDataArg,
5624 unsigned numDataArgs, bool isObjC, const char *beg,
5625 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005626 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005627 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005628 llvm::SmallBitVector &CheckedVarArgs,
5629 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005630 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5631 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5632 inFunctionCall, CallType, CheckedVarArgs,
5633 UncoveredArg) {}
5634
5635 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5636
5637 /// Returns true if '%@' specifiers are allowed in the format string.
5638 bool allowsObjCArg() const {
5639 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5640 FSType == Sema::FST_OSTrace;
5641 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00005642
Ted Kremenek02087932010-07-16 02:11:22 +00005643 bool HandleInvalidPrintfConversionSpecifier(
5644 const analyze_printf::PrintfSpecifier &FS,
5645 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005646 unsigned specifierLen) override;
5647
Ted Kremenek02087932010-07-16 02:11:22 +00005648 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5649 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005650 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005651 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5652 const char *StartSpecifier,
5653 unsigned SpecifierLen,
5654 const Expr *E);
5655
Ted Kremenek02087932010-07-16 02:11:22 +00005656 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5657 const char *startSpecifier, unsigned specifierLen);
5658 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5659 const analyze_printf::OptionalAmount &Amt,
5660 unsigned type,
5661 const char *startSpecifier, unsigned specifierLen);
5662 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5663 const analyze_printf::OptionalFlag &flag,
5664 const char *startSpecifier, unsigned specifierLen);
5665 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5666 const analyze_printf::OptionalFlag &ignoredFlag,
5667 const analyze_printf::OptionalFlag &flag,
5668 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005669 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00005670 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00005671
5672 void HandleEmptyObjCModifierFlag(const char *startFlag,
5673 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005674
Ted Kremenek2b417712015-07-02 05:39:16 +00005675 void HandleInvalidObjCModifierFlag(const char *startFlag,
5676 unsigned flagLen) override;
5677
5678 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5679 const char *flagsEnd,
5680 const char *conversionPosition)
5681 override;
5682};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005683} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00005684
5685bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5686 const analyze_printf::PrintfSpecifier &FS,
5687 const char *startSpecifier,
5688 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005689 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005690 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005691
Ted Kremenekce815422010-07-19 21:25:57 +00005692 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5693 getLocationOfByte(CS.getStart()),
5694 startSpecifier, specifierLen,
5695 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00005696}
5697
Ted Kremenek02087932010-07-16 02:11:22 +00005698bool CheckPrintfHandler::HandleAmount(
5699 const analyze_format_string::OptionalAmount &Amt,
5700 unsigned k, const char *startSpecifier,
5701 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005702 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005703 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00005704 unsigned argIndex = Amt.getArgIndex();
5705 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005706 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5707 << k,
5708 getLocationOfByte(Amt.getStart()),
5709 /*IsStringLocation*/true,
5710 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005711 // Don't do any more checking. We will just emit
5712 // spurious errors.
5713 return false;
5714 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005715
Ted Kremenek5739de72010-01-29 01:06:55 +00005716 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00005717 // Although not in conformance with C99, we also allow the argument to be
5718 // an 'unsigned int' as that is a reasonably safe case. GCC also
5719 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00005720 CoveredArgs.set(argIndex);
5721 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005722 if (!Arg)
5723 return false;
5724
Ted Kremenek5739de72010-01-29 01:06:55 +00005725 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005726
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005727 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5728 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005729
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005730 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005731 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005732 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00005733 << T << Arg->getSourceRange(),
5734 getLocationOfByte(Amt.getStart()),
5735 /*IsStringLocation*/true,
5736 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005737 // Don't do any more checking. We will just emit
5738 // spurious errors.
5739 return false;
5740 }
5741 }
5742 }
5743 return true;
5744}
Ted Kremenek5739de72010-01-29 01:06:55 +00005745
Tom Careb49ec692010-06-17 19:00:27 +00005746void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00005747 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005748 const analyze_printf::OptionalAmount &Amt,
5749 unsigned type,
5750 const char *startSpecifier,
5751 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005752 const analyze_printf::PrintfConversionSpecifier &CS =
5753 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00005754
Richard Trieu03cf7b72011-10-28 00:41:25 +00005755 FixItHint fixit =
5756 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5757 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5758 Amt.getConstantLength()))
5759 : FixItHint();
5760
5761 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5762 << type << CS.toString(),
5763 getLocationOfByte(Amt.getStart()),
5764 /*IsStringLocation*/true,
5765 getSpecifierRange(startSpecifier, specifierLen),
5766 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00005767}
5768
Ted Kremenek02087932010-07-16 02:11:22 +00005769void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005770 const analyze_printf::OptionalFlag &flag,
5771 const char *startSpecifier,
5772 unsigned specifierLen) {
5773 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005774 const analyze_printf::PrintfConversionSpecifier &CS =
5775 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00005776 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5777 << flag.toString() << CS.toString(),
5778 getLocationOfByte(flag.getPosition()),
5779 /*IsStringLocation*/true,
5780 getSpecifierRange(startSpecifier, specifierLen),
5781 FixItHint::CreateRemoval(
5782 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005783}
5784
5785void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00005786 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005787 const analyze_printf::OptionalFlag &ignoredFlag,
5788 const analyze_printf::OptionalFlag &flag,
5789 const char *startSpecifier,
5790 unsigned specifierLen) {
5791 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005792 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5793 << ignoredFlag.toString() << flag.toString(),
5794 getLocationOfByte(ignoredFlag.getPosition()),
5795 /*IsStringLocation*/true,
5796 getSpecifierRange(startSpecifier, specifierLen),
5797 FixItHint::CreateRemoval(
5798 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005799}
5800
Ted Kremenek2b417712015-07-02 05:39:16 +00005801// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5802// bool IsStringLocation, Range StringRange,
5803// ArrayRef<FixItHint> Fixit = None);
5804
5805void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5806 unsigned flagLen) {
5807 // Warn about an empty flag.
5808 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5809 getLocationOfByte(startFlag),
5810 /*IsStringLocation*/true,
5811 getSpecifierRange(startFlag, flagLen));
5812}
5813
5814void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5815 unsigned flagLen) {
5816 // Warn about an invalid flag.
5817 auto Range = getSpecifierRange(startFlag, flagLen);
5818 StringRef flag(startFlag, flagLen);
5819 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5820 getLocationOfByte(startFlag),
5821 /*IsStringLocation*/true,
5822 Range, FixItHint::CreateRemoval(Range));
5823}
5824
5825void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5826 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5827 // Warn about using '[...]' without a '@' conversion.
5828 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5829 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5830 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5831 getLocationOfByte(conversionPosition),
5832 /*IsStringLocation*/true,
5833 Range, FixItHint::CreateRemoval(Range));
5834}
5835
Richard Smith55ce3522012-06-25 20:30:08 +00005836// Determines if the specified is a C++ class or struct containing
5837// a member with the specified name and kind (e.g. a CXXMethodDecl named
5838// "c_str()").
5839template<typename MemberKind>
5840static llvm::SmallPtrSet<MemberKind*, 1>
5841CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5842 const RecordType *RT = Ty->getAs<RecordType>();
5843 llvm::SmallPtrSet<MemberKind*, 1> Results;
5844
5845 if (!RT)
5846 return Results;
5847 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005848 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005849 return Results;
5850
Alp Tokerb6cc5922014-05-03 03:45:55 +00005851 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005852 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005853 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005854
5855 // We just need to include all members of the right kind turned up by the
5856 // filter, at this point.
5857 if (S.LookupQualifiedName(R, RT->getDecl()))
5858 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5859 NamedDecl *decl = (*I)->getUnderlyingDecl();
5860 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5861 Results.insert(FK);
5862 }
5863 return Results;
5864}
5865
Richard Smith2868a732014-02-28 01:36:39 +00005866/// Check if we could call '.c_str()' on an object.
5867///
5868/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5869/// allow the call, or if it would be ambiguous).
5870bool Sema::hasCStrMethod(const Expr *E) {
5871 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5872 MethodSet Results =
5873 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5874 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5875 MI != ME; ++MI)
5876 if ((*MI)->getMinRequiredArguments() == 0)
5877 return true;
5878 return false;
5879}
5880
Richard Smith55ce3522012-06-25 20:30:08 +00005881// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005882// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00005883// Returns true when a c_str() conversion method is found.
5884bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00005885 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00005886 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5887
5888 MethodSet Results =
5889 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5890
5891 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5892 MI != ME; ++MI) {
5893 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00005894 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00005895 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00005896 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00005897 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00005898 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5899 << "c_str()"
5900 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5901 return true;
5902 }
5903 }
5904
5905 return false;
5906}
5907
Ted Kremenekab278de2010-01-28 23:39:18 +00005908bool
Ted Kremenek02087932010-07-16 02:11:22 +00005909CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00005910 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00005911 const char *startSpecifier,
5912 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005913 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00005914 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005915 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00005916
Ted Kremenek6cd69422010-07-19 22:01:06 +00005917 if (FS.consumesDataArgument()) {
5918 if (atFirstArg) {
5919 atFirstArg = false;
5920 usesPositionalArgs = FS.usesPositionalArg();
5921 }
5922 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005923 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5924 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005925 return false;
5926 }
Ted Kremenek5739de72010-01-29 01:06:55 +00005927 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005928
Ted Kremenekd1668192010-02-27 01:41:03 +00005929 // First check if the field width, precision, and conversion specifier
5930 // have matching data arguments.
5931 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5932 startSpecifier, specifierLen)) {
5933 return false;
5934 }
5935
5936 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5937 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005938 return false;
5939 }
5940
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005941 if (!CS.consumesDataArgument()) {
5942 // FIXME: Technically specifying a precision or field width here
5943 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00005944 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005945 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005946
Ted Kremenek4a49d982010-02-26 19:18:41 +00005947 // Consume the argument.
5948 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00005949 if (argIndex < NumDataArgs) {
5950 // The check to see if the argIndex is valid will come later.
5951 // We set the bit here because we may exit early from this
5952 // function if we encounter some other error.
5953 CoveredArgs.set(argIndex);
5954 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00005955
Dimitry Andric6b5ed342015-02-19 22:32:33 +00005956 // FreeBSD kernel extensions.
5957 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5958 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5959 // We need at least two arguments.
5960 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5961 return false;
5962
5963 // Claim the second argument.
5964 CoveredArgs.set(argIndex + 1);
5965
5966 // Type check the first argument (int for %b, pointer for %D)
5967 const Expr *Ex = getDataArg(argIndex);
5968 const analyze_printf::ArgType &AT =
5969 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5970 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5971 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5972 EmitFormatDiagnostic(
5973 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5974 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5975 << false << Ex->getSourceRange(),
5976 Ex->getLocStart(), /*IsStringLocation*/false,
5977 getSpecifierRange(startSpecifier, specifierLen));
5978
5979 // Type check the second argument (char * for both %b and %D)
5980 Ex = getDataArg(argIndex + 1);
5981 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5982 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5983 EmitFormatDiagnostic(
5984 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5985 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5986 << false << Ex->getSourceRange(),
5987 Ex->getLocStart(), /*IsStringLocation*/false,
5988 getSpecifierRange(startSpecifier, specifierLen));
5989
5990 return true;
5991 }
5992
Ted Kremenek4a49d982010-02-26 19:18:41 +00005993 // Check for using an Objective-C specific conversion specifier
5994 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00005995 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00005996 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5997 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00005998 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005999
Mehdi Amini06d367c2016-10-24 20:39:34 +00006000 // %P can only be used with os_log.
6001 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6002 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6003 specifierLen);
6004 }
6005
6006 // %n is not allowed with os_log.
6007 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6008 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6009 getLocationOfByte(CS.getStart()),
6010 /*IsStringLocation*/ false,
6011 getSpecifierRange(startSpecifier, specifierLen));
6012
6013 return true;
6014 }
6015
6016 // Only scalars are allowed for os_trace.
6017 if (FSType == Sema::FST_OSTrace &&
6018 (CS.getKind() == ConversionSpecifier::PArg ||
6019 CS.getKind() == ConversionSpecifier::sArg ||
6020 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6021 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6022 specifierLen);
6023 }
6024
6025 // Check for use of public/private annotation outside of os_log().
6026 if (FSType != Sema::FST_OSLog) {
6027 if (FS.isPublic().isSet()) {
6028 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6029 << "public",
6030 getLocationOfByte(FS.isPublic().getPosition()),
6031 /*IsStringLocation*/ false,
6032 getSpecifierRange(startSpecifier, specifierLen));
6033 }
6034 if (FS.isPrivate().isSet()) {
6035 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6036 << "private",
6037 getLocationOfByte(FS.isPrivate().getPosition()),
6038 /*IsStringLocation*/ false,
6039 getSpecifierRange(startSpecifier, specifierLen));
6040 }
6041 }
6042
Tom Careb49ec692010-06-17 19:00:27 +00006043 // Check for invalid use of field width
6044 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00006045 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00006046 startSpecifier, specifierLen);
6047 }
6048
6049 // Check for invalid use of precision
6050 if (!FS.hasValidPrecision()) {
6051 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6052 startSpecifier, specifierLen);
6053 }
6054
Mehdi Amini06d367c2016-10-24 20:39:34 +00006055 // Precision is mandatory for %P specifier.
6056 if (CS.getKind() == ConversionSpecifier::PArg &&
6057 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6058 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6059 getLocationOfByte(startSpecifier),
6060 /*IsStringLocation*/ false,
6061 getSpecifierRange(startSpecifier, specifierLen));
6062 }
6063
Tom Careb49ec692010-06-17 19:00:27 +00006064 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00006065 if (!FS.hasValidThousandsGroupingPrefix())
6066 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006067 if (!FS.hasValidLeadingZeros())
6068 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6069 if (!FS.hasValidPlusPrefix())
6070 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00006071 if (!FS.hasValidSpacePrefix())
6072 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006073 if (!FS.hasValidAlternativeForm())
6074 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6075 if (!FS.hasValidLeftJustified())
6076 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6077
6078 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00006079 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6080 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6081 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006082 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6083 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6084 startSpecifier, specifierLen);
6085
6086 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006087 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006088 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6089 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006090 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006091 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006092 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006093 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6094 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00006095
Jordan Rose92303592012-09-08 04:00:03 +00006096 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6097 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6098
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006099 // The remaining checks depend on the data arguments.
6100 if (HasVAListArg)
6101 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006102
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006103 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006104 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006105
Jordan Rose58bbe422012-07-19 18:10:08 +00006106 const Expr *Arg = getDataArg(argIndex);
6107 if (!Arg)
6108 return true;
6109
6110 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00006111}
6112
Jordan Roseaee34382012-09-05 22:56:26 +00006113static bool requiresParensToAddCast(const Expr *E) {
6114 // FIXME: We should have a general way to reason about operator
6115 // precedence and whether parens are actually needed here.
6116 // Take care of a few common cases where they aren't.
6117 const Expr *Inside = E->IgnoreImpCasts();
6118 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6119 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6120
6121 switch (Inside->getStmtClass()) {
6122 case Stmt::ArraySubscriptExprClass:
6123 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006124 case Stmt::CharacterLiteralClass:
6125 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006126 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006127 case Stmt::FloatingLiteralClass:
6128 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006129 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006130 case Stmt::ObjCArrayLiteralClass:
6131 case Stmt::ObjCBoolLiteralExprClass:
6132 case Stmt::ObjCBoxedExprClass:
6133 case Stmt::ObjCDictionaryLiteralClass:
6134 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006135 case Stmt::ObjCIvarRefExprClass:
6136 case Stmt::ObjCMessageExprClass:
6137 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006138 case Stmt::ObjCStringLiteralClass:
6139 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006140 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006141 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006142 case Stmt::UnaryOperatorClass:
6143 return false;
6144 default:
6145 return true;
6146 }
6147}
6148
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006149static std::pair<QualType, StringRef>
6150shouldNotPrintDirectly(const ASTContext &Context,
6151 QualType IntendedTy,
6152 const Expr *E) {
6153 // Use a 'while' to peel off layers of typedefs.
6154 QualType TyTy = IntendedTy;
6155 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6156 StringRef Name = UserTy->getDecl()->getName();
6157 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Alexander Shaposhnikov62351372017-06-26 23:02:27 +00006158 .Case("CFIndex", Context.LongTy)
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006159 .Case("NSInteger", Context.LongTy)
6160 .Case("NSUInteger", Context.UnsignedLongTy)
6161 .Case("SInt32", Context.IntTy)
6162 .Case("UInt32", Context.UnsignedIntTy)
6163 .Default(QualType());
6164
6165 if (!CastTy.isNull())
6166 return std::make_pair(CastTy, Name);
6167
6168 TyTy = UserTy->desugar();
6169 }
6170
6171 // Strip parens if necessary.
6172 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6173 return shouldNotPrintDirectly(Context,
6174 PE->getSubExpr()->getType(),
6175 PE->getSubExpr());
6176
6177 // If this is a conditional expression, then its result type is constructed
6178 // via usual arithmetic conversions and thus there might be no necessary
6179 // typedef sugar there. Recurse to operands to check for NSInteger &
6180 // Co. usage condition.
6181 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6182 QualType TrueTy, FalseTy;
6183 StringRef TrueName, FalseName;
6184
6185 std::tie(TrueTy, TrueName) =
6186 shouldNotPrintDirectly(Context,
6187 CO->getTrueExpr()->getType(),
6188 CO->getTrueExpr());
6189 std::tie(FalseTy, FalseName) =
6190 shouldNotPrintDirectly(Context,
6191 CO->getFalseExpr()->getType(),
6192 CO->getFalseExpr());
6193
6194 if (TrueTy == FalseTy)
6195 return std::make_pair(TrueTy, TrueName);
6196 else if (TrueTy.isNull())
6197 return std::make_pair(FalseTy, FalseName);
6198 else if (FalseTy.isNull())
6199 return std::make_pair(TrueTy, TrueName);
6200 }
6201
6202 return std::make_pair(QualType(), StringRef());
6203}
6204
Richard Smith55ce3522012-06-25 20:30:08 +00006205bool
6206CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6207 const char *StartSpecifier,
6208 unsigned SpecifierLen,
6209 const Expr *E) {
6210 using namespace analyze_format_string;
6211 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006212 // Now type check the data expression that matches the
6213 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006214 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00006215 if (!AT.isValid())
6216 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00006217
Jordan Rose598ec092012-12-05 18:44:40 +00006218 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00006219 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6220 ExprTy = TET->getUnderlyingExpr()->getType();
6221 }
6222
Seth Cantrellb4802962015-03-04 03:12:10 +00006223 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6224
6225 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00006226 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006227 }
Jordan Rose98709982012-06-04 22:48:57 +00006228
Jordan Rose22b74712012-09-05 22:56:19 +00006229 // Look through argument promotions for our error message's reported type.
6230 // This includes the integral and floating promotions, but excludes array
6231 // and function pointer decay; seeing that an argument intended to be a
6232 // string has type 'char [6]' is probably more confusing than 'char *'.
6233 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6234 if (ICE->getCastKind() == CK_IntegralCast ||
6235 ICE->getCastKind() == CK_FloatingCast) {
6236 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006237 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006238
6239 // Check if we didn't match because of an implicit cast from a 'char'
6240 // or 'short' to an 'int'. This is done because printf is a varargs
6241 // function.
6242 if (ICE->getType() == S.Context.IntTy ||
6243 ICE->getType() == S.Context.UnsignedIntTy) {
6244 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006245 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006246 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006247 }
Jordan Rose98709982012-06-04 22:48:57 +00006248 }
Jordan Rose598ec092012-12-05 18:44:40 +00006249 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6250 // Special case for 'a', which has type 'int' in C.
6251 // Note, however, that we do /not/ want to treat multibyte constants like
6252 // 'MooV' as characters! This form is deprecated but still exists.
6253 if (ExprTy == S.Context.IntTy)
6254 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6255 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006256 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006257
Jordan Rosebc53ed12014-05-31 04:12:14 +00006258 // Look through enums to their underlying type.
6259 bool IsEnum = false;
6260 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6261 ExprTy = EnumTy->getDecl()->getIntegerType();
6262 IsEnum = true;
6263 }
6264
Jordan Rose0e5badd2012-12-05 18:44:49 +00006265 // %C in an Objective-C context prints a unichar, not a wchar_t.
6266 // If the argument is an integer of some kind, believe the %C and suggest
6267 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006268 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006269 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006270 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6271 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6272 !ExprTy->isCharType()) {
6273 // 'unichar' is defined as a typedef of unsigned short, but we should
6274 // prefer using the typedef if it is visible.
6275 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006276
6277 // While we are here, check if the value is an IntegerLiteral that happens
6278 // to be within the valid range.
6279 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6280 const llvm::APInt &V = IL->getValue();
6281 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6282 return true;
6283 }
6284
Jordan Rose0e5badd2012-12-05 18:44:49 +00006285 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6286 Sema::LookupOrdinaryName);
6287 if (S.LookupName(Result, S.getCurScope())) {
6288 NamedDecl *ND = Result.getFoundDecl();
6289 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6290 if (TD->getUnderlyingType() == IntendedTy)
6291 IntendedTy = S.Context.getTypedefType(TD);
6292 }
6293 }
6294 }
6295
6296 // Special-case some of Darwin's platform-independence types by suggesting
6297 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006298 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006299 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006300 QualType CastTy;
6301 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6302 if (!CastTy.isNull()) {
6303 IntendedTy = CastTy;
6304 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006305 }
6306 }
6307
Jordan Rose22b74712012-09-05 22:56:19 +00006308 // We may be able to offer a FixItHint if it is a supported type.
6309 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006310 bool success =
6311 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006312
Jordan Rose22b74712012-09-05 22:56:19 +00006313 if (success) {
6314 // Get the fix string from the fixed format specifier
6315 SmallString<16> buf;
6316 llvm::raw_svector_ostream os(buf);
6317 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006318
Jordan Roseaee34382012-09-05 22:56:26 +00006319 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6320
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006321 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00006322 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6323 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6324 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6325 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00006326 // In this case, the specifier is wrong and should be changed to match
6327 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006328 EmitFormatDiagnostic(S.PDiag(diag)
6329 << AT.getRepresentativeTypeName(S.Context)
6330 << IntendedTy << IsEnum << E->getSourceRange(),
6331 E->getLocStart(),
6332 /*IsStringLocation*/ false, SpecRange,
6333 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006334 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006335 // The canonical type for formatting this value is different from the
6336 // actual type of the expression. (This occurs, for example, with Darwin's
6337 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6338 // should be printed as 'long' for 64-bit compatibility.)
6339 // Rather than emitting a normal format/argument mismatch, we want to
6340 // add a cast to the recommended type (and correct the format string
6341 // if necessary).
6342 SmallString<16> CastBuf;
6343 llvm::raw_svector_ostream CastFix(CastBuf);
6344 CastFix << "(";
6345 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6346 CastFix << ")";
6347
6348 SmallVector<FixItHint,4> Hints;
Alexander Shaposhnikov1788a9b2017-09-22 18:36:06 +00006349 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
Jordan Roseaee34382012-09-05 22:56:26 +00006350 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6351
6352 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6353 // If there's already a cast present, just replace it.
6354 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6355 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6356
6357 } else if (!requiresParensToAddCast(E)) {
6358 // If the expression has high enough precedence,
6359 // just write the C-style cast.
6360 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6361 CastFix.str()));
6362 } else {
6363 // Otherwise, add parens around the expression as well as the cast.
6364 CastFix << "(";
6365 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6366 CastFix.str()));
6367
Alp Tokerb6cc5922014-05-03 03:45:55 +00006368 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006369 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6370 }
6371
Jordan Rose0e5badd2012-12-05 18:44:49 +00006372 if (ShouldNotPrintDirectly) {
6373 // The expression has a type that should not be printed directly.
6374 // We extract the name from the typedef because we don't want to show
6375 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006376 StringRef Name;
6377 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6378 Name = TypedefTy->getDecl()->getName();
6379 else
6380 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006381 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006382 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006383 << E->getSourceRange(),
6384 E->getLocStart(), /*IsStringLocation=*/false,
6385 SpecRange, Hints);
6386 } else {
6387 // In this case, the expression could be printed using a different
6388 // specifier, but we've decided that the specifier is probably correct
6389 // and we should cast instead. Just use the normal warning message.
6390 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006391 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6392 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006393 << E->getSourceRange(),
6394 E->getLocStart(), /*IsStringLocation*/false,
6395 SpecRange, Hints);
6396 }
Jordan Roseaee34382012-09-05 22:56:26 +00006397 }
Jordan Rose22b74712012-09-05 22:56:19 +00006398 } else {
6399 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6400 SpecifierLen);
6401 // Since the warning for passing non-POD types to variadic functions
6402 // was deferred until now, we emit a warning for non-POD
6403 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006404 switch (S.isValidVarArgType(ExprTy)) {
6405 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006406 case Sema::VAK_ValidInCXX11: {
6407 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6408 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6409 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6410 }
Richard Smithd7293d72013-08-05 18:49:43 +00006411
Seth Cantrellb4802962015-03-04 03:12:10 +00006412 EmitFormatDiagnostic(
6413 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6414 << IsEnum << CSR << E->getSourceRange(),
6415 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6416 break;
6417 }
Richard Smithd7293d72013-08-05 18:49:43 +00006418 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006419 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006420 EmitFormatDiagnostic(
6421 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006422 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006423 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006424 << CallType
6425 << AT.getRepresentativeTypeName(S.Context)
6426 << CSR
6427 << E->getSourceRange(),
6428 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006429 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006430 break;
6431
6432 case Sema::VAK_Invalid:
6433 if (ExprTy->isObjCObjectType())
6434 EmitFormatDiagnostic(
6435 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6436 << S.getLangOpts().CPlusPlus11
6437 << ExprTy
6438 << CallType
6439 << AT.getRepresentativeTypeName(S.Context)
6440 << CSR
6441 << E->getSourceRange(),
6442 E->getLocStart(), /*IsStringLocation*/false, CSR);
6443 else
6444 // FIXME: If this is an initializer list, suggest removing the braces
6445 // or inserting a cast to the target type.
6446 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6447 << isa<InitListExpr>(E) << ExprTy << CallType
6448 << AT.getRepresentativeTypeName(S.Context)
6449 << E->getSourceRange();
6450 break;
6451 }
6452
6453 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6454 "format string specifier index out of range");
6455 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006456 }
6457
Ted Kremenekab278de2010-01-28 23:39:18 +00006458 return true;
6459}
6460
Ted Kremenek02087932010-07-16 02:11:22 +00006461//===--- CHECK: Scanf format string checking ------------------------------===//
6462
6463namespace {
6464class CheckScanfHandler : public CheckFormatHandler {
6465public:
Stephen Hines648c3692016-09-16 01:07:04 +00006466 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006467 const Expr *origFormatExpr, Sema::FormatStringType type,
6468 unsigned firstDataArg, unsigned numDataArgs,
6469 const char *beg, bool hasVAListArg,
6470 ArrayRef<const Expr *> Args, unsigned formatIdx,
6471 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006472 llvm::SmallBitVector &CheckedVarArgs,
6473 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006474 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6475 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6476 inFunctionCall, CallType, CheckedVarArgs,
6477 UncoveredArg) {}
6478
Ted Kremenek02087932010-07-16 02:11:22 +00006479 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6480 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006481 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006482
6483 bool HandleInvalidScanfConversionSpecifier(
6484 const analyze_scanf::ScanfSpecifier &FS,
6485 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006486 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006487
Craig Toppere14c0f82014-03-12 04:55:44 +00006488 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006489};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006490} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006491
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006492void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6493 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006494 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6495 getLocationOfByte(end), /*IsStringLocation*/true,
6496 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006497}
6498
Ted Kremenekce815422010-07-19 21:25:57 +00006499bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6500 const analyze_scanf::ScanfSpecifier &FS,
6501 const char *startSpecifier,
6502 unsigned specifierLen) {
6503
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006504 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006505 FS.getConversionSpecifier();
6506
6507 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6508 getLocationOfByte(CS.getStart()),
6509 startSpecifier, specifierLen,
6510 CS.getStart(), CS.getLength());
6511}
6512
Ted Kremenek02087932010-07-16 02:11:22 +00006513bool CheckScanfHandler::HandleScanfSpecifier(
6514 const analyze_scanf::ScanfSpecifier &FS,
6515 const char *startSpecifier,
6516 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006517 using namespace analyze_scanf;
6518 using namespace analyze_format_string;
6519
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006520 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006521
Ted Kremenek6cd69422010-07-19 22:01:06 +00006522 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6523 // be used to decide if we are using positional arguments consistently.
6524 if (FS.consumesDataArgument()) {
6525 if (atFirstArg) {
6526 atFirstArg = false;
6527 usesPositionalArgs = FS.usesPositionalArg();
6528 }
6529 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006530 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6531 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006532 return false;
6533 }
Ted Kremenek02087932010-07-16 02:11:22 +00006534 }
6535
6536 // Check if the field with is non-zero.
6537 const OptionalAmount &Amt = FS.getFieldWidth();
6538 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6539 if (Amt.getConstantAmount() == 0) {
6540 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6541 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006542 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6543 getLocationOfByte(Amt.getStart()),
6544 /*IsStringLocation*/true, R,
6545 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006546 }
6547 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006548
Ted Kremenek02087932010-07-16 02:11:22 +00006549 if (!FS.consumesDataArgument()) {
6550 // FIXME: Technically specifying a precision or field width here
6551 // makes no sense. Worth issuing a warning at some point.
6552 return true;
6553 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006554
Ted Kremenek02087932010-07-16 02:11:22 +00006555 // Consume the argument.
6556 unsigned argIndex = FS.getArgIndex();
6557 if (argIndex < NumDataArgs) {
6558 // The check to see if the argIndex is valid will come later.
6559 // We set the bit here because we may exit early from this
6560 // function if we encounter some other error.
6561 CoveredArgs.set(argIndex);
6562 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006563
Ted Kremenek4407ea42010-07-20 20:04:47 +00006564 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006565 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006566 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6567 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006568 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006569 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006570 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006571 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6572 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006573
Jordan Rose92303592012-09-08 04:00:03 +00006574 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6575 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6576
Ted Kremenek02087932010-07-16 02:11:22 +00006577 // The remaining checks depend on the data arguments.
6578 if (HasVAListArg)
6579 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006580
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006581 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006582 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006583
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006584 // Check that the argument type matches the format specifier.
6585 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006586 if (!Ex)
6587 return true;
6588
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006589 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006590
6591 if (!AT.isValid()) {
6592 return true;
6593 }
6594
Seth Cantrellb4802962015-03-04 03:12:10 +00006595 analyze_format_string::ArgType::MatchKind match =
6596 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006597 if (match == analyze_format_string::ArgType::Match) {
6598 return true;
6599 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006600
Seth Cantrell79340072015-03-04 05:58:08 +00006601 ScanfSpecifier fixedFS = FS;
6602 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6603 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006604
Seth Cantrell79340072015-03-04 05:58:08 +00006605 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6606 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6607 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6608 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006609
Seth Cantrell79340072015-03-04 05:58:08 +00006610 if (success) {
6611 // Get the fix string from the fixed format specifier.
6612 SmallString<128> buf;
6613 llvm::raw_svector_ostream os(buf);
6614 fixedFS.toString(os);
6615
6616 EmitFormatDiagnostic(
6617 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6618 << Ex->getType() << false << Ex->getSourceRange(),
6619 Ex->getLocStart(),
6620 /*IsStringLocation*/ false,
6621 getSpecifierRange(startSpecifier, specifierLen),
6622 FixItHint::CreateReplacement(
6623 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6624 } else {
6625 EmitFormatDiagnostic(S.PDiag(diag)
6626 << AT.getRepresentativeTypeName(S.Context)
6627 << Ex->getType() << false << Ex->getSourceRange(),
6628 Ex->getLocStart(),
6629 /*IsStringLocation*/ false,
6630 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006631 }
6632
Ted Kremenek02087932010-07-16 02:11:22 +00006633 return true;
6634}
6635
Stephen Hines648c3692016-09-16 01:07:04 +00006636static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006637 const Expr *OrigFormatExpr,
6638 ArrayRef<const Expr *> Args,
6639 bool HasVAListArg, unsigned format_idx,
6640 unsigned firstDataArg,
6641 Sema::FormatStringType Type,
6642 bool inFunctionCall,
6643 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006644 llvm::SmallBitVector &CheckedVarArgs,
6645 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00006646 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00006647 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006648 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006649 S, inFunctionCall, Args[format_idx],
6650 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006651 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006652 return;
6653 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006654
Ted Kremenekab278de2010-01-28 23:39:18 +00006655 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006656 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00006657 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006658 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006659 const ConstantArrayType *T =
6660 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006661 assert(T && "String literal not of constant array type!");
6662 size_t TypeSize = T->getSize().getZExtValue();
6663 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006664 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006665
6666 // Emit a warning if the string literal is truncated and does not contain an
6667 // embedded null character.
6668 if (TypeSize <= StrRef.size() &&
6669 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6670 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006671 S, inFunctionCall, Args[format_idx],
6672 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006673 FExpr->getLocStart(),
6674 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6675 return;
6676 }
6677
Ted Kremenekab278de2010-01-28 23:39:18 +00006678 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006679 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006680 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006681 S, inFunctionCall, Args[format_idx],
6682 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006683 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006684 return;
6685 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006686
6687 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00006688 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6689 Type == Sema::FST_OSTrace) {
6690 CheckPrintfHandler H(
6691 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6692 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6693 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6694 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006695
Hans Wennborg23926bd2011-12-15 10:25:47 +00006696 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006697 S.getLangOpts(),
6698 S.Context.getTargetInfo(),
6699 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006700 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006701 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00006702 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6703 numDataArgs, Str, HasVAListArg, Args, format_idx,
6704 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006705
Hans Wennborg23926bd2011-12-15 10:25:47 +00006706 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006707 S.getLangOpts(),
6708 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006709 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006710 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006711}
6712
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006713bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6714 // Str - The format string. NOTE: this is NOT null-terminated!
6715 StringRef StrRef = FExpr->getString();
6716 const char *Str = StrRef.data();
6717 // Account for cases where the string literal is truncated in a declaration.
6718 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6719 assert(T && "String literal not of constant array type!");
6720 size_t TypeSize = T->getSize().getZExtValue();
6721 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6722 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6723 getLangOpts(),
6724 Context.getTargetInfo());
6725}
6726
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006727//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6728
6729// Returns the related absolute value function that is larger, of 0 if one
6730// does not exist.
6731static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6732 switch (AbsFunction) {
6733 default:
6734 return 0;
6735
6736 case Builtin::BI__builtin_abs:
6737 return Builtin::BI__builtin_labs;
6738 case Builtin::BI__builtin_labs:
6739 return Builtin::BI__builtin_llabs;
6740 case Builtin::BI__builtin_llabs:
6741 return 0;
6742
6743 case Builtin::BI__builtin_fabsf:
6744 return Builtin::BI__builtin_fabs;
6745 case Builtin::BI__builtin_fabs:
6746 return Builtin::BI__builtin_fabsl;
6747 case Builtin::BI__builtin_fabsl:
6748 return 0;
6749
6750 case Builtin::BI__builtin_cabsf:
6751 return Builtin::BI__builtin_cabs;
6752 case Builtin::BI__builtin_cabs:
6753 return Builtin::BI__builtin_cabsl;
6754 case Builtin::BI__builtin_cabsl:
6755 return 0;
6756
6757 case Builtin::BIabs:
6758 return Builtin::BIlabs;
6759 case Builtin::BIlabs:
6760 return Builtin::BIllabs;
6761 case Builtin::BIllabs:
6762 return 0;
6763
6764 case Builtin::BIfabsf:
6765 return Builtin::BIfabs;
6766 case Builtin::BIfabs:
6767 return Builtin::BIfabsl;
6768 case Builtin::BIfabsl:
6769 return 0;
6770
6771 case Builtin::BIcabsf:
6772 return Builtin::BIcabs;
6773 case Builtin::BIcabs:
6774 return Builtin::BIcabsl;
6775 case Builtin::BIcabsl:
6776 return 0;
6777 }
6778}
6779
6780// Returns the argument type of the absolute value function.
6781static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6782 unsigned AbsType) {
6783 if (AbsType == 0)
6784 return QualType();
6785
6786 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6787 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6788 if (Error != ASTContext::GE_None)
6789 return QualType();
6790
6791 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6792 if (!FT)
6793 return QualType();
6794
6795 if (FT->getNumParams() != 1)
6796 return QualType();
6797
6798 return FT->getParamType(0);
6799}
6800
6801// Returns the best absolute value function, or zero, based on type and
6802// current absolute value function.
6803static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6804 unsigned AbsFunctionKind) {
6805 unsigned BestKind = 0;
6806 uint64_t ArgSize = Context.getTypeSize(ArgType);
6807 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6808 Kind = getLargerAbsoluteValueFunction(Kind)) {
6809 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6810 if (Context.getTypeSize(ParamType) >= ArgSize) {
6811 if (BestKind == 0)
6812 BestKind = Kind;
6813 else if (Context.hasSameType(ParamType, ArgType)) {
6814 BestKind = Kind;
6815 break;
6816 }
6817 }
6818 }
6819 return BestKind;
6820}
6821
6822enum AbsoluteValueKind {
6823 AVK_Integer,
6824 AVK_Floating,
6825 AVK_Complex
6826};
6827
6828static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6829 if (T->isIntegralOrEnumerationType())
6830 return AVK_Integer;
6831 if (T->isRealFloatingType())
6832 return AVK_Floating;
6833 if (T->isAnyComplexType())
6834 return AVK_Complex;
6835
6836 llvm_unreachable("Type not integer, floating, or complex");
6837}
6838
6839// Changes the absolute value function to a different type. Preserves whether
6840// the function is a builtin.
6841static unsigned changeAbsFunction(unsigned AbsKind,
6842 AbsoluteValueKind ValueKind) {
6843 switch (ValueKind) {
6844 case AVK_Integer:
6845 switch (AbsKind) {
6846 default:
6847 return 0;
6848 case Builtin::BI__builtin_fabsf:
6849 case Builtin::BI__builtin_fabs:
6850 case Builtin::BI__builtin_fabsl:
6851 case Builtin::BI__builtin_cabsf:
6852 case Builtin::BI__builtin_cabs:
6853 case Builtin::BI__builtin_cabsl:
6854 return Builtin::BI__builtin_abs;
6855 case Builtin::BIfabsf:
6856 case Builtin::BIfabs:
6857 case Builtin::BIfabsl:
6858 case Builtin::BIcabsf:
6859 case Builtin::BIcabs:
6860 case Builtin::BIcabsl:
6861 return Builtin::BIabs;
6862 }
6863 case AVK_Floating:
6864 switch (AbsKind) {
6865 default:
6866 return 0;
6867 case Builtin::BI__builtin_abs:
6868 case Builtin::BI__builtin_labs:
6869 case Builtin::BI__builtin_llabs:
6870 case Builtin::BI__builtin_cabsf:
6871 case Builtin::BI__builtin_cabs:
6872 case Builtin::BI__builtin_cabsl:
6873 return Builtin::BI__builtin_fabsf;
6874 case Builtin::BIabs:
6875 case Builtin::BIlabs:
6876 case Builtin::BIllabs:
6877 case Builtin::BIcabsf:
6878 case Builtin::BIcabs:
6879 case Builtin::BIcabsl:
6880 return Builtin::BIfabsf;
6881 }
6882 case AVK_Complex:
6883 switch (AbsKind) {
6884 default:
6885 return 0;
6886 case Builtin::BI__builtin_abs:
6887 case Builtin::BI__builtin_labs:
6888 case Builtin::BI__builtin_llabs:
6889 case Builtin::BI__builtin_fabsf:
6890 case Builtin::BI__builtin_fabs:
6891 case Builtin::BI__builtin_fabsl:
6892 return Builtin::BI__builtin_cabsf;
6893 case Builtin::BIabs:
6894 case Builtin::BIlabs:
6895 case Builtin::BIllabs:
6896 case Builtin::BIfabsf:
6897 case Builtin::BIfabs:
6898 case Builtin::BIfabsl:
6899 return Builtin::BIcabsf;
6900 }
6901 }
6902 llvm_unreachable("Unable to convert function");
6903}
6904
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006905static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006906 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6907 if (!FnInfo)
6908 return 0;
6909
6910 switch (FDecl->getBuiltinID()) {
6911 default:
6912 return 0;
6913 case Builtin::BI__builtin_abs:
6914 case Builtin::BI__builtin_fabs:
6915 case Builtin::BI__builtin_fabsf:
6916 case Builtin::BI__builtin_fabsl:
6917 case Builtin::BI__builtin_labs:
6918 case Builtin::BI__builtin_llabs:
6919 case Builtin::BI__builtin_cabs:
6920 case Builtin::BI__builtin_cabsf:
6921 case Builtin::BI__builtin_cabsl:
6922 case Builtin::BIabs:
6923 case Builtin::BIlabs:
6924 case Builtin::BIllabs:
6925 case Builtin::BIfabs:
6926 case Builtin::BIfabsf:
6927 case Builtin::BIfabsl:
6928 case Builtin::BIcabs:
6929 case Builtin::BIcabsf:
6930 case Builtin::BIcabsl:
6931 return FDecl->getBuiltinID();
6932 }
6933 llvm_unreachable("Unknown Builtin type");
6934}
6935
6936// If the replacement is valid, emit a note with replacement function.
6937// Additionally, suggest including the proper header if not already included.
6938static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00006939 unsigned AbsKind, QualType ArgType) {
6940 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006941 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00006942 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006943 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6944 FunctionName = "std::abs";
6945 if (ArgType->isIntegralOrEnumerationType()) {
6946 HeaderName = "cstdlib";
6947 } else if (ArgType->isRealFloatingType()) {
6948 HeaderName = "cmath";
6949 } else {
6950 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006951 }
Richard Trieubeffb832014-04-15 23:47:53 +00006952
6953 // Lookup all std::abs
6954 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00006955 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00006956 R.suppressDiagnostics();
6957 S.LookupQualifiedName(R, Std);
6958
6959 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006960 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006961 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6962 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6963 } else {
6964 FDecl = dyn_cast<FunctionDecl>(I);
6965 }
6966 if (!FDecl)
6967 continue;
6968
6969 // Found std::abs(), check that they are the right ones.
6970 if (FDecl->getNumParams() != 1)
6971 continue;
6972
6973 // Check that the parameter type can handle the argument.
6974 QualType ParamType = FDecl->getParamDecl(0)->getType();
6975 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6976 S.Context.getTypeSize(ArgType) <=
6977 S.Context.getTypeSize(ParamType)) {
6978 // Found a function, don't need the header hint.
6979 EmitHeaderHint = false;
6980 break;
6981 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006982 }
Richard Trieubeffb832014-04-15 23:47:53 +00006983 }
6984 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00006985 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00006986 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6987
6988 if (HeaderName) {
6989 DeclarationName DN(&S.Context.Idents.get(FunctionName));
6990 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6991 R.suppressDiagnostics();
6992 S.LookupName(R, S.getCurScope());
6993
6994 if (R.isSingleResult()) {
6995 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6996 if (FD && FD->getBuiltinID() == AbsKind) {
6997 EmitHeaderHint = false;
6998 } else {
6999 return;
7000 }
7001 } else if (!R.empty()) {
7002 return;
7003 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007004 }
7005 }
7006
7007 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00007008 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007009
Richard Trieubeffb832014-04-15 23:47:53 +00007010 if (!HeaderName)
7011 return;
7012
7013 if (!EmitHeaderHint)
7014 return;
7015
Alp Toker5d96e0a2014-07-11 20:53:51 +00007016 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7017 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00007018}
7019
Richard Trieua7f30b12016-12-06 01:42:28 +00007020template <std::size_t StrLen>
7021static bool IsStdFunction(const FunctionDecl *FDecl,
7022 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00007023 if (!FDecl)
7024 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007025 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00007026 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007027 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00007028 return false;
7029
7030 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007031}
7032
7033// Warn when using the wrong abs() function.
7034void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00007035 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007036 if (Call->getNumArgs() != 1)
7037 return;
7038
7039 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00007040 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00007041 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007042 return;
7043
7044 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7045 QualType ParamType = Call->getArg(0)->getType();
7046
Alp Toker5d96e0a2014-07-11 20:53:51 +00007047 // Unsigned types cannot be negative. Suggest removing the absolute value
7048 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007049 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00007050 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00007051 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007052 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7053 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00007054 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007055 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7056 return;
7057 }
7058
David Majnemer7f77eb92015-11-15 03:04:34 +00007059 // Taking the absolute value of a pointer is very suspicious, they probably
7060 // wanted to index into an array, dereference a pointer, call a function, etc.
7061 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7062 unsigned DiagType = 0;
7063 if (ArgType->isFunctionType())
7064 DiagType = 1;
7065 else if (ArgType->isArrayType())
7066 DiagType = 2;
7067
7068 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7069 return;
7070 }
7071
Richard Trieubeffb832014-04-15 23:47:53 +00007072 // std::abs has overloads which prevent most of the absolute value problems
7073 // from occurring.
7074 if (IsStdAbs)
7075 return;
7076
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007077 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7078 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7079
7080 // The argument and parameter are the same kind. Check if they are the right
7081 // size.
7082 if (ArgValueKind == ParamValueKind) {
7083 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7084 return;
7085
7086 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7087 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7088 << FDecl << ArgType << ParamType;
7089
7090 if (NewAbsKind == 0)
7091 return;
7092
7093 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007094 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007095 return;
7096 }
7097
7098 // ArgValueKind != ParamValueKind
7099 // The wrong type of absolute value function was used. Attempt to find the
7100 // proper one.
7101 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7102 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7103 if (NewAbsKind == 0)
7104 return;
7105
7106 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7107 << FDecl << ParamValueKind << ArgValueKind;
7108
7109 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007110 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007111}
7112
Richard Trieu67c00712016-12-05 23:41:46 +00007113//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00007114void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7115 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00007116 if (!Call || !FDecl) return;
7117
7118 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00007119 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007120 if (Call->getExprLoc().isMacroID()) return;
7121
7122 // Only care about the one template argument, two function parameter std::max
7123 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00007124 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007125 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7126 if (!ArgList) return;
7127 if (ArgList->size() != 1) return;
7128
7129 // Check that template type argument is unsigned integer.
7130 const auto& TA = ArgList->get(0);
7131 if (TA.getKind() != TemplateArgument::Type) return;
7132 QualType ArgType = TA.getAsType();
7133 if (!ArgType->isUnsignedIntegerType()) return;
7134
7135 // See if either argument is a literal zero.
7136 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7137 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7138 if (!MTE) return false;
7139 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7140 if (!Num) return false;
7141 if (Num->getValue() != 0) return false;
7142 return true;
7143 };
7144
7145 const Expr *FirstArg = Call->getArg(0);
7146 const Expr *SecondArg = Call->getArg(1);
7147 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7148 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7149
7150 // Only warn when exactly one argument is zero.
7151 if (IsFirstArgZero == IsSecondArgZero) return;
7152
7153 SourceRange FirstRange = FirstArg->getSourceRange();
7154 SourceRange SecondRange = SecondArg->getSourceRange();
7155
7156 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7157
7158 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7159 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7160
7161 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7162 SourceRange RemovalRange;
7163 if (IsFirstArgZero) {
7164 RemovalRange = SourceRange(FirstRange.getBegin(),
7165 SecondRange.getBegin().getLocWithOffset(-1));
7166 } else {
7167 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7168 SecondRange.getEnd());
7169 }
7170
7171 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7172 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7173 << FixItHint::CreateRemoval(RemovalRange);
7174}
7175
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007176//===--- CHECK: Standard memory functions ---------------------------------===//
7177
Nico Weber0e6daef2013-12-26 23:38:39 +00007178/// \brief Takes the expression passed to the size_t parameter of functions
7179/// such as memcmp, strncat, etc and warns if it's a comparison.
7180///
7181/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7182static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7183 IdentifierInfo *FnName,
7184 SourceLocation FnLoc,
7185 SourceLocation RParenLoc) {
7186 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7187 if (!Size)
7188 return false;
7189
7190 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
7191 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
7192 return false;
7193
Nico Weber0e6daef2013-12-26 23:38:39 +00007194 SourceRange SizeRange = Size->getSourceRange();
7195 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7196 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00007197 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007198 << FnName << FixItHint::CreateInsertion(
7199 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00007200 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00007201 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00007202 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00007203 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7204 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00007205
7206 return true;
7207}
7208
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007209/// \brief Determine whether the given type is or contains a dynamic class type
7210/// (e.g., whether it has a vtable).
7211static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7212 bool &IsContained) {
7213 // Look through array types while ignoring qualifiers.
7214 const Type *Ty = T->getBaseElementTypeUnsafe();
7215 IsContained = false;
7216
7217 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7218 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00007219 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007220 return nullptr;
7221
7222 if (RD->isDynamicClass())
7223 return RD;
7224
7225 // Check all the fields. If any bases were dynamic, the class is dynamic.
7226 // It's impossible for a class to transitively contain itself by value, so
7227 // infinite recursion is impossible.
7228 for (auto *FD : RD->fields()) {
7229 bool SubContained;
7230 if (const CXXRecordDecl *ContainedRD =
7231 getContainedDynamicClass(FD->getType(), SubContained)) {
7232 IsContained = true;
7233 return ContainedRD;
7234 }
7235 }
7236
7237 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007238}
7239
Chandler Carruth889ed862011-06-21 23:04:20 +00007240/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007241/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007242static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007243 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007244 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7245 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
7246 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007247
Craig Topperc3ec1492014-05-26 06:22:03 +00007248 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007249}
7250
Chandler Carruth889ed862011-06-21 23:04:20 +00007251/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007252static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007253 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7254 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7255 if (SizeOf->getKind() == clang::UETT_SizeOf)
7256 return SizeOf->getTypeOfArgument();
7257
7258 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007259}
7260
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007261/// \brief Check for dangerous or invalid arguments to memset().
7262///
Chandler Carruthac687262011-06-03 06:23:57 +00007263/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007264/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7265/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007266///
7267/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007268void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007269 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007270 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007271 assert(BId != 0);
7272
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007273 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007274 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007275 unsigned ExpectedNumArgs =
7276 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007277 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007278 return;
7279
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007280 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007281 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007282 unsigned LenArg =
7283 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007284 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007285
Nico Weber0e6daef2013-12-26 23:38:39 +00007286 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7287 Call->getLocStart(), Call->getRParenLoc()))
7288 return;
7289
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007290 // We have special checking when the length is a sizeof expression.
7291 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7292 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7293 llvm::FoldingSetNodeID SizeOfArgID;
7294
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007295 // Although widely used, 'bzero' is not a standard function. Be more strict
7296 // with the argument types before allowing diagnostics and only allow the
7297 // form bzero(ptr, sizeof(...)).
7298 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7299 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7300 return;
7301
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007302 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7303 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007304 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007305
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007306 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007307 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007308 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007309 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007310
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007311 // Never warn about void type pointers. This can be used to suppress
7312 // false positives.
7313 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007314 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007315
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007316 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7317 // actually comparing the expressions for equality. Because computing the
7318 // expression IDs can be expensive, we only do this if the diagnostic is
7319 // enabled.
7320 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007321 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7322 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007323 // We only compute IDs for expressions if the warning is enabled, and
7324 // cache the sizeof arg's ID.
7325 if (SizeOfArgID == llvm::FoldingSetNodeID())
7326 SizeOfArg->Profile(SizeOfArgID, Context, true);
7327 llvm::FoldingSetNodeID DestID;
7328 Dest->Profile(DestID, Context, true);
7329 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007330 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7331 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007332 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007333 StringRef ReadableName = FnName->getName();
7334
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007335 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007336 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007337 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007338 if (!PointeeTy->isIncompleteType() &&
7339 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007340 ActionIdx = 2; // If the pointee's size is sizeof(char),
7341 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007342
7343 // If the function is defined as a builtin macro, do not show macro
7344 // expansion.
7345 SourceLocation SL = SizeOfArg->getExprLoc();
7346 SourceRange DSR = Dest->getSourceRange();
7347 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007348 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007349
7350 if (SM.isMacroArgExpansion(SL)) {
7351 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7352 SL = SM.getSpellingLoc(SL);
7353 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7354 SM.getSpellingLoc(DSR.getEnd()));
7355 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7356 SM.getSpellingLoc(SSR.getEnd()));
7357 }
7358
Anna Zaksd08d9152012-05-30 23:14:52 +00007359 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007360 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007361 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007362 << PointeeTy
7363 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007364 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007365 << SSR);
7366 DiagRuntimeBehavior(SL, SizeOfArg,
7367 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7368 << ActionIdx
7369 << SSR);
7370
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007371 break;
7372 }
7373 }
7374
7375 // Also check for cases where the sizeof argument is the exact same
7376 // type as the memory argument, and where it points to a user-defined
7377 // record type.
7378 if (SizeOfArgTy != QualType()) {
7379 if (PointeeTy->isRecordType() &&
7380 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7381 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7382 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7383 << FnName << SizeOfArgTy << ArgIdx
7384 << PointeeTy << Dest->getSourceRange()
7385 << LenExpr->getSourceRange());
7386 break;
7387 }
Nico Weberc5e73862011-06-14 16:14:58 +00007388 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00007389 } else if (DestTy->isArrayType()) {
7390 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00007391 }
Nico Weberc5e73862011-06-14 16:14:58 +00007392
Nico Weberc44b35e2015-03-21 17:37:46 +00007393 if (PointeeTy == QualType())
7394 continue;
Anna Zaks22122702012-01-17 00:37:07 +00007395
Nico Weberc44b35e2015-03-21 17:37:46 +00007396 // Always complain about dynamic classes.
7397 bool IsContained;
7398 if (const CXXRecordDecl *ContainedRD =
7399 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00007400
Nico Weberc44b35e2015-03-21 17:37:46 +00007401 unsigned OperationType = 0;
7402 // "overwritten" if we're warning about the destination for any call
7403 // but memcmp; otherwise a verb appropriate to the call.
7404 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7405 if (BId == Builtin::BImemcpy)
7406 OperationType = 1;
7407 else if(BId == Builtin::BImemmove)
7408 OperationType = 2;
7409 else if (BId == Builtin::BImemcmp)
7410 OperationType = 3;
7411 }
7412
John McCall31168b02011-06-15 23:02:42 +00007413 DiagRuntimeBehavior(
7414 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007415 PDiag(diag::warn_dyn_class_memaccess)
7416 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7417 << FnName << IsContained << ContainedRD << OperationType
7418 << Call->getCallee()->getSourceRange());
7419 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7420 BId != Builtin::BImemset)
7421 DiagRuntimeBehavior(
7422 Dest->getExprLoc(), Dest,
7423 PDiag(diag::warn_arc_object_memaccess)
7424 << ArgIdx << FnName << PointeeTy
7425 << Call->getCallee()->getSourceRange());
7426 else
7427 continue;
7428
7429 DiagRuntimeBehavior(
7430 Dest->getExprLoc(), Dest,
7431 PDiag(diag::note_bad_memaccess_silence)
7432 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7433 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007434 }
7435}
7436
Ted Kremenek6865f772011-08-18 20:55:45 +00007437// A little helper routine: ignore addition and subtraction of integer literals.
7438// This intentionally does not ignore all integer constant expressions because
7439// we don't want to remove sizeof().
7440static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7441 Ex = Ex->IgnoreParenCasts();
7442
7443 for (;;) {
7444 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7445 if (!BO || !BO->isAdditiveOp())
7446 break;
7447
7448 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7449 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7450
7451 if (isa<IntegerLiteral>(RHS))
7452 Ex = LHS;
7453 else if (isa<IntegerLiteral>(LHS))
7454 Ex = RHS;
7455 else
7456 break;
7457 }
7458
7459 return Ex;
7460}
7461
Anna Zaks13b08572012-08-08 21:42:23 +00007462static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7463 ASTContext &Context) {
7464 // Only handle constant-sized or VLAs, but not flexible members.
7465 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7466 // Only issue the FIXIT for arrays of size > 1.
7467 if (CAT->getSize().getSExtValue() <= 1)
7468 return false;
7469 } else if (!Ty->isVariableArrayType()) {
7470 return false;
7471 }
7472 return true;
7473}
7474
Ted Kremenek6865f772011-08-18 20:55:45 +00007475// Warn if the user has made the 'size' argument to strlcpy or strlcat
7476// be the size of the source, instead of the destination.
7477void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7478 IdentifierInfo *FnName) {
7479
7480 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007481 unsigned NumArgs = Call->getNumArgs();
7482 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007483 return;
7484
7485 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7486 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007487 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007488
7489 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7490 Call->getLocStart(), Call->getRParenLoc()))
7491 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00007492
7493 // Look for 'strlcpy(dst, x, sizeof(x))'
7494 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7495 CompareWithSrc = Ex;
7496 else {
7497 // Look for 'strlcpy(dst, x, strlen(x))'
7498 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00007499 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7500 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00007501 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7502 }
7503 }
7504
7505 if (!CompareWithSrc)
7506 return;
7507
7508 // Determine if the argument to sizeof/strlen is equal to the source
7509 // argument. In principle there's all kinds of things you could do
7510 // here, for instance creating an == expression and evaluating it with
7511 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7512 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7513 if (!SrcArgDRE)
7514 return;
7515
7516 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7517 if (!CompareWithSrcDRE ||
7518 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7519 return;
7520
7521 const Expr *OriginalSizeArg = Call->getArg(2);
7522 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7523 << OriginalSizeArg->getSourceRange() << FnName;
7524
7525 // Output a FIXIT hint if the destination is an array (rather than a
7526 // pointer to an array). This could be enhanced to handle some
7527 // pointers if we know the actual size, like if DstArg is 'array+2'
7528 // we could say 'sizeof(array)-2'.
7529 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00007530 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00007531 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007532
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007533 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007534 llvm::raw_svector_ostream OS(sizeString);
7535 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007536 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00007537 OS << ")";
7538
7539 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7540 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7541 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00007542}
7543
Anna Zaks314cd092012-02-01 19:08:57 +00007544/// Check if two expressions refer to the same declaration.
7545static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7546 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7547 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7548 return D1->getDecl() == D2->getDecl();
7549 return false;
7550}
7551
7552static const Expr *getStrlenExprArg(const Expr *E) {
7553 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7554 const FunctionDecl *FD = CE->getDirectCallee();
7555 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00007556 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007557 return CE->getArg(0)->IgnoreParenCasts();
7558 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007559 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007560}
7561
7562// Warn on anti-patterns as the 'size' argument to strncat.
7563// The correct size argument should look like following:
7564// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7565void Sema::CheckStrncatArguments(const CallExpr *CE,
7566 IdentifierInfo *FnName) {
7567 // Don't crash if the user has the wrong number of arguments.
7568 if (CE->getNumArgs() < 3)
7569 return;
7570 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7571 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7572 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7573
Nico Weber0e6daef2013-12-26 23:38:39 +00007574 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7575 CE->getRParenLoc()))
7576 return;
7577
Anna Zaks314cd092012-02-01 19:08:57 +00007578 // Identify common expressions, which are wrongly used as the size argument
7579 // to strncat and may lead to buffer overflows.
7580 unsigned PatternType = 0;
7581 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7582 // - sizeof(dst)
7583 if (referToTheSameDecl(SizeOfArg, DstArg))
7584 PatternType = 1;
7585 // - sizeof(src)
7586 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7587 PatternType = 2;
7588 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7589 if (BE->getOpcode() == BO_Sub) {
7590 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7591 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7592 // - sizeof(dst) - strlen(dst)
7593 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7594 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7595 PatternType = 1;
7596 // - sizeof(src) - (anything)
7597 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7598 PatternType = 2;
7599 }
7600 }
7601
7602 if (PatternType == 0)
7603 return;
7604
Anna Zaks5069aa32012-02-03 01:27:37 +00007605 // Generate the diagnostic.
7606 SourceLocation SL = LenArg->getLocStart();
7607 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007608 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00007609
7610 // If the function is defined as a builtin macro, do not show macro expansion.
7611 if (SM.isMacroArgExpansion(SL)) {
7612 SL = SM.getSpellingLoc(SL);
7613 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7614 SM.getSpellingLoc(SR.getEnd()));
7615 }
7616
Anna Zaks13b08572012-08-08 21:42:23 +00007617 // Check if the destination is an array (rather than a pointer to an array).
7618 QualType DstTy = DstArg->getType();
7619 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7620 Context);
7621 if (!isKnownSizeArray) {
7622 if (PatternType == 1)
7623 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7624 else
7625 Diag(SL, diag::warn_strncat_src_size) << SR;
7626 return;
7627 }
7628
Anna Zaks314cd092012-02-01 19:08:57 +00007629 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00007630 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007631 else
Anna Zaks5069aa32012-02-03 01:27:37 +00007632 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007633
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007634 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00007635 llvm::raw_svector_ostream OS(sizeString);
7636 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007637 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007638 OS << ") - ";
7639 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007640 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007641 OS << ") - 1";
7642
Anna Zaks5069aa32012-02-03 01:27:37 +00007643 Diag(SL, diag::note_strncat_wrong_size)
7644 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00007645}
7646
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007647//===--- CHECK: Return Address of Stack Variable --------------------------===//
7648
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007649static const Expr *EvalVal(const Expr *E,
7650 SmallVectorImpl<const DeclRefExpr *> &refVars,
7651 const Decl *ParentDecl);
7652static const Expr *EvalAddr(const Expr *E,
7653 SmallVectorImpl<const DeclRefExpr *> &refVars,
7654 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007655
7656/// CheckReturnStackAddr - Check if a return statement returns the address
7657/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007658static void
7659CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7660 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00007661
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007662 const Expr *stackE = nullptr;
7663 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007664
7665 // Perform checking for returned stack addresses, local blocks,
7666 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00007667 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007668 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007669 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00007670 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007671 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007672 }
7673
Craig Topperc3ec1492014-05-26 06:22:03 +00007674 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007675 return; // Nothing suspicious was found.
7676
Simon Pilgrim750bde62017-03-31 11:00:53 +00007677 // Parameters are initialized in the calling scope, so taking the address
Richard Trieu81b6c562016-08-05 23:24:47 +00007678 // of a parameter reference doesn't need a warning.
7679 for (auto *DRE : refVars)
7680 if (isa<ParmVarDecl>(DRE->getDecl()))
7681 return;
7682
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007683 SourceLocation diagLoc;
7684 SourceRange diagRange;
7685 if (refVars.empty()) {
7686 diagLoc = stackE->getLocStart();
7687 diagRange = stackE->getSourceRange();
7688 } else {
7689 // We followed through a reference variable. 'stackE' contains the
7690 // problematic expression but we will warn at the return statement pointing
7691 // at the reference variable. We will later display the "trail" of
7692 // reference variables using notes.
7693 diagLoc = refVars[0]->getLocStart();
7694 diagRange = refVars[0]->getSourceRange();
7695 }
7696
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007697 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7698 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00007699 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007700 << DR->getDecl()->getDeclName() << diagRange;
7701 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007702 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007703 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007704 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007705 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00007706 // If there is an LValue->RValue conversion, then the value of the
7707 // reference type is used, not the reference.
7708 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7709 if (ICE->getCastKind() == CK_LValueToRValue) {
7710 return;
7711 }
7712 }
Craig Topperda7b27f2015-11-17 05:40:09 +00007713 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7714 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007715 }
7716
7717 // Display the "trail" of reference variables that we followed until we
7718 // found the problematic expression using notes.
7719 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007720 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007721 // If this var binds to another reference var, show the range of the next
7722 // var, otherwise the var binds to the problematic expression, in which case
7723 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007724 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7725 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007726 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7727 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007728 }
7729}
7730
7731/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7732/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007733/// to a location on the stack, a local block, an address of a label, or a
7734/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007735/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007736/// encounter a subexpression that (1) clearly does not lead to one of the
7737/// above problematic expressions (2) is something we cannot determine leads to
7738/// a problematic expression based on such local checking.
7739///
7740/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7741/// the expression that they point to. Such variables are added to the
7742/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007743///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007744/// EvalAddr processes expressions that are pointers that are used as
7745/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007746/// At the base case of the recursion is a check for the above problematic
7747/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007748///
7749/// This implementation handles:
7750///
7751/// * pointer-to-pointer casts
7752/// * implicit conversions from array references to pointers
7753/// * taking the address of fields
7754/// * arbitrary interplay between "&" and "*" operators
7755/// * pointer arithmetic from an address of a stack variable
7756/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007757static const Expr *EvalAddr(const Expr *E,
7758 SmallVectorImpl<const DeclRefExpr *> &refVars,
7759 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007760 if (E->isTypeDependent())
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 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00007764 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00007765 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007766 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00007767 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00007768
Peter Collingbourne91147592011-04-15 00:35:48 +00007769 E = E->IgnoreParens();
7770
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007771 // Our "symbolic interpreter" is just a dispatch off the currently
7772 // viewed AST node. We then recursively traverse the AST by calling
7773 // EvalAddr and EvalVal appropriately.
7774 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007775 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007776 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007777
Richard Smith40f08eb2014-01-30 22:05:38 +00007778 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00007779 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00007780 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00007781
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007782 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007783 // If this is a reference variable, follow through to the expression that
7784 // it points to.
7785 if (V->hasLocalStorage() &&
7786 V->getType()->isReferenceType() && V->hasInit()) {
7787 // Add the reference variable to the "trail".
7788 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007789 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007790 }
7791
Craig Topperc3ec1492014-05-26 06:22:03 +00007792 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007793 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007794
Chris Lattner934edb22007-12-28 05:31:15 +00007795 case Stmt::UnaryOperatorClass: {
7796 // The only unary operator that make sense to handle here
7797 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007798 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007799
John McCalle3027922010-08-25 11:45:40 +00007800 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007801 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007802 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007803 }
Mike Stump11289f42009-09-09 15:08:12 +00007804
Chris Lattner934edb22007-12-28 05:31:15 +00007805 case Stmt::BinaryOperatorClass: {
7806 // Handle pointer arithmetic. All other binary operators are not valid
7807 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007808 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00007809 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00007810
John McCalle3027922010-08-25 11:45:40 +00007811 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00007812 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007813
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007814 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00007815
7816 // Determine which argument is the real pointer base. It could be
7817 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007818 if (!Base->getType()->isPointerType())
7819 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00007820
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007821 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007822 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007823 }
Steve Naroff2752a172008-09-10 19:17:48 +00007824
Chris Lattner934edb22007-12-28 05:31:15 +00007825 // For conditional operators we need to see if either the LHS or RHS are
7826 // valid DeclRefExpr*s. If one of them is valid, we return it.
7827 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007828 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007829
Chris Lattner934edb22007-12-28 05:31:15 +00007830 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007831 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007832 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007833 // In C++, we can have a throw-expression, which has 'void' type.
7834 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007835 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007836 return LHS;
7837 }
Chris Lattner934edb22007-12-28 05:31:15 +00007838
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007839 // In C++, we can have a throw-expression, which has 'void' type.
7840 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00007841 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007842
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007843 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007844 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007845
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007846 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00007847 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007848 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00007849 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007850
7851 case Stmt::AddrLabelExprClass:
7852 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00007853
John McCall28fc7092011-11-10 05:35:25 +00007854 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007855 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7856 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00007857
Ted Kremenekc3b4c522008-08-07 00:49:01 +00007858 // For casts, we need to handle conversions from arrays to
7859 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00007860 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00007861 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007862 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00007863 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00007864 case Stmt::CXXStaticCastExprClass:
7865 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00007866 case Stmt::CXXConstCastExprClass:
7867 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007868 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00007869 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00007870 case CK_LValueToRValue:
7871 case CK_NoOp:
7872 case CK_BaseToDerived:
7873 case CK_DerivedToBase:
7874 case CK_UncheckedDerivedToBase:
7875 case CK_Dynamic:
7876 case CK_CPointerToObjCPointerCast:
7877 case CK_BlockPointerToObjCPointerCast:
7878 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007879 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007880
7881 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007882 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007883
Richard Trieudadefde2014-07-02 04:39:38 +00007884 case CK_BitCast:
7885 if (SubExpr->getType()->isAnyPointerType() ||
7886 SubExpr->getType()->isBlockPointerType() ||
7887 SubExpr->getType()->isObjCQualifiedIdType())
7888 return EvalAddr(SubExpr, refVars, ParentDecl);
7889 else
7890 return nullptr;
7891
Eli Friedman8195ad72012-02-23 23:04:32 +00007892 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007893 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00007894 }
Chris Lattner934edb22007-12-28 05:31:15 +00007895 }
Mike Stump11289f42009-09-09 15:08:12 +00007896
Douglas Gregorfe314812011-06-21 17:03:29 +00007897 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007898 if (const Expr *Result =
7899 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7900 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00007901 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00007902 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007903
Chris Lattner934edb22007-12-28 05:31:15 +00007904 // Everything else: we simply don't reason about them.
7905 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007906 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00007907 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007908}
Mike Stump11289f42009-09-09 15:08:12 +00007909
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007910/// EvalVal - This function is complements EvalAddr in the mutual recursion.
7911/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007912static const Expr *EvalVal(const Expr *E,
7913 SmallVectorImpl<const DeclRefExpr *> &refVars,
7914 const Decl *ParentDecl) {
7915 do {
7916 // We should only be called for evaluating non-pointer expressions, or
7917 // expressions with a pointer type that are not used as references but
7918 // instead
7919 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00007920
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007921 // Our "symbolic interpreter" is just a dispatch off the currently
7922 // viewed AST node. We then recursively traverse the AST by calling
7923 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00007924
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007925 E = E->IgnoreParens();
7926 switch (E->getStmtClass()) {
7927 case Stmt::ImplicitCastExprClass: {
7928 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7929 if (IE->getValueKind() == VK_LValue) {
7930 E = IE->getSubExpr();
7931 continue;
7932 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007933 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007934 }
Richard Smith40f08eb2014-01-30 22:05:38 +00007935
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007936 case Stmt::ExprWithCleanupsClass:
7937 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7938 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007939
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007940 case Stmt::DeclRefExprClass: {
7941 // When we hit a DeclRefExpr we are looking at code that refers to a
7942 // variable's name. If it's not a reference variable we check if it has
7943 // local storage within the function, and if so, return the expression.
7944 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7945
7946 // If we leave the immediate function, the lifetime isn't about to end.
7947 if (DR->refersToEnclosingVariableOrCapture())
7948 return nullptr;
7949
7950 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7951 // Check if it refers to itself, e.g. "int& i = i;".
7952 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007953 return DR;
7954
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007955 if (V->hasLocalStorage()) {
7956 if (!V->getType()->isReferenceType())
7957 return DR;
7958
7959 // Reference variable, follow through to the expression that
7960 // it points to.
7961 if (V->hasInit()) {
7962 // Add the reference variable to the "trail".
7963 refVars.push_back(DR);
7964 return EvalVal(V->getInit(), refVars, V);
7965 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007966 }
7967 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007968
7969 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007970 }
Mike Stump11289f42009-09-09 15:08:12 +00007971
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007972 case Stmt::UnaryOperatorClass: {
7973 // The only unary operator that make sense to handle here
7974 // is Deref. All others don't resolve to a "name." This includes
7975 // handling all sorts of rvalues passed to a unary operator.
7976 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007977
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007978 if (U->getOpcode() == UO_Deref)
7979 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007980
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007981 return nullptr;
7982 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007983
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007984 case Stmt::ArraySubscriptExprClass: {
7985 // Array subscripts are potential references to data on the stack. We
7986 // retrieve the DeclRefExpr* for the array variable if it indeed
7987 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00007988 const auto *ASE = cast<ArraySubscriptExpr>(E);
7989 if (ASE->isTypeDependent())
7990 return nullptr;
7991 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007992 }
Mike Stump11289f42009-09-09 15:08:12 +00007993
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007994 case Stmt::OMPArraySectionExprClass: {
7995 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7996 ParentDecl);
7997 }
Mike Stump11289f42009-09-09 15:08:12 +00007998
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007999 case Stmt::ConditionalOperatorClass: {
8000 // For conditional operators we need to see if either the LHS or RHS are
8001 // non-NULL Expr's. If one is non-NULL, we return it.
8002 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008003
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008004 // Handle the GNU extension for missing LHS.
8005 if (const Expr *LHSExpr = C->getLHS()) {
8006 // In C++, we can have a throw-expression, which has 'void' type.
8007 if (!LHSExpr->getType()->isVoidType())
8008 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8009 return LHS;
8010 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008011
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008012 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008013 if (C->getRHS()->getType()->isVoidType())
8014 return nullptr;
8015
8016 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008017 }
8018
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008019 // Accesses to members are potential references to data on the stack.
8020 case Stmt::MemberExprClass: {
8021 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00008022
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008023 // Check for indirect access. We only want direct field accesses.
8024 if (M->isArrow())
8025 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008026
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008027 // Check whether the member type is itself a reference, in which case
8028 // we're not going to refer to the member, but to what the member refers
8029 // to.
8030 if (M->getMemberDecl()->getType()->isReferenceType())
8031 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008032
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008033 return EvalVal(M->getBase(), refVars, ParentDecl);
8034 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00008035
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008036 case Stmt::MaterializeTemporaryExprClass:
8037 if (const Expr *Result =
8038 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8039 refVars, ParentDecl))
8040 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008041 return E;
8042
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008043 default:
8044 // Check that we don't return or take the address of a reference to a
8045 // temporary. This is only useful in C++.
8046 if (!E->isTypeDependent() && E->isRValue())
8047 return E;
8048
8049 // Everything else: we simply don't reason about them.
8050 return nullptr;
8051 }
8052 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008053}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008054
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008055void
8056Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8057 SourceLocation ReturnLoc,
8058 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00008059 const AttrVec *Attrs,
8060 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008061 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8062
8063 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00008064 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8065 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00008066 CheckNonNullExpr(*this, RetValExp))
8067 Diag(ReturnLoc, diag::warn_null_ret)
8068 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00008069
8070 // C++11 [basic.stc.dynamic.allocation]p4:
8071 // If an allocation function declared with a non-throwing
8072 // exception-specification fails to allocate storage, it shall return
8073 // a null pointer. Any other allocation function that fails to allocate
8074 // storage shall indicate failure only by throwing an exception [...]
8075 if (FD) {
8076 OverloadedOperatorKind Op = FD->getOverloadedOperator();
8077 if (Op == OO_New || Op == OO_Array_New) {
8078 const FunctionProtoType *Proto
8079 = FD->getType()->castAs<FunctionProtoType>();
8080 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
8081 CheckNonNullExpr(*this, RetValExp))
8082 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8083 << FD << getLangOpts().CPlusPlus11;
8084 }
8085 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008086}
8087
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008088//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8089
8090/// Check for comparisons of floating point operands using != and ==.
8091/// Issue a warning if these are no self-comparisons, as they are not likely
8092/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00008093void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00008094 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8095 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008096
8097 // Special case: check for x == x (which is OK).
8098 // Do not emit warnings for such cases.
8099 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8100 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8101 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00008102 return;
Mike Stump11289f42009-09-09 15:08:12 +00008103
Ted Kremenekeda40e22007-11-29 00:59:04 +00008104 // Special case: check for comparisons against literals that can be exactly
8105 // represented by APFloat. In such cases, do not emit a warning. This
8106 // is a heuristic: often comparison against such literals are used to
8107 // detect if a value in a variable has not changed. This clearly can
8108 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00008109 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8110 if (FLL->isExact())
8111 return;
8112 } else
8113 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8114 if (FLR->isExact())
8115 return;
Mike Stump11289f42009-09-09 15:08:12 +00008116
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008117 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00008118 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008119 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008120 return;
Mike Stump11289f42009-09-09 15:08:12 +00008121
David Blaikie1f4ff152012-07-16 20:47:22 +00008122 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008123 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008124 return;
Mike Stump11289f42009-09-09 15:08:12 +00008125
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008126 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00008127 Diag(Loc, diag::warn_floatingpoint_eq)
8128 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008129}
John McCallca01b222010-01-04 23:21:16 +00008130
John McCall70aa5392010-01-06 05:24:50 +00008131//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8132//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00008133
John McCall70aa5392010-01-06 05:24:50 +00008134namespace {
John McCallca01b222010-01-04 23:21:16 +00008135
John McCall70aa5392010-01-06 05:24:50 +00008136/// Structure recording the 'active' range of an integer-valued
8137/// expression.
8138struct IntRange {
8139 /// The number of bits active in the int.
8140 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00008141
John McCall70aa5392010-01-06 05:24:50 +00008142 /// True if the int is known not to have negative values.
8143 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00008144
John McCall70aa5392010-01-06 05:24:50 +00008145 IntRange(unsigned Width, bool NonNegative)
8146 : Width(Width), NonNegative(NonNegative)
8147 {}
John McCallca01b222010-01-04 23:21:16 +00008148
John McCall817d4af2010-11-10 23:38:19 +00008149 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00008150 static IntRange forBoolType() {
8151 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00008152 }
8153
John McCall817d4af2010-11-10 23:38:19 +00008154 /// Returns the range of an opaque value of the given integral type.
8155 static IntRange forValueOfType(ASTContext &C, QualType T) {
8156 return forValueOfCanonicalType(C,
8157 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00008158 }
8159
John McCall817d4af2010-11-10 23:38:19 +00008160 /// Returns the range of an opaque value of a canonical integral type.
8161 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00008162 assert(T->isCanonicalUnqualified());
8163
8164 if (const VectorType *VT = dyn_cast<VectorType>(T))
8165 T = VT->getElementType().getTypePtr();
8166 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8167 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008168 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8169 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00008170
David Majnemer6a426652013-06-07 22:07:20 +00008171 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00008172 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00008173 EnumDecl *Enum = ET->getDecl();
Erich Keane69dbbb02017-09-21 19:58:55 +00008174 // In C++11, enums without definitions can have an explicitly specified
8175 // underlying type. Use this type to compute the range.
David Majnemer6a426652013-06-07 22:07:20 +00008176 if (!Enum->isCompleteDefinition())
Erich Keane69dbbb02017-09-21 19:58:55 +00008177 return IntRange(C.getIntWidth(QualType(T, 0)),
8178 !ET->isSignedIntegerOrEnumerationType());
John McCall18a2c2c2010-11-09 22:22:12 +00008179
David Majnemer6a426652013-06-07 22:07:20 +00008180 unsigned NumPositive = Enum->getNumPositiveBits();
8181 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00008182
David Majnemer6a426652013-06-07 22:07:20 +00008183 if (NumNegative == 0)
8184 return IntRange(NumPositive, true/*NonNegative*/);
8185 else
8186 return IntRange(std::max(NumPositive + 1, NumNegative),
8187 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00008188 }
John McCall70aa5392010-01-06 05:24:50 +00008189
8190 const BuiltinType *BT = cast<BuiltinType>(T);
8191 assert(BT->isInteger());
8192
8193 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8194 }
8195
John McCall817d4af2010-11-10 23:38:19 +00008196 /// Returns the "target" range of a canonical integral type, i.e.
8197 /// the range of values expressible in the type.
8198 ///
8199 /// This matches forValueOfCanonicalType except that enums have the
8200 /// full range of their type, not the range of their enumerators.
8201 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8202 assert(T->isCanonicalUnqualified());
8203
8204 if (const VectorType *VT = dyn_cast<VectorType>(T))
8205 T = VT->getElementType().getTypePtr();
8206 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8207 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008208 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8209 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008210 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00008211 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008212
8213 const BuiltinType *BT = cast<BuiltinType>(T);
8214 assert(BT->isInteger());
8215
8216 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8217 }
8218
8219 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00008220 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00008221 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00008222 L.NonNegative && R.NonNegative);
8223 }
8224
John McCall817d4af2010-11-10 23:38:19 +00008225 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008226 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008227 return IntRange(std::min(L.Width, R.Width),
8228 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008229 }
8230};
8231
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008232IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008233 if (value.isSigned() && value.isNegative())
8234 return IntRange(value.getMinSignedBits(), false);
8235
8236 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008237 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008238
8239 // isNonNegative() just checks the sign bit without considering
8240 // signedness.
8241 return IntRange(value.getActiveBits(), true);
8242}
8243
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008244IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8245 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008246 if (result.isInt())
8247 return GetValueRange(C, result.getInt(), MaxWidth);
8248
8249 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008250 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8251 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8252 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8253 R = IntRange::join(R, El);
8254 }
John McCall70aa5392010-01-06 05:24:50 +00008255 return R;
8256 }
8257
8258 if (result.isComplexInt()) {
8259 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8260 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8261 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008262 }
8263
8264 // This can happen with lossless casts to intptr_t of "based" lvalues.
8265 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008266 // FIXME: The only reason we need to pass the type in here is to get
8267 // the sign right on this one case. It would be nice if APValue
8268 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008269 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008270 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008271}
John McCall70aa5392010-01-06 05:24:50 +00008272
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008273QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008274 QualType Ty = E->getType();
8275 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8276 Ty = AtomicRHS->getValueType();
8277 return Ty;
8278}
8279
John McCall70aa5392010-01-06 05:24:50 +00008280/// Pseudo-evaluate the given integer expression, estimating the
8281/// range of values it might take.
8282///
8283/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008284IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008285 E = E->IgnoreParens();
8286
8287 // Try a full evaluation first.
8288 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008289 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008290 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008291
8292 // I think we only want to look through implicit casts here; if the
8293 // user has an explicit widening cast, we should treat the value as
8294 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008295 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00008296 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00008297 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8298
Eli Friedmane6d33952013-07-08 20:20:06 +00008299 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00008300
George Burgess IVdf1ed002016-01-13 01:52:39 +00008301 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8302 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00008303
John McCall70aa5392010-01-06 05:24:50 +00008304 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00008305 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00008306 return OutputTypeRange;
8307
8308 IntRange SubRange
8309 = GetExprRange(C, CE->getSubExpr(),
8310 std::min(MaxWidth, OutputTypeRange.Width));
8311
8312 // Bail out if the subexpr's range is as wide as the cast type.
8313 if (SubRange.Width >= OutputTypeRange.Width)
8314 return OutputTypeRange;
8315
8316 // Otherwise, we take the smaller width, and we're non-negative if
8317 // either the output type or the subexpr is.
8318 return IntRange(SubRange.Width,
8319 SubRange.NonNegative || OutputTypeRange.NonNegative);
8320 }
8321
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008322 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008323 // If we can fold the condition, just take that operand.
8324 bool CondResult;
8325 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8326 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8327 : CO->getFalseExpr(),
8328 MaxWidth);
8329
8330 // Otherwise, conservatively merge.
8331 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8332 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8333 return IntRange::join(L, R);
8334 }
8335
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008336 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008337 switch (BO->getOpcode()) {
8338
8339 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00008340 case BO_LAnd:
8341 case BO_LOr:
8342 case BO_LT:
8343 case BO_GT:
8344 case BO_LE:
8345 case BO_GE:
8346 case BO_EQ:
8347 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00008348 return IntRange::forBoolType();
8349
John McCallc3688382011-07-13 06:35:24 +00008350 // The type of the assignments is the type of the LHS, so the RHS
8351 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00008352 case BO_MulAssign:
8353 case BO_DivAssign:
8354 case BO_RemAssign:
8355 case BO_AddAssign:
8356 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00008357 case BO_XorAssign:
8358 case BO_OrAssign:
8359 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00008360 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00008361
John McCallc3688382011-07-13 06:35:24 +00008362 // Simple assignments just pass through the RHS, which will have
8363 // been coerced to the LHS type.
8364 case BO_Assign:
8365 // TODO: bitfields?
8366 return GetExprRange(C, BO->getRHS(), MaxWidth);
8367
John McCall70aa5392010-01-06 05:24:50 +00008368 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008369 case BO_PtrMemD:
8370 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00008371 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008372
John McCall2ce81ad2010-01-06 22:07:33 +00008373 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00008374 case BO_And:
8375 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00008376 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8377 GetExprRange(C, BO->getRHS(), MaxWidth));
8378
John McCall70aa5392010-01-06 05:24:50 +00008379 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00008380 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00008381 // ...except that we want to treat '1 << (blah)' as logically
8382 // positive. It's an important idiom.
8383 if (IntegerLiteral *I
8384 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8385 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008386 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00008387 return IntRange(R.Width, /*NonNegative*/ true);
8388 }
8389 }
8390 // fallthrough
8391
John McCalle3027922010-08-25 11:45:40 +00008392 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00008393 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008394
John McCall2ce81ad2010-01-06 22:07:33 +00008395 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00008396 case BO_Shr:
8397 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00008398 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8399
8400 // If the shift amount is a positive constant, drop the width by
8401 // that much.
8402 llvm::APSInt shift;
8403 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8404 shift.isNonNegative()) {
8405 unsigned zext = shift.getZExtValue();
8406 if (zext >= L.Width)
8407 L.Width = (L.NonNegative ? 0 : 1);
8408 else
8409 L.Width -= zext;
8410 }
8411
8412 return L;
8413 }
8414
8415 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008416 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008417 return GetExprRange(C, BO->getRHS(), MaxWidth);
8418
John McCall2ce81ad2010-01-06 22:07:33 +00008419 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008420 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008421 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008422 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008423 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008424
John McCall51431812011-07-14 22:39:48 +00008425 // The width of a division result is mostly determined by the size
8426 // of the LHS.
8427 case BO_Div: {
8428 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008429 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008430 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8431
8432 // If the divisor is constant, use that.
8433 llvm::APSInt divisor;
8434 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8435 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8436 if (log2 >= L.Width)
8437 L.Width = (L.NonNegative ? 0 : 1);
8438 else
8439 L.Width = std::min(L.Width - log2, MaxWidth);
8440 return L;
8441 }
8442
8443 // Otherwise, just use the LHS's width.
8444 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8445 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8446 }
8447
8448 // The result of a remainder can't be larger than the result of
8449 // either side.
8450 case BO_Rem: {
8451 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008452 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008453 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8454 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8455
8456 IntRange meet = IntRange::meet(L, R);
8457 meet.Width = std::min(meet.Width, MaxWidth);
8458 return meet;
8459 }
8460
8461 // The default behavior is okay for these.
8462 case BO_Mul:
8463 case BO_Add:
8464 case BO_Xor:
8465 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008466 break;
8467 }
8468
John McCall51431812011-07-14 22:39:48 +00008469 // The default case is to treat the operation as if it were closed
8470 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008471 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8472 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8473 return IntRange::join(L, R);
8474 }
8475
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008476 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008477 switch (UO->getOpcode()) {
8478 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008479 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008480 return IntRange::forBoolType();
8481
8482 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008483 case UO_Deref:
8484 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00008485 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008486
8487 default:
8488 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8489 }
8490 }
8491
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008492 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00008493 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8494
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008495 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00008496 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00008497 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00008498
Eli Friedmane6d33952013-07-08 20:20:06 +00008499 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008500}
John McCall263a48b2010-01-04 23:31:57 +00008501
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008502IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008503 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00008504}
8505
John McCall263a48b2010-01-04 23:31:57 +00008506/// Checks whether the given value, which currently has the given
8507/// source semantics, has the same value when coerced through the
8508/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008509bool IsSameFloatAfterCast(const llvm::APFloat &value,
8510 const llvm::fltSemantics &Src,
8511 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008512 llvm::APFloat truncated = value;
8513
8514 bool ignored;
8515 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8516 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8517
8518 return truncated.bitwiseIsEqual(value);
8519}
8520
8521/// Checks whether the given value, which currently has the given
8522/// source semantics, has the same value when coerced through the
8523/// target semantics.
8524///
8525/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008526bool IsSameFloatAfterCast(const APValue &value,
8527 const llvm::fltSemantics &Src,
8528 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008529 if (value.isFloat())
8530 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8531
8532 if (value.isVector()) {
8533 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8534 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8535 return false;
8536 return true;
8537 }
8538
8539 assert(value.isComplexFloat());
8540 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8541 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8542}
8543
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008544void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008545
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008546bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00008547 // Suppress cases where we are comparing against an enum constant.
8548 if (const DeclRefExpr *DR =
8549 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8550 if (isa<EnumConstantDecl>(DR->getDecl()))
8551 return false;
8552
8553 // Suppress cases where the '0' value is expanded from a macro.
8554 if (E->getLocStart().isMacroID())
8555 return false;
8556
John McCallcc7e5bf2010-05-06 08:58:33 +00008557 llvm::APSInt Value;
8558 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8559}
8560
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008561bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00008562 // Strip off implicit integral promotions.
8563 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008564 if (ICE->getCastKind() != CK_IntegralCast &&
8565 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00008566 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008567 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00008568 }
8569
8570 return E->getType()->isEnumeralType();
8571}
8572
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008573bool isNonBooleanUnsignedValue(Expr *E) {
8574 // We are checking that the expression is not known to have boolean value,
8575 // is an integer type; and is either unsigned after implicit casts,
8576 // or was unsigned before implicit casts.
8577 return !E->isKnownToHaveBooleanValue() && E->getType()->isIntegerType() &&
8578 (!E->getType()->isSignedIntegerType() ||
8579 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
8580}
8581
8582bool CheckTautologicalComparisonWithZero(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00008583 // Disable warning in template instantiations.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008584 if (S.inTemplateInstantiation())
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008585 return false;
8586
8587 // bool values are handled by DiagnoseOutOfRangeComparison().
Richard Trieu36594562013-11-01 21:47:19 +00008588
Roman Lebedevb0f0a1e2017-09-20 09:54:47 +00008589 BinaryOperatorKind Op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00008590 if (E->isValueDependent())
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008591 return false;
Douglas Gregorb14dbd72010-12-21 07:22:56 +00008592
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008593 Expr *LHS = E->getLHS();
8594 Expr *RHS = E->getRHS();
8595
8596 bool Match = true;
8597
Roman Lebedev30d26082017-09-20 13:50:01 +00008598 if (Op == BO_LT && isNonBooleanUnsignedValue(LHS) && IsZero(S, RHS)) {
Roman Lebedevb0f0a1e2017-09-20 09:54:47 +00008599 S.Diag(E->getOperatorLoc(),
8600 HasEnumType(LHS) ? diag::warn_lunsigned_enum_always_true_comparison
8601 : diag::warn_lunsigned_always_true_comparison)
8602 << "< 0" << false << LHS->getSourceRange() << RHS->getSourceRange();
Roman Lebedev30d26082017-09-20 13:50:01 +00008603 } else if (Op == BO_GE && isNonBooleanUnsignedValue(LHS) && IsZero(S, RHS)) {
Roman Lebedevb0f0a1e2017-09-20 09:54:47 +00008604 S.Diag(E->getOperatorLoc(),
8605 HasEnumType(LHS) ? diag::warn_lunsigned_enum_always_true_comparison
8606 : diag::warn_lunsigned_always_true_comparison)
8607 << ">= 0" << true << LHS->getSourceRange() << RHS->getSourceRange();
Roman Lebedev30d26082017-09-20 13:50:01 +00008608 } else if (Op == BO_GT && isNonBooleanUnsignedValue(RHS) && IsZero(S, LHS)) {
Roman Lebedevb0f0a1e2017-09-20 09:54:47 +00008609 S.Diag(E->getOperatorLoc(),
8610 HasEnumType(RHS) ? diag::warn_runsigned_enum_always_true_comparison
8611 : diag::warn_runsigned_always_true_comparison)
8612 << "0 >" << false << LHS->getSourceRange() << RHS->getSourceRange();
Roman Lebedev30d26082017-09-20 13:50:01 +00008613 } else if (Op == BO_LE && isNonBooleanUnsignedValue(RHS) && IsZero(S, LHS)) {
Roman Lebedevb0f0a1e2017-09-20 09:54:47 +00008614 S.Diag(E->getOperatorLoc(),
8615 HasEnumType(RHS) ? diag::warn_runsigned_enum_always_true_comparison
8616 : diag::warn_runsigned_always_true_comparison)
8617 << "0 <=" << true << LHS->getSourceRange() << RHS->getSourceRange();
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008618 } else
8619 Match = false;
8620
8621 return Match;
John McCallcc7e5bf2010-05-06 08:58:33 +00008622}
8623
Benjamin Kramer7320b992016-06-15 14:20:56 +00008624void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8625 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008626 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00008627 // Disable warning in template instantiations.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008628 if (S.inTemplateInstantiation())
Richard Trieudd51d742013-11-01 21:19:43 +00008629 return;
8630
Richard Trieu0f097742014-04-04 04:13:47 +00008631 // TODO: Investigate using GetExprRange() to get tighter bounds
8632 // on the bit ranges.
8633 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00008634 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00008635 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00008636 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8637 unsigned OtherWidth = OtherRange.Width;
8638
8639 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8640
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008641 // 0 values are handled later by CheckTautologicalComparisonWithZero().
Richard Trieu0f097742014-04-04 04:13:47 +00008642 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00008643 return;
8644
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008645 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00008646 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008647
Richard Trieu0f097742014-04-04 04:13:47 +00008648 // Used for diagnostic printout.
8649 enum {
8650 LiteralConstant = 0,
8651 CXXBoolLiteralTrue,
8652 CXXBoolLiteralFalse
8653 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008654
Richard Trieu0f097742014-04-04 04:13:47 +00008655 if (!OtherIsBooleanType) {
8656 QualType ConstantT = Constant->getType();
8657 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00008658
Richard Trieu0f097742014-04-04 04:13:47 +00008659 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8660 return;
8661 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8662 "comparison with non-integer type");
8663
8664 bool ConstantSigned = ConstantT->isSignedIntegerType();
8665 bool CommonSigned = CommonT->isSignedIntegerType();
8666
8667 bool EqualityOnly = false;
8668
8669 if (CommonSigned) {
8670 // The common type is signed, therefore no signed to unsigned conversion.
8671 if (!OtherRange.NonNegative) {
8672 // Check that the constant is representable in type OtherT.
8673 if (ConstantSigned) {
8674 if (OtherWidth >= Value.getMinSignedBits())
8675 return;
8676 } else { // !ConstantSigned
8677 if (OtherWidth >= Value.getActiveBits() + 1)
8678 return;
8679 }
8680 } else { // !OtherSigned
8681 // Check that the constant is representable in type OtherT.
8682 // Negative values are out of range.
8683 if (ConstantSigned) {
8684 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8685 return;
8686 } else { // !ConstantSigned
8687 if (OtherWidth >= Value.getActiveBits())
8688 return;
8689 }
Richard Trieu560910c2012-11-14 22:50:24 +00008690 }
Richard Trieu0f097742014-04-04 04:13:47 +00008691 } else { // !CommonSigned
8692 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00008693 if (OtherWidth >= Value.getActiveBits())
8694 return;
Craig Toppercf360162014-06-18 05:13:11 +00008695 } else { // OtherSigned
8696 assert(!ConstantSigned &&
8697 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00008698 // Check to see if the constant is representable in OtherT.
8699 if (OtherWidth > Value.getActiveBits())
8700 return;
8701 // Check to see if the constant is equivalent to a negative value
8702 // cast to CommonT.
8703 if (S.Context.getIntWidth(ConstantT) ==
8704 S.Context.getIntWidth(CommonT) &&
8705 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8706 return;
8707 // The constant value rests between values that OtherT can represent
8708 // after conversion. Relational comparison still works, but equality
8709 // comparisons will be tautological.
8710 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008711 }
8712 }
Richard Trieu0f097742014-04-04 04:13:47 +00008713
8714 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8715
8716 if (op == BO_EQ || op == BO_NE) {
8717 IsTrue = op == BO_NE;
8718 } else if (EqualityOnly) {
8719 return;
8720 } else if (RhsConstant) {
8721 if (op == BO_GT || op == BO_GE)
8722 IsTrue = !PositiveConstant;
8723 else // op == BO_LT || op == BO_LE
8724 IsTrue = PositiveConstant;
8725 } else {
8726 if (op == BO_LT || op == BO_LE)
8727 IsTrue = !PositiveConstant;
8728 else // op == BO_GT || op == BO_GE
8729 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008730 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008731 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00008732 // Other isKnownToHaveBooleanValue
8733 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8734 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8735 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8736
8737 static const struct LinkedConditions {
8738 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8739 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8740 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8741 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8742 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8743 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8744
8745 } TruthTable = {
8746 // Constant on LHS. | Constant on RHS. |
8747 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
8748 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8749 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8750 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8751 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8752 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8753 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8754 };
8755
8756 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8757
8758 enum ConstantValue ConstVal = Zero;
8759 if (Value.isUnsigned() || Value.isNonNegative()) {
8760 if (Value == 0) {
8761 LiteralOrBoolConstant =
8762 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8763 ConstVal = Zero;
8764 } else if (Value == 1) {
8765 LiteralOrBoolConstant =
8766 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8767 ConstVal = One;
8768 } else {
8769 LiteralOrBoolConstant = LiteralConstant;
8770 ConstVal = GT_One;
8771 }
8772 } else {
8773 ConstVal = LT_Zero;
8774 }
8775
8776 CompareBoolWithConstantResult CmpRes;
8777
8778 switch (op) {
8779 case BO_LT:
8780 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8781 break;
8782 case BO_GT:
8783 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8784 break;
8785 case BO_LE:
8786 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8787 break;
8788 case BO_GE:
8789 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8790 break;
8791 case BO_EQ:
8792 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8793 break;
8794 case BO_NE:
8795 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8796 break;
8797 default:
8798 CmpRes = Unkwn;
8799 break;
8800 }
8801
8802 if (CmpRes == AFals) {
8803 IsTrue = false;
8804 } else if (CmpRes == ATrue) {
8805 IsTrue = true;
8806 } else {
8807 return;
8808 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008809 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008810
8811 // If this is a comparison to an enum constant, include that
8812 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00008813 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008814 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8815 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8816
8817 SmallString<64> PrettySourceValue;
8818 llvm::raw_svector_ostream OS(PrettySourceValue);
8819 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00008820 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008821 else
8822 OS << Value;
8823
Richard Trieu0f097742014-04-04 04:13:47 +00008824 S.DiagRuntimeBehavior(
8825 E->getOperatorLoc(), E,
8826 S.PDiag(diag::warn_out_of_range_compare)
8827 << OS.str() << LiteralOrBoolConstant
8828 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8829 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008830}
8831
John McCallcc7e5bf2010-05-06 08:58:33 +00008832/// Analyze the operands of the given comparison. Implements the
8833/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008834void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00008835 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8836 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008837}
John McCall263a48b2010-01-04 23:31:57 +00008838
John McCallca01b222010-01-04 23:21:16 +00008839/// \brief Implements -Wsign-compare.
8840///
Richard Trieu82402a02011-09-15 21:56:47 +00008841/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008842void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008843 // The type the comparison is being performed in.
8844 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00008845
8846 // Only analyze comparison operators where both sides have been converted to
8847 // the same type.
8848 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8849 return AnalyzeImpConvsInComparison(S, E);
8850
8851 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00008852 if (E->isValueDependent())
8853 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008854
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008855 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8856 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008857
8858 bool IsComparisonConstant = false;
8859
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008860 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008861 // of 'true' or 'false'.
8862 if (T->isIntegralType(S.Context)) {
8863 llvm::APSInt RHSValue;
8864 bool IsRHSIntegralLiteral =
8865 RHS->isIntegerConstantExpr(RHSValue, S.Context);
8866 llvm::APSInt LHSValue;
8867 bool IsLHSIntegralLiteral =
8868 LHS->isIntegerConstantExpr(LHSValue, S.Context);
8869 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8870 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8871 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8872 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8873 else
8874 IsComparisonConstant =
8875 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008876 } else if (!T->hasUnsignedIntegerRepresentation())
8877 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008878
8879 // We don't care about value-dependent expressions or expressions
8880 // whose result is a constant.
8881 if (IsComparisonConstant)
8882 return AnalyzeImpConvsInComparison(S, E);
8883
8884 // If this is a tautological comparison, suppress -Wsign-compare.
8885 if (CheckTautologicalComparisonWithZero(S, E))
8886 return AnalyzeImpConvsInComparison(S, E);
8887
John McCallcc7e5bf2010-05-06 08:58:33 +00008888 // We don't do anything special if this isn't an unsigned integral
8889 // comparison: we're only interested in integral comparisons, and
8890 // signed comparisons only happen in cases we don't care to warn about.
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008891 if (!T->hasUnsignedIntegerRepresentation())
John McCallcc7e5bf2010-05-06 08:58:33 +00008892 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008893
John McCallcc7e5bf2010-05-06 08:58:33 +00008894 // Check to see if one of the (unmodified) operands is of different
8895 // signedness.
8896 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00008897 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8898 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00008899 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00008900 signedOperand = LHS;
8901 unsignedOperand = RHS;
8902 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8903 signedOperand = RHS;
8904 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00008905 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00008906 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008907 }
8908
John McCallcc7e5bf2010-05-06 08:58:33 +00008909 // Otherwise, calculate the effective range of the signed operand.
8910 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00008911
John McCallcc7e5bf2010-05-06 08:58:33 +00008912 // Go ahead and analyze implicit conversions in the operands. Note
8913 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00008914 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8915 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00008916
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008917 // If the signed range is non-negative, -Wsign-compare won't fire.
John McCallcc7e5bf2010-05-06 08:58:33 +00008918 if (signedRange.NonNegative)
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008919 return;
John McCallca01b222010-01-04 23:21:16 +00008920
8921 // For (in)equality comparisons, if the unsigned operand is a
8922 // constant which cannot collide with a overflowed signed operand,
8923 // then reinterpreting the signed operand as unsigned will not
8924 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00008925 if (E->isEqualityOp()) {
8926 unsigned comparisonWidth = S.Context.getIntWidth(T);
8927 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00008928
John McCallcc7e5bf2010-05-06 08:58:33 +00008929 // We should never be unable to prove that the unsigned operand is
8930 // non-negative.
8931 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8932
8933 if (unsignedRange.Width < comparisonWidth)
8934 return;
8935 }
8936
Douglas Gregorbfb4a212012-05-01 01:53:49 +00008937 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8938 S.PDiag(diag::warn_mixed_sign_comparison)
8939 << LHS->getType() << RHS->getType()
8940 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00008941}
8942
John McCall1f425642010-11-11 03:21:53 +00008943/// Analyzes an attempt to assign the given value to a bitfield.
8944///
8945/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008946bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8947 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00008948 assert(Bitfield->isBitField());
8949 if (Bitfield->isInvalidDecl())
8950 return false;
8951
John McCalldeebbcf2010-11-11 05:33:51 +00008952 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00008953 QualType BitfieldType = Bitfield->getType();
8954 if (BitfieldType->isBooleanType())
8955 return false;
8956
8957 if (BitfieldType->isEnumeralType()) {
8958 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
8959 // If the underlying enum type was not explicitly specified as an unsigned
8960 // type and the enum contain only positive values, MSVC++ will cause an
8961 // inconsistency by storing this as a signed type.
8962 if (S.getLangOpts().CPlusPlus11 &&
8963 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
8964 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
8965 BitfieldEnumDecl->getNumNegativeBits() == 0) {
8966 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
8967 << BitfieldEnumDecl->getNameAsString();
8968 }
8969 }
8970
John McCalldeebbcf2010-11-11 05:33:51 +00008971 if (Bitfield->getType()->isBooleanType())
8972 return false;
8973
Douglas Gregor789adec2011-02-04 13:09:01 +00008974 // Ignore value- or type-dependent expressions.
8975 if (Bitfield->getBitWidth()->isValueDependent() ||
8976 Bitfield->getBitWidth()->isTypeDependent() ||
8977 Init->isValueDependent() ||
8978 Init->isTypeDependent())
8979 return false;
8980
John McCall1f425642010-11-11 03:21:53 +00008981 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00008982 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00008983
Richard Smith5fab0c92011-12-28 19:48:30 +00008984 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00008985 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
8986 Expr::SE_AllowSideEffects)) {
8987 // The RHS is not constant. If the RHS has an enum type, make sure the
8988 // bitfield is wide enough to hold all the values of the enum without
8989 // truncation.
8990 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
8991 EnumDecl *ED = EnumTy->getDecl();
8992 bool SignedBitfield = BitfieldType->isSignedIntegerType();
8993
8994 // Enum types are implicitly signed on Windows, so check if there are any
8995 // negative enumerators to see if the enum was intended to be signed or
8996 // not.
8997 bool SignedEnum = ED->getNumNegativeBits() > 0;
8998
8999 // Check for surprising sign changes when assigning enum values to a
9000 // bitfield of different signedness. If the bitfield is signed and we
9001 // have exactly the right number of bits to store this unsigned enum,
9002 // suggest changing the enum to an unsigned type. This typically happens
9003 // on Windows where unfixed enums always use an underlying type of 'int'.
9004 unsigned DiagID = 0;
9005 if (SignedEnum && !SignedBitfield) {
9006 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9007 } else if (SignedBitfield && !SignedEnum &&
9008 ED->getNumPositiveBits() == FieldWidth) {
9009 DiagID = diag::warn_signed_bitfield_enum_conversion;
9010 }
9011
9012 if (DiagID) {
9013 S.Diag(InitLoc, DiagID) << Bitfield << ED;
9014 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9015 SourceRange TypeRange =
9016 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9017 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9018 << SignedEnum << TypeRange;
9019 }
9020
9021 // Compute the required bitwidth. If the enum has negative values, we need
9022 // one more bit than the normal number of positive bits to represent the
9023 // sign bit.
9024 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9025 ED->getNumNegativeBits())
9026 : ED->getNumPositiveBits();
9027
9028 // Check the bitwidth.
9029 if (BitsNeeded > FieldWidth) {
9030 Expr *WidthExpr = Bitfield->getBitWidth();
9031 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9032 << Bitfield << ED;
9033 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9034 << BitsNeeded << ED << WidthExpr->getSourceRange();
9035 }
9036 }
9037
John McCall1f425642010-11-11 03:21:53 +00009038 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009039 }
John McCall1f425642010-11-11 03:21:53 +00009040
John McCall1f425642010-11-11 03:21:53 +00009041 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00009042
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009043 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00009044 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009045 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9046 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00009047
John McCall1f425642010-11-11 03:21:53 +00009048 if (OriginalWidth <= FieldWidth)
9049 return false;
9050
Eli Friedmanc267a322012-01-26 23:11:39 +00009051 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00009052 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00009053 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00009054
Eli Friedmanc267a322012-01-26 23:11:39 +00009055 // Check whether the stored value is equal to the original value.
9056 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00009057 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00009058 return false;
9059
Eli Friedmanc267a322012-01-26 23:11:39 +00009060 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00009061 // therefore don't strictly fit into a signed bitfield of width 1.
9062 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00009063 return false;
9064
John McCall1f425642010-11-11 03:21:53 +00009065 std::string PrettyValue = Value.toString(10);
9066 std::string PrettyTrunc = TruncatedValue.toString(10);
9067
9068 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9069 << PrettyValue << PrettyTrunc << OriginalInit->getType()
9070 << Init->getSourceRange();
9071
9072 return true;
9073}
9074
John McCalld2a53122010-11-09 23:24:47 +00009075/// Analyze the given simple or compound assignment for warning-worthy
9076/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009077void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00009078 // Just recurse on the LHS.
9079 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9080
9081 // We want to recurse on the RHS as normal unless we're assigning to
9082 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00009083 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009084 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00009085 E->getOperatorLoc())) {
9086 // Recurse, ignoring any implicit conversions on the RHS.
9087 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9088 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00009089 }
9090 }
9091
9092 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9093}
9094
John McCall263a48b2010-01-04 23:31:57 +00009095/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009096void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9097 SourceLocation CContext, unsigned diag,
9098 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009099 if (pruneControlFlow) {
9100 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9101 S.PDiag(diag)
9102 << SourceType << T << E->getSourceRange()
9103 << SourceRange(CContext));
9104 return;
9105 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00009106 S.Diag(E->getExprLoc(), diag)
9107 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9108}
9109
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009110/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009111void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
9112 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009113 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009114}
9115
Richard Trieube234c32016-04-21 21:04:55 +00009116
9117/// Diagnose an implicit cast from a floating point value to an integer value.
9118void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9119
9120 SourceLocation CContext) {
9121 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00009122 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00009123
9124 Expr *InnerE = E->IgnoreParenImpCasts();
9125 // We also want to warn on, e.g., "int i = -1.234"
9126 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9127 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9128 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9129
9130 const bool IsLiteral =
9131 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9132
9133 llvm::APFloat Value(0.0);
9134 bool IsConstant =
9135 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9136 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00009137 return DiagnoseImpCast(S, E, T, CContext,
9138 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00009139 }
9140
Chandler Carruth016ef402011-04-10 08:36:24 +00009141 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00009142
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00009143 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9144 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00009145 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
9146 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00009147 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00009148 if (IsLiteral) return;
9149 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9150 PruneWarnings);
9151 }
9152
9153 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00009154 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00009155 // Warn on floating point literal to integer.
9156 DiagID = diag::warn_impcast_literal_float_to_integer;
9157 } else if (IntegerValue == 0) {
9158 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
9159 return DiagnoseImpCast(S, E, T, CContext,
9160 diag::warn_impcast_float_integer, PruneWarnings);
9161 }
9162 // Warn on non-zero to zero conversion.
9163 DiagID = diag::warn_impcast_float_to_integer_zero;
9164 } else {
9165 if (IntegerValue.isUnsigned()) {
9166 if (!IntegerValue.isMaxValue()) {
9167 return DiagnoseImpCast(S, E, T, CContext,
9168 diag::warn_impcast_float_integer, PruneWarnings);
9169 }
9170 } else { // IntegerValue.isSigned()
9171 if (!IntegerValue.isMaxSignedValue() &&
9172 !IntegerValue.isMinSignedValue()) {
9173 return DiagnoseImpCast(S, E, T, CContext,
9174 diag::warn_impcast_float_integer, PruneWarnings);
9175 }
9176 }
9177 // Warn on evaluatable floating point expression to integer conversion.
9178 DiagID = diag::warn_impcast_float_to_integer;
9179 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009180
Eli Friedman07185912013-08-29 23:44:43 +00009181 // FIXME: Force the precision of the source value down so we don't print
9182 // digits which are usually useless (we don't really care here if we
9183 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9184 // would automatically print the shortest representation, but it's a bit
9185 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00009186 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00009187 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9188 precision = (precision * 59 + 195) / 196;
9189 Value.toString(PrettySourceValue, precision);
9190
David Blaikie9b88cc02012-05-15 17:18:27 +00009191 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00009192 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00009193 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00009194 else
David Blaikie9b88cc02012-05-15 17:18:27 +00009195 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00009196
Richard Trieube234c32016-04-21 21:04:55 +00009197 if (PruneWarnings) {
9198 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9199 S.PDiag(DiagID)
9200 << E->getType() << T.getUnqualifiedType()
9201 << PrettySourceValue << PrettyTargetValue
9202 << E->getSourceRange() << SourceRange(CContext));
9203 } else {
9204 S.Diag(E->getExprLoc(), DiagID)
9205 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9206 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9207 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009208}
9209
John McCall18a2c2c2010-11-09 22:22:12 +00009210std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
9211 if (!Range.Width) return "0";
9212
9213 llvm::APSInt ValueInRange = Value;
9214 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00009215 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00009216 return ValueInRange.toString(10);
9217}
9218
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009219bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009220 if (!isa<ImplicitCastExpr>(Ex))
9221 return false;
9222
9223 Expr *InnerE = Ex->IgnoreParenImpCasts();
9224 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9225 const Type *Source =
9226 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9227 if (Target->isDependentType())
9228 return false;
9229
9230 const BuiltinType *FloatCandidateBT =
9231 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9232 const Type *BoolCandidateType = ToBool ? Target : Source;
9233
9234 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9235 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9236}
9237
9238void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9239 SourceLocation CC) {
9240 unsigned NumArgs = TheCall->getNumArgs();
9241 for (unsigned i = 0; i < NumArgs; ++i) {
9242 Expr *CurrA = TheCall->getArg(i);
9243 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9244 continue;
9245
9246 bool IsSwapped = ((i > 0) &&
9247 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9248 IsSwapped |= ((i < (NumArgs - 1)) &&
9249 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9250 if (IsSwapped) {
9251 // Warn on this floating-point to bool conversion.
9252 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9253 CurrA->getType(), CC,
9254 diag::warn_impcast_floating_point_to_bool);
9255 }
9256 }
9257}
9258
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009259void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009260 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9261 E->getExprLoc()))
9262 return;
9263
Richard Trieu09d6b802016-01-08 23:35:06 +00009264 // Don't warn on functions which have return type nullptr_t.
9265 if (isa<CallExpr>(E))
9266 return;
9267
Richard Trieu5b993502014-10-15 03:42:06 +00009268 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9269 const Expr::NullPointerConstantKind NullKind =
9270 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9271 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9272 return;
9273
9274 // Return if target type is a safe conversion.
9275 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9276 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9277 return;
9278
9279 SourceLocation Loc = E->getSourceRange().getBegin();
9280
Richard Trieu0a5e1662016-02-13 00:58:53 +00009281 // Venture through the macro stacks to get to the source of macro arguments.
9282 // The new location is a better location than the complete location that was
9283 // passed in.
9284 while (S.SourceMgr.isMacroArgExpansion(Loc))
9285 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
9286
9287 while (S.SourceMgr.isMacroArgExpansion(CC))
9288 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
9289
Richard Trieu5b993502014-10-15 03:42:06 +00009290 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00009291 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9292 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9293 Loc, S.SourceMgr, S.getLangOpts());
9294 if (MacroName == "NULL")
9295 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00009296 }
9297
9298 // Only warn if the null and context location are in the same macro expansion.
9299 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9300 return;
9301
9302 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9303 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
9304 << FixItHint::CreateReplacement(Loc,
9305 S.getFixItZeroLiteralForType(T, Loc));
9306}
9307
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009308void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9309 ObjCArrayLiteral *ArrayLiteral);
9310void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9311 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00009312
9313/// Check a single element within a collection literal against the
9314/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009315void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
9316 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009317 // Skip a bitcast to 'id' or qualified 'id'.
9318 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9319 if (ICE->getCastKind() == CK_BitCast &&
9320 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9321 Element = ICE->getSubExpr();
9322 }
9323
9324 QualType ElementType = Element->getType();
9325 ExprResult ElementResult(Element);
9326 if (ElementType->getAs<ObjCObjectPointerType>() &&
9327 S.CheckSingleAssignmentConstraints(TargetElementType,
9328 ElementResult,
9329 false, false)
9330 != Sema::Compatible) {
9331 S.Diag(Element->getLocStart(),
9332 diag::warn_objc_collection_literal_element)
9333 << ElementType << ElementKind << TargetElementType
9334 << Element->getSourceRange();
9335 }
9336
9337 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9338 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9339 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9340 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9341}
9342
9343/// Check an Objective-C array literal being converted to the given
9344/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009345void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9346 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009347 if (!S.NSArrayDecl)
9348 return;
9349
9350 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9351 if (!TargetObjCPtr)
9352 return;
9353
9354 if (TargetObjCPtr->isUnspecialized() ||
9355 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9356 != S.NSArrayDecl->getCanonicalDecl())
9357 return;
9358
9359 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9360 if (TypeArgs.size() != 1)
9361 return;
9362
9363 QualType TargetElementType = TypeArgs[0];
9364 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9365 checkObjCCollectionLiteralElement(S, TargetElementType,
9366 ArrayLiteral->getElement(I),
9367 0);
9368 }
9369}
9370
9371/// Check an Objective-C dictionary literal being converted to the given
9372/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009373void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9374 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009375 if (!S.NSDictionaryDecl)
9376 return;
9377
9378 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9379 if (!TargetObjCPtr)
9380 return;
9381
9382 if (TargetObjCPtr->isUnspecialized() ||
9383 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9384 != S.NSDictionaryDecl->getCanonicalDecl())
9385 return;
9386
9387 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9388 if (TypeArgs.size() != 2)
9389 return;
9390
9391 QualType TargetKeyType = TypeArgs[0];
9392 QualType TargetObjectType = TypeArgs[1];
9393 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9394 auto Element = DictionaryLiteral->getKeyValueElement(I);
9395 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9396 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9397 }
9398}
9399
Richard Trieufc404c72016-02-05 23:02:38 +00009400// Helper function to filter out cases for constant width constant conversion.
9401// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009402bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9403 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00009404 // If initializing from a constant, and the constant starts with '0',
9405 // then it is a binary, octal, or hexadecimal. Allow these constants
9406 // to fill all the bits, even if there is a sign change.
9407 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9408 const char FirstLiteralCharacter =
9409 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9410 if (FirstLiteralCharacter == '0')
9411 return false;
9412 }
9413
9414 // If the CC location points to a '{', and the type is char, then assume
9415 // assume it is an array initialization.
9416 if (CC.isValid() && T->isCharType()) {
9417 const char FirstContextCharacter =
9418 S.getSourceManager().getCharacterData(CC)[0];
9419 if (FirstContextCharacter == '{')
9420 return false;
9421 }
9422
9423 return true;
9424}
9425
John McCallcc7e5bf2010-05-06 08:58:33 +00009426void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00009427 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009428 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00009429
John McCallcc7e5bf2010-05-06 08:58:33 +00009430 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9431 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9432 if (Source == Target) return;
9433 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00009434
Chandler Carruthc22845a2011-07-26 05:40:03 +00009435 // If the conversion context location is invalid don't complain. We also
9436 // don't want to emit a warning if the issue occurs from the expansion of
9437 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9438 // delay this check as long as possible. Once we detect we are in that
9439 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009440 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00009441 return;
9442
Richard Trieu021baa32011-09-23 20:10:00 +00009443 // Diagnose implicit casts to bool.
9444 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9445 if (isa<StringLiteral>(E))
9446 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00009447 // and expressions, for instance, assert(0 && "error here"), are
9448 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00009449 return DiagnoseImpCast(S, E, T, CC,
9450 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00009451 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9452 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9453 // This covers the literal expressions that evaluate to Objective-C
9454 // objects.
9455 return DiagnoseImpCast(S, E, T, CC,
9456 diag::warn_impcast_objective_c_literal_to_bool);
9457 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009458 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9459 // Warn on pointer to bool conversion that is always true.
9460 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9461 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00009462 }
Richard Trieu021baa32011-09-23 20:10:00 +00009463 }
John McCall263a48b2010-01-04 23:31:57 +00009464
Douglas Gregor5054cb02015-07-07 03:58:22 +00009465 // Check implicit casts from Objective-C collection literals to specialized
9466 // collection types, e.g., NSArray<NSString *> *.
9467 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9468 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9469 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9470 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9471
John McCall263a48b2010-01-04 23:31:57 +00009472 // Strip vector types.
9473 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009474 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009475 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009476 return;
John McCallacf0ee52010-10-08 02:01:28 +00009477 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009478 }
Chris Lattneree7286f2011-06-14 04:51:15 +00009479
9480 // If the vector cast is cast between two vectors of the same size, it is
9481 // a bitcast, not a conversion.
9482 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9483 return;
John McCall263a48b2010-01-04 23:31:57 +00009484
9485 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9486 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9487 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00009488 if (auto VecTy = dyn_cast<VectorType>(Target))
9489 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00009490
9491 // Strip complex types.
9492 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009493 if (!isa<ComplexType>(Target)) {
Tim Northover02416372017-08-08 23:18:05 +00009494 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009495 return;
9496
Tim Northover02416372017-08-08 23:18:05 +00009497 return DiagnoseImpCast(S, E, T, CC,
9498 S.getLangOpts().CPlusPlus
9499 ? diag::err_impcast_complex_scalar
9500 : diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009501 }
John McCall263a48b2010-01-04 23:31:57 +00009502
9503 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9504 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9505 }
9506
9507 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9508 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9509
9510 // If the source is floating point...
9511 if (SourceBT && SourceBT->isFloatingPoint()) {
9512 // ...and the target is floating point...
9513 if (TargetBT && TargetBT->isFloatingPoint()) {
9514 // ...then warn if we're dropping FP rank.
9515
9516 // Builtin FP kinds are ordered by increasing FP rank.
9517 if (SourceBT->getKind() > TargetBT->getKind()) {
9518 // Don't warn about float constants that are precisely
9519 // representable in the target type.
9520 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009521 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00009522 // Value might be a float, a float vector, or a float complex.
9523 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00009524 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9525 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00009526 return;
9527 }
9528
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009529 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009530 return;
9531
John McCallacf0ee52010-10-08 02:01:28 +00009532 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00009533 }
9534 // ... or possibly if we're increasing rank, too
9535 else if (TargetBT->getKind() > SourceBT->getKind()) {
9536 if (S.SourceMgr.isInSystemMacro(CC))
9537 return;
9538
9539 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00009540 }
9541 return;
9542 }
9543
Richard Trieube234c32016-04-21 21:04:55 +00009544 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00009545 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009546 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009547 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00009548
Richard Trieube234c32016-04-21 21:04:55 +00009549 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00009550 }
John McCall263a48b2010-01-04 23:31:57 +00009551
Richard Smith54894fd2015-12-30 01:06:52 +00009552 // Detect the case where a call result is converted from floating-point to
9553 // to bool, and the final argument to the call is converted from bool, to
9554 // discover this typo:
9555 //
9556 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9557 //
9558 // FIXME: This is an incredibly special case; is there some more general
9559 // way to detect this class of misplaced-parentheses bug?
9560 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009561 // Check last argument of function call to see if it is an
9562 // implicit cast from a type matching the type the result
9563 // is being cast to.
9564 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00009565 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009566 Expr *LastA = CEx->getArg(NumArgs - 1);
9567 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00009568 if (isa<ImplicitCastExpr>(LastA) &&
9569 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009570 // Warn on this floating-point to bool conversion
9571 DiagnoseImpCast(S, E, T, CC,
9572 diag::warn_impcast_floating_point_to_bool);
9573 }
9574 }
9575 }
John McCall263a48b2010-01-04 23:31:57 +00009576 return;
9577 }
9578
Richard Trieu5b993502014-10-15 03:42:06 +00009579 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00009580
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009581 S.DiscardMisalignedMemberAddress(Target, E);
9582
David Blaikie9366d2b2012-06-19 21:19:06 +00009583 if (!Source->isIntegerType() || !Target->isIntegerType())
9584 return;
9585
David Blaikie7555b6a2012-05-15 16:56:36 +00009586 // TODO: remove this early return once the false positives for constant->bool
9587 // in templates, macros, etc, are reduced or removed.
9588 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9589 return;
9590
John McCallcc7e5bf2010-05-06 08:58:33 +00009591 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00009592 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00009593
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009594 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00009595 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009596 // TODO: this should happen for bitfield stores, too.
9597 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00009598 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009599 if (S.SourceMgr.isInSystemMacro(CC))
9600 return;
9601
John McCall18a2c2c2010-11-09 22:22:12 +00009602 std::string PrettySourceValue = Value.toString(10);
9603 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009604
Ted Kremenek33ba9952011-10-22 02:37:33 +00009605 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9606 S.PDiag(diag::warn_impcast_integer_precision_constant)
9607 << PrettySourceValue << PrettyTargetValue
9608 << E->getType() << T << E->getSourceRange()
9609 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00009610 return;
9611 }
9612
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009613 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9614 if (S.SourceMgr.isInSystemMacro(CC))
9615 return;
9616
David Blaikie9455da02012-04-12 22:40:54 +00009617 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00009618 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9619 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00009620 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00009621 }
9622
Richard Trieudcb55572016-01-29 23:51:16 +00009623 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9624 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9625 // Warn when doing a signed to signed conversion, warn if the positive
9626 // source value is exactly the width of the target type, which will
9627 // cause a negative value to be stored.
9628
9629 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00009630 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9631 !S.SourceMgr.isInSystemMacro(CC)) {
9632 if (isSameWidthConstantConversion(S, E, T, CC)) {
9633 std::string PrettySourceValue = Value.toString(10);
9634 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00009635
Richard Trieufc404c72016-02-05 23:02:38 +00009636 S.DiagRuntimeBehavior(
9637 E->getExprLoc(), E,
9638 S.PDiag(diag::warn_impcast_integer_precision_constant)
9639 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9640 << E->getSourceRange() << clang::SourceRange(CC));
9641 return;
Richard Trieudcb55572016-01-29 23:51:16 +00009642 }
9643 }
Richard Trieufc404c72016-02-05 23:02:38 +00009644
Richard Trieudcb55572016-01-29 23:51:16 +00009645 // Fall through for non-constants to give a sign conversion warning.
9646 }
9647
John McCallcc7e5bf2010-05-06 08:58:33 +00009648 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9649 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9650 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009651 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009652 return;
9653
John McCallcc7e5bf2010-05-06 08:58:33 +00009654 unsigned DiagID = diag::warn_impcast_integer_sign;
9655
9656 // Traditionally, gcc has warned about this under -Wsign-compare.
9657 // We also want to warn about it in -Wconversion.
9658 // So if -Wconversion is off, use a completely identical diagnostic
9659 // in the sign-compare group.
9660 // The conditional-checking code will
9661 if (ICContext) {
9662 DiagID = diag::warn_impcast_integer_sign_conditional;
9663 *ICContext = true;
9664 }
9665
John McCallacf0ee52010-10-08 02:01:28 +00009666 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00009667 }
9668
Douglas Gregora78f1932011-02-22 02:45:07 +00009669 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00009670 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9671 // type, to give us better diagnostics.
9672 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009673 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00009674 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9675 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9676 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9677 SourceType = S.Context.getTypeDeclType(Enum);
9678 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9679 }
9680 }
9681
Douglas Gregora78f1932011-02-22 02:45:07 +00009682 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9683 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00009684 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9685 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009686 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009687 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009688 return;
9689
Douglas Gregor364f7db2011-03-12 00:14:31 +00009690 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00009691 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009692 }
John McCall263a48b2010-01-04 23:31:57 +00009693}
9694
David Blaikie18e9ac72012-05-15 21:57:38 +00009695void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9696 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009697
9698void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00009699 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009700 E = E->IgnoreParenImpCasts();
9701
9702 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00009703 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009704
John McCallacf0ee52010-10-08 02:01:28 +00009705 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009706 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009707 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00009708}
9709
David Blaikie18e9ac72012-05-15 21:57:38 +00009710void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9711 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00009712 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009713
9714 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00009715 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9716 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009717
9718 // If -Wconversion would have warned about either of the candidates
9719 // for a signedness conversion to the context type...
9720 if (!Suspicious) return;
9721
9722 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009723 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00009724 return;
9725
John McCallcc7e5bf2010-05-06 08:58:33 +00009726 // ...then check whether it would have warned about either of the
9727 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00009728 if (E->getType() == T) return;
9729
9730 Suspicious = false;
9731 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9732 E->getType(), CC, &Suspicious);
9733 if (!Suspicious)
9734 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00009735 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009736}
9737
Richard Trieu65724892014-11-15 06:37:39 +00009738/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9739/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009740void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00009741 if (S.getLangOpts().Bool)
9742 return;
9743 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9744}
9745
John McCallcc7e5bf2010-05-06 08:58:33 +00009746/// AnalyzeImplicitConversions - Find and report any interesting
9747/// implicit conversions in the given expression. There are a couple
9748/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009749void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00009750 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00009751 Expr *E = OrigE->IgnoreParenImpCasts();
9752
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00009753 if (E->isTypeDependent() || E->isValueDependent())
9754 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00009755
John McCallcc7e5bf2010-05-06 08:58:33 +00009756 // For conditional operators, we analyze the arguments as if they
9757 // were being fed directly into the output.
9758 if (isa<ConditionalOperator>(E)) {
9759 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00009760 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009761 return;
9762 }
9763
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009764 // Check implicit argument conversions for function calls.
9765 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9766 CheckImplicitArgumentConversions(S, Call, CC);
9767
John McCallcc7e5bf2010-05-06 08:58:33 +00009768 // Go ahead and check any implicit conversions we might have skipped.
9769 // The non-canonical typecheck is just an optimization;
9770 // CheckImplicitConversion will filter out dead implicit conversions.
9771 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009772 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009773
9774 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00009775
9776 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9777 // The bound subexpressions in a PseudoObjectExpr are not reachable
9778 // as transitive children.
9779 // FIXME: Use a more uniform representation for this.
9780 for (auto *SE : POE->semantics())
9781 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9782 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00009783 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00009784
John McCallcc7e5bf2010-05-06 08:58:33 +00009785 // Skip past explicit casts.
9786 if (isa<ExplicitCastExpr>(E)) {
9787 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00009788 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009789 }
9790
John McCalld2a53122010-11-09 23:24:47 +00009791 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9792 // Do a somewhat different check with comparison operators.
9793 if (BO->isComparisonOp())
9794 return AnalyzeComparison(S, BO);
9795
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009796 // And with simple assignments.
9797 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00009798 return AnalyzeAssignment(S, BO);
9799 }
John McCallcc7e5bf2010-05-06 08:58:33 +00009800
9801 // These break the otherwise-useful invariant below. Fortunately,
9802 // we don't really need to recurse into them, because any internal
9803 // expressions should have been analyzed already when they were
9804 // built into statements.
9805 if (isa<StmtExpr>(E)) return;
9806
9807 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00009808 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00009809
9810 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00009811 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00009812 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00009813 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00009814 for (Stmt *SubStmt : E->children()) {
9815 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00009816 if (!ChildExpr)
9817 continue;
9818
Richard Trieu955231d2014-01-25 01:10:35 +00009819 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00009820 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00009821 // Ignore checking string literals that are in logical and operators.
9822 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00009823 continue;
9824 AnalyzeImplicitConversions(S, ChildExpr, CC);
9825 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009826
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009827 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00009828 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9829 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009830 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00009831
9832 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9833 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009834 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009835 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009836
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009837 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9838 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00009839 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009840}
9841
9842} // end anonymous namespace
9843
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009844/// Diagnose integer type and any valid implicit convertion to it.
9845static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9846 // Taking into account implicit conversions,
9847 // allow any integer.
9848 if (!E->getType()->isIntegerType()) {
9849 S.Diag(E->getLocStart(),
9850 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9851 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009852 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009853 // Potentially emit standard warnings for implicit conversions if enabled
9854 // using -Wconversion.
9855 CheckImplicitConversion(S, E, IntT, E->getLocStart());
9856 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009857}
9858
Richard Trieuc1888e02014-06-28 23:25:37 +00009859// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9860// Returns true when emitting a warning about taking the address of a reference.
9861static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00009862 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00009863 E = E->IgnoreParenImpCasts();
9864
9865 const FunctionDecl *FD = nullptr;
9866
9867 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9868 if (!DRE->getDecl()->getType()->isReferenceType())
9869 return false;
9870 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9871 if (!M->getMemberDecl()->getType()->isReferenceType())
9872 return false;
9873 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00009874 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00009875 return false;
9876 FD = Call->getDirectCallee();
9877 } else {
9878 return false;
9879 }
9880
9881 SemaRef.Diag(E->getExprLoc(), PD);
9882
9883 // If possible, point to location of function.
9884 if (FD) {
9885 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9886 }
9887
9888 return true;
9889}
9890
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009891// Returns true if the SourceLocation is expanded from any macro body.
9892// Returns false if the SourceLocation is invalid, is from not in a macro
9893// expansion, or is from expanded from a top-level macro argument.
9894static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9895 if (Loc.isInvalid())
9896 return false;
9897
9898 while (Loc.isMacroID()) {
9899 if (SM.isMacroBodyExpansion(Loc))
9900 return true;
9901 Loc = SM.getImmediateMacroCallerLoc(Loc);
9902 }
9903
9904 return false;
9905}
9906
Richard Trieu3bb8b562014-02-26 02:36:06 +00009907/// \brief Diagnose pointers that are always non-null.
9908/// \param E the expression containing the pointer
9909/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9910/// compared to a null pointer
9911/// \param IsEqual True when the comparison is equal to a null pointer
9912/// \param Range Extra SourceRange to highlight in the diagnostic
9913void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9914 Expr::NullPointerConstantKind NullKind,
9915 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00009916 if (!E)
9917 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009918
9919 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009920 if (E->getExprLoc().isMacroID()) {
9921 const SourceManager &SM = getSourceManager();
9922 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9923 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00009924 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009925 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009926 E = E->IgnoreImpCasts();
9927
9928 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9929
Richard Trieuf7432752014-06-06 21:39:26 +00009930 if (isa<CXXThisExpr>(E)) {
9931 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9932 : diag::warn_this_bool_conversion;
9933 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9934 return;
9935 }
9936
Richard Trieu3bb8b562014-02-26 02:36:06 +00009937 bool IsAddressOf = false;
9938
9939 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9940 if (UO->getOpcode() != UO_AddrOf)
9941 return;
9942 IsAddressOf = true;
9943 E = UO->getSubExpr();
9944 }
9945
Richard Trieuc1888e02014-06-28 23:25:37 +00009946 if (IsAddressOf) {
9947 unsigned DiagID = IsCompare
9948 ? diag::warn_address_of_reference_null_compare
9949 : diag::warn_address_of_reference_bool_conversion;
9950 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9951 << IsEqual;
9952 if (CheckForReference(*this, E, PD)) {
9953 return;
9954 }
9955 }
9956
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009957 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9958 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00009959 std::string Str;
9960 llvm::raw_string_ostream S(Str);
9961 E->printPretty(S, nullptr, getPrintingPolicy());
9962 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9963 : diag::warn_cast_nonnull_to_bool;
9964 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9965 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009966 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00009967 };
9968
9969 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9970 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9971 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009972 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9973 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009974 return;
9975 }
9976 }
9977 }
9978
Richard Trieu3bb8b562014-02-26 02:36:06 +00009979 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00009980 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009981 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9982 D = R->getDecl();
9983 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9984 D = M->getMemberDecl();
9985 }
9986
9987 // Weak Decls can be null.
9988 if (!D || D->isWeak())
9989 return;
George Burgess IV850269a2015-12-08 22:02:00 +00009990
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009991 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00009992 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9993 if (getCurFunction() &&
9994 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009995 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9996 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009997 return;
9998 }
9999
10000 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +000010001 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +000010002 assert(ParamIter != FD->param_end());
10003 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10004
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010005 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10006 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010007 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +000010008 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010009 }
George Burgess IV850269a2015-12-08 22:02:00 +000010010
10011 for (unsigned ArgNo : NonNull->args()) {
10012 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010013 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010014 return;
10015 }
George Burgess IV850269a2015-12-08 22:02:00 +000010016 }
10017 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010018 }
10019 }
George Burgess IV850269a2015-12-08 22:02:00 +000010020 }
10021
Richard Trieu3bb8b562014-02-26 02:36:06 +000010022 QualType T = D->getType();
10023 const bool IsArray = T->isArrayType();
10024 const bool IsFunction = T->isFunctionType();
10025
Richard Trieuc1888e02014-06-28 23:25:37 +000010026 // Address of function is used to silence the function warning.
10027 if (IsAddressOf && IsFunction) {
10028 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010029 }
10030
10031 // Found nothing.
10032 if (!IsAddressOf && !IsFunction && !IsArray)
10033 return;
10034
10035 // Pretty print the expression for the diagnostic.
10036 std::string Str;
10037 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +000010038 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +000010039
10040 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10041 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +000010042 enum {
10043 AddressOf,
10044 FunctionPointer,
10045 ArrayPointer
10046 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010047 if (IsAddressOf)
10048 DiagType = AddressOf;
10049 else if (IsFunction)
10050 DiagType = FunctionPointer;
10051 else if (IsArray)
10052 DiagType = ArrayPointer;
10053 else
10054 llvm_unreachable("Could not determine diagnostic.");
10055 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10056 << Range << IsEqual;
10057
10058 if (!IsFunction)
10059 return;
10060
10061 // Suggest '&' to silence the function warning.
10062 Diag(E->getExprLoc(), diag::note_function_warning_silence)
10063 << FixItHint::CreateInsertion(E->getLocStart(), "&");
10064
10065 // Check to see if '()' fixit should be emitted.
10066 QualType ReturnType;
10067 UnresolvedSet<4> NonTemplateOverloads;
10068 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10069 if (ReturnType.isNull())
10070 return;
10071
10072 if (IsCompare) {
10073 // There are two cases here. If there is null constant, the only suggest
10074 // for a pointer return type. If the null is 0, then suggest if the return
10075 // type is a pointer or an integer type.
10076 if (!ReturnType->isPointerType()) {
10077 if (NullKind == Expr::NPCK_ZeroExpression ||
10078 NullKind == Expr::NPCK_ZeroLiteral) {
10079 if (!ReturnType->isIntegerType())
10080 return;
10081 } else {
10082 return;
10083 }
10084 }
10085 } else { // !IsCompare
10086 // For function to bool, only suggest if the function pointer has bool
10087 // return type.
10088 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10089 return;
10090 }
10091 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +000010092 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +000010093}
10094
John McCallcc7e5bf2010-05-06 08:58:33 +000010095/// Diagnoses "dangerous" implicit conversions within the given
10096/// expression (which is a full expression). Implements -Wconversion
10097/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +000010098///
10099/// \param CC the "context" location of the implicit conversion, i.e.
10100/// the most location of the syntactic entity requiring the implicit
10101/// conversion
10102void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010103 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +000010104 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +000010105 return;
10106
10107 // Don't diagnose for value- or type-dependent expressions.
10108 if (E->isTypeDependent() || E->isValueDependent())
10109 return;
10110
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010111 // Check for array bounds violations in cases where the check isn't triggered
10112 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10113 // ArraySubscriptExpr is on the RHS of a variable initialization.
10114 CheckArrayAccess(E);
10115
John McCallacf0ee52010-10-08 02:01:28 +000010116 // This is not the right CC for (e.g.) a variable initialization.
10117 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010118}
10119
Richard Trieu65724892014-11-15 06:37:39 +000010120/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10121/// Input argument E is a logical expression.
10122void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10123 ::CheckBoolLikeConversion(*this, E, CC);
10124}
10125
Richard Smith9f7df0c2017-06-26 23:19:32 +000010126/// Diagnose when expression is an integer constant expression and its evaluation
10127/// results in integer overflow
10128void Sema::CheckForIntOverflow (Expr *E) {
10129 // Use a work list to deal with nested struct initializers.
10130 SmallVector<Expr *, 2> Exprs(1, E);
10131
10132 do {
10133 Expr *E = Exprs.pop_back_val();
10134
10135 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
10136 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10137 continue;
10138 }
10139
10140 if (auto InitList = dyn_cast<InitListExpr>(E))
10141 Exprs.append(InitList->inits().begin(), InitList->inits().end());
10142
10143 if (isa<ObjCBoxedExpr>(E))
10144 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10145 } while (!Exprs.empty());
10146}
10147
Richard Smithc406cb72013-01-17 01:17:56 +000010148namespace {
10149/// \brief Visitor for expressions which looks for unsequenced operations on the
10150/// same object.
10151class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010152 typedef EvaluatedExprVisitor<SequenceChecker> Base;
10153
Richard Smithc406cb72013-01-17 01:17:56 +000010154 /// \brief A tree of sequenced regions within an expression. Two regions are
10155 /// unsequenced if one is an ancestor or a descendent of the other. When we
10156 /// finish processing an expression with sequencing, such as a comma
10157 /// expression, we fold its tree nodes into its parent, since they are
10158 /// unsequenced with respect to nodes we will visit later.
10159 class SequenceTree {
10160 struct Value {
10161 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10162 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +000010163 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +000010164 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010165 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +000010166
10167 public:
10168 /// \brief A region within an expression which may be sequenced with respect
10169 /// to some other region.
10170 class Seq {
10171 explicit Seq(unsigned N) : Index(N) {}
10172 unsigned Index;
10173 friend class SequenceTree;
10174 public:
10175 Seq() : Index(0) {}
10176 };
10177
10178 SequenceTree() { Values.push_back(Value(0)); }
10179 Seq root() const { return Seq(0); }
10180
10181 /// \brief Create a new sequence of operations, which is an unsequenced
10182 /// subset of \p Parent. This sequence of operations is sequenced with
10183 /// respect to other children of \p Parent.
10184 Seq allocate(Seq Parent) {
10185 Values.push_back(Value(Parent.Index));
10186 return Seq(Values.size() - 1);
10187 }
10188
10189 /// \brief Merge a sequence of operations into its parent.
10190 void merge(Seq S) {
10191 Values[S.Index].Merged = true;
10192 }
10193
10194 /// \brief Determine whether two operations are unsequenced. This operation
10195 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10196 /// should have been merged into its parent as appropriate.
10197 bool isUnsequenced(Seq Cur, Seq Old) {
10198 unsigned C = representative(Cur.Index);
10199 unsigned Target = representative(Old.Index);
10200 while (C >= Target) {
10201 if (C == Target)
10202 return true;
10203 C = Values[C].Parent;
10204 }
10205 return false;
10206 }
10207
10208 private:
10209 /// \brief Pick a representative for a sequence.
10210 unsigned representative(unsigned K) {
10211 if (Values[K].Merged)
10212 // Perform path compression as we go.
10213 return Values[K].Parent = representative(Values[K].Parent);
10214 return K;
10215 }
10216 };
10217
10218 /// An object for which we can track unsequenced uses.
10219 typedef NamedDecl *Object;
10220
10221 /// Different flavors of object usage which we track. We only track the
10222 /// least-sequenced usage of each kind.
10223 enum UsageKind {
10224 /// A read of an object. Multiple unsequenced reads are OK.
10225 UK_Use,
10226 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000010227 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000010228 UK_ModAsValue,
10229 /// A modification of an object which is not sequenced before the value
10230 /// computation of the expression, such as n++.
10231 UK_ModAsSideEffect,
10232
10233 UK_Count = UK_ModAsSideEffect + 1
10234 };
10235
10236 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +000010237 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +000010238 Expr *Use;
10239 SequenceTree::Seq Seq;
10240 };
10241
10242 struct UsageInfo {
10243 UsageInfo() : Diagnosed(false) {}
10244 Usage Uses[UK_Count];
10245 /// Have we issued a diagnostic for this variable already?
10246 bool Diagnosed;
10247 };
10248 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
10249
10250 Sema &SemaRef;
10251 /// Sequenced regions within the expression.
10252 SequenceTree Tree;
10253 /// Declaration modifications and references which we have seen.
10254 UsageInfoMap UsageMap;
10255 /// The region we are currently within.
10256 SequenceTree::Seq Region;
10257 /// Filled in with declarations which were modified as a side-effect
10258 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010259 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +000010260 /// Expressions to check later. We defer checking these to reduce
10261 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010262 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000010263
10264 /// RAII object wrapping the visitation of a sequenced subexpression of an
10265 /// expression. At the end of this process, the side-effects of the evaluation
10266 /// become sequenced with respect to the value computation of the result, so
10267 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10268 /// UK_ModAsValue.
10269 struct SequencedSubexpression {
10270 SequencedSubexpression(SequenceChecker &Self)
10271 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10272 Self.ModAsSideEffect = &ModAsSideEffect;
10273 }
10274 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000010275 for (auto &M : llvm::reverse(ModAsSideEffect)) {
10276 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000010277 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000010278 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10279 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000010280 }
10281 Self.ModAsSideEffect = OldModAsSideEffect;
10282 }
10283
10284 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010285 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
10286 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000010287 };
10288
Richard Smith40238f02013-06-20 22:21:56 +000010289 /// RAII object wrapping the visitation of a subexpression which we might
10290 /// choose to evaluate as a constant. If any subexpression is evaluated and
10291 /// found to be non-constant, this allows us to suppress the evaluation of
10292 /// the outer expression.
10293 class EvaluationTracker {
10294 public:
10295 EvaluationTracker(SequenceChecker &Self)
10296 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
10297 Self.EvalTracker = this;
10298 }
10299 ~EvaluationTracker() {
10300 Self.EvalTracker = Prev;
10301 if (Prev)
10302 Prev->EvalOK &= EvalOK;
10303 }
10304
10305 bool evaluate(const Expr *E, bool &Result) {
10306 if (!EvalOK || E->isValueDependent())
10307 return false;
10308 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10309 return EvalOK;
10310 }
10311
10312 private:
10313 SequenceChecker &Self;
10314 EvaluationTracker *Prev;
10315 bool EvalOK;
10316 } *EvalTracker;
10317
Richard Smithc406cb72013-01-17 01:17:56 +000010318 /// \brief Find the object which is produced by the specified expression,
10319 /// if any.
10320 Object getObject(Expr *E, bool Mod) const {
10321 E = E->IgnoreParenCasts();
10322 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10323 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10324 return getObject(UO->getSubExpr(), Mod);
10325 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10326 if (BO->getOpcode() == BO_Comma)
10327 return getObject(BO->getRHS(), Mod);
10328 if (Mod && BO->isAssignmentOp())
10329 return getObject(BO->getLHS(), Mod);
10330 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10331 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10332 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10333 return ME->getMemberDecl();
10334 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10335 // FIXME: If this is a reference, map through to its value.
10336 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000010337 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010338 }
10339
10340 /// \brief Note that an object was modified or used by an expression.
10341 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10342 Usage &U = UI.Uses[UK];
10343 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10344 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10345 ModAsSideEffect->push_back(std::make_pair(O, U));
10346 U.Use = Ref;
10347 U.Seq = Region;
10348 }
10349 }
10350 /// \brief Check whether a modification or use conflicts with a prior usage.
10351 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10352 bool IsModMod) {
10353 if (UI.Diagnosed)
10354 return;
10355
10356 const Usage &U = UI.Uses[OtherKind];
10357 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10358 return;
10359
10360 Expr *Mod = U.Use;
10361 Expr *ModOrUse = Ref;
10362 if (OtherKind == UK_Use)
10363 std::swap(Mod, ModOrUse);
10364
10365 SemaRef.Diag(Mod->getExprLoc(),
10366 IsModMod ? diag::warn_unsequenced_mod_mod
10367 : diag::warn_unsequenced_mod_use)
10368 << O << SourceRange(ModOrUse->getExprLoc());
10369 UI.Diagnosed = true;
10370 }
10371
10372 void notePreUse(Object O, Expr *Use) {
10373 UsageInfo &U = UsageMap[O];
10374 // Uses conflict with other modifications.
10375 checkUsage(O, U, Use, UK_ModAsValue, false);
10376 }
10377 void notePostUse(Object O, Expr *Use) {
10378 UsageInfo &U = UsageMap[O];
10379 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10380 addUsage(U, O, Use, UK_Use);
10381 }
10382
10383 void notePreMod(Object O, Expr *Mod) {
10384 UsageInfo &U = UsageMap[O];
10385 // Modifications conflict with other modifications and with uses.
10386 checkUsage(O, U, Mod, UK_ModAsValue, true);
10387 checkUsage(O, U, Mod, UK_Use, false);
10388 }
10389 void notePostMod(Object O, Expr *Use, UsageKind UK) {
10390 UsageInfo &U = UsageMap[O];
10391 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10392 addUsage(U, O, Use, UK);
10393 }
10394
10395public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010396 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +000010397 : Base(S.Context), SemaRef(S), Region(Tree.root()),
10398 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010399 Visit(E);
10400 }
10401
10402 void VisitStmt(Stmt *S) {
10403 // Skip all statements which aren't expressions for now.
10404 }
10405
10406 void VisitExpr(Expr *E) {
10407 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000010408 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000010409 }
10410
10411 void VisitCastExpr(CastExpr *E) {
10412 Object O = Object();
10413 if (E->getCastKind() == CK_LValueToRValue)
10414 O = getObject(E->getSubExpr(), false);
10415
10416 if (O)
10417 notePreUse(O, E);
10418 VisitExpr(E);
10419 if (O)
10420 notePostUse(O, E);
10421 }
10422
10423 void VisitBinComma(BinaryOperator *BO) {
10424 // C++11 [expr.comma]p1:
10425 // Every value computation and side effect associated with the left
10426 // expression is sequenced before every value computation and side
10427 // effect associated with the right expression.
10428 SequenceTree::Seq LHS = Tree.allocate(Region);
10429 SequenceTree::Seq RHS = Tree.allocate(Region);
10430 SequenceTree::Seq OldRegion = Region;
10431
10432 {
10433 SequencedSubexpression SeqLHS(*this);
10434 Region = LHS;
10435 Visit(BO->getLHS());
10436 }
10437
10438 Region = RHS;
10439 Visit(BO->getRHS());
10440
10441 Region = OldRegion;
10442
10443 // Forget that LHS and RHS are sequenced. They are both unsequenced
10444 // with respect to other stuff.
10445 Tree.merge(LHS);
10446 Tree.merge(RHS);
10447 }
10448
10449 void VisitBinAssign(BinaryOperator *BO) {
10450 // The modification is sequenced after the value computation of the LHS
10451 // and RHS, so check it before inspecting the operands and update the
10452 // map afterwards.
10453 Object O = getObject(BO->getLHS(), true);
10454 if (!O)
10455 return VisitExpr(BO);
10456
10457 notePreMod(O, BO);
10458
10459 // C++11 [expr.ass]p7:
10460 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10461 // only once.
10462 //
10463 // Therefore, for a compound assignment operator, O is considered used
10464 // everywhere except within the evaluation of E1 itself.
10465 if (isa<CompoundAssignOperator>(BO))
10466 notePreUse(O, BO);
10467
10468 Visit(BO->getLHS());
10469
10470 if (isa<CompoundAssignOperator>(BO))
10471 notePostUse(O, BO);
10472
10473 Visit(BO->getRHS());
10474
Richard Smith83e37bee2013-06-26 23:16:51 +000010475 // C++11 [expr.ass]p1:
10476 // the assignment is sequenced [...] before the value computation of the
10477 // assignment expression.
10478 // C11 6.5.16/3 has no such rule.
10479 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10480 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010481 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010482
Richard Smithc406cb72013-01-17 01:17:56 +000010483 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10484 VisitBinAssign(CAO);
10485 }
10486
10487 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10488 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10489 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10490 Object O = getObject(UO->getSubExpr(), true);
10491 if (!O)
10492 return VisitExpr(UO);
10493
10494 notePreMod(O, UO);
10495 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000010496 // C++11 [expr.pre.incr]p1:
10497 // the expression ++x is equivalent to x+=1
10498 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10499 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010500 }
10501
10502 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10503 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10504 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10505 Object O = getObject(UO->getSubExpr(), true);
10506 if (!O)
10507 return VisitExpr(UO);
10508
10509 notePreMod(O, UO);
10510 Visit(UO->getSubExpr());
10511 notePostMod(O, UO, UK_ModAsSideEffect);
10512 }
10513
10514 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10515 void VisitBinLOr(BinaryOperator *BO) {
10516 // The side-effects of the LHS of an '&&' are sequenced before the
10517 // value computation of the RHS, and hence before the value computation
10518 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10519 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000010520 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010521 {
10522 SequencedSubexpression Sequenced(*this);
10523 Visit(BO->getLHS());
10524 }
10525
10526 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010527 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010528 if (!Result)
10529 Visit(BO->getRHS());
10530 } else {
10531 // Check for unsequenced operations in the RHS, treating it as an
10532 // entirely separate evaluation.
10533 //
10534 // FIXME: If there are operations in the RHS which are unsequenced
10535 // with respect to operations outside the RHS, and those operations
10536 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000010537 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010538 }
Richard Smithc406cb72013-01-17 01:17:56 +000010539 }
10540 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000010541 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010542 {
10543 SequencedSubexpression Sequenced(*this);
10544 Visit(BO->getLHS());
10545 }
10546
10547 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010548 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010549 if (Result)
10550 Visit(BO->getRHS());
10551 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000010552 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010553 }
Richard Smithc406cb72013-01-17 01:17:56 +000010554 }
10555
10556 // Only visit the condition, unless we can be sure which subexpression will
10557 // be chosen.
10558 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000010559 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000010560 {
10561 SequencedSubexpression Sequenced(*this);
10562 Visit(CO->getCond());
10563 }
Richard Smithc406cb72013-01-17 01:17:56 +000010564
10565 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010566 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000010567 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010568 else {
Richard Smithd33f5202013-01-17 23:18:09 +000010569 WorkList.push_back(CO->getTrueExpr());
10570 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010571 }
Richard Smithc406cb72013-01-17 01:17:56 +000010572 }
10573
Richard Smithe3dbfe02013-06-30 10:40:20 +000010574 void VisitCallExpr(CallExpr *CE) {
10575 // C++11 [intro.execution]p15:
10576 // When calling a function [...], every value computation and side effect
10577 // associated with any argument expression, or with the postfix expression
10578 // designating the called function, is sequenced before execution of every
10579 // expression or statement in the body of the function [and thus before
10580 // the value computation of its result].
10581 SequencedSubexpression Sequenced(*this);
10582 Base::VisitCallExpr(CE);
10583
10584 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10585 }
10586
Richard Smithc406cb72013-01-17 01:17:56 +000010587 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010588 // This is a call, so all subexpressions are sequenced before the result.
10589 SequencedSubexpression Sequenced(*this);
10590
Richard Smithc406cb72013-01-17 01:17:56 +000010591 if (!CCE->isListInitialization())
10592 return VisitExpr(CCE);
10593
10594 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010595 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010596 SequenceTree::Seq Parent = Region;
10597 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10598 E = CCE->arg_end();
10599 I != E; ++I) {
10600 Region = Tree.allocate(Parent);
10601 Elts.push_back(Region);
10602 Visit(*I);
10603 }
10604
10605 // Forget that the initializers are sequenced.
10606 Region = Parent;
10607 for (unsigned I = 0; I < Elts.size(); ++I)
10608 Tree.merge(Elts[I]);
10609 }
10610
10611 void VisitInitListExpr(InitListExpr *ILE) {
10612 if (!SemaRef.getLangOpts().CPlusPlus11)
10613 return VisitExpr(ILE);
10614
10615 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010616 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010617 SequenceTree::Seq Parent = Region;
10618 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10619 Expr *E = ILE->getInit(I);
10620 if (!E) continue;
10621 Region = Tree.allocate(Parent);
10622 Elts.push_back(Region);
10623 Visit(E);
10624 }
10625
10626 // Forget that the initializers are sequenced.
10627 Region = Parent;
10628 for (unsigned I = 0; I < Elts.size(); ++I)
10629 Tree.merge(Elts[I]);
10630 }
10631};
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010632} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +000010633
10634void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010635 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000010636 WorkList.push_back(E);
10637 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000010638 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000010639 SequenceChecker(*this, Item, WorkList);
10640 }
Richard Smithc406cb72013-01-17 01:17:56 +000010641}
10642
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010643void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10644 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010645 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000010646 if (!E->isInstantiationDependent())
10647 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010648 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000010649 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010650 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000010651}
10652
John McCall1f425642010-11-11 03:21:53 +000010653void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10654 FieldDecl *BitField,
10655 Expr *Init) {
10656 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10657}
10658
David Majnemer61a5bbf2015-04-07 22:08:51 +000010659static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10660 SourceLocation Loc) {
10661 if (!PType->isVariablyModifiedType())
10662 return;
10663 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10664 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10665 return;
10666 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000010667 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10668 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10669 return;
10670 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000010671 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10672 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10673 return;
10674 }
10675
10676 const ArrayType *AT = S.Context.getAsArrayType(PType);
10677 if (!AT)
10678 return;
10679
10680 if (AT->getSizeModifier() != ArrayType::Star) {
10681 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10682 return;
10683 }
10684
10685 S.Diag(Loc, diag::err_array_star_in_function_definition);
10686}
10687
Mike Stump0c2ec772010-01-21 03:59:47 +000010688/// CheckParmsForFunctionDef - Check that the parameters of the given
10689/// function are appropriate for the definition of a function. This
10690/// takes care of any checks that cannot be performed on the
10691/// declaration itself, e.g., that the types of each of the function
10692/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000010693bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000010694 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010695 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000010696 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010697 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10698 // function declarator that is part of a function definition of
10699 // that function shall not have incomplete type.
10700 //
10701 // This is also C++ [dcl.fct]p6.
10702 if (!Param->isInvalidDecl() &&
10703 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010704 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010705 Param->setInvalidDecl();
10706 HasInvalidParm = true;
10707 }
10708
10709 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10710 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000010711 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000010712 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000010713 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000010714 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000010715 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000010716
10717 // C99 6.7.5.3p12:
10718 // If the function declarator is not part of a definition of that
10719 // function, parameters may have incomplete type and may use the [*]
10720 // notation in their sequences of declarator specifiers to specify
10721 // variable length array types.
10722 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000010723 // FIXME: This diagnostic should point the '[*]' if source-location
10724 // information is added for it.
10725 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010726
10727 // MSVC destroys objects passed by value in the callee. Therefore a
10728 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010729 // object's destructor. However, we don't perform any direct access check
10730 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +000010731 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10732 .getCXXABI()
10733 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +000010734 if (!Param->isInvalidDecl()) {
10735 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10736 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10737 if (!ClassDecl->isInvalidDecl() &&
10738 !ClassDecl->hasIrrelevantDestructor() &&
10739 !ClassDecl->isDependentContext()) {
10740 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10741 MarkFunctionReferenced(Param->getLocation(), Destructor);
10742 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10743 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010744 }
10745 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010746 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010747
10748 // Parameters with the pass_object_size attribute only need to be marked
10749 // constant at function definitions. Because we lack information about
10750 // whether we're on a declaration or definition when we're instantiating the
10751 // attribute, we need to check for constness here.
10752 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10753 if (!Param->getType().isConstQualified())
10754 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10755 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000010756 }
10757
10758 return HasInvalidParm;
10759}
John McCall2b5c1b22010-08-12 21:44:57 +000010760
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010761/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10762/// or MemberExpr.
10763static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10764 ASTContext &Context) {
10765 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10766 return Context.getDeclAlign(DRE->getDecl());
10767
10768 if (const auto *ME = dyn_cast<MemberExpr>(E))
10769 return Context.getDeclAlign(ME->getMemberDecl());
10770
10771 return TypeAlign;
10772}
10773
John McCall2b5c1b22010-08-12 21:44:57 +000010774/// CheckCastAlign - Implements -Wcast-align, which warns when a
10775/// pointer cast increases the alignment requirements.
10776void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10777 // This is actually a lot of work to potentially be doing on every
10778 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010779 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000010780 return;
10781
10782 // Ignore dependent types.
10783 if (T->isDependentType() || Op->getType()->isDependentType())
10784 return;
10785
10786 // Require that the destination be a pointer type.
10787 const PointerType *DestPtr = T->getAs<PointerType>();
10788 if (!DestPtr) return;
10789
10790 // If the destination has alignment 1, we're done.
10791 QualType DestPointee = DestPtr->getPointeeType();
10792 if (DestPointee->isIncompleteType()) return;
10793 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10794 if (DestAlign.isOne()) return;
10795
10796 // Require that the source be a pointer type.
10797 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10798 if (!SrcPtr) return;
10799 QualType SrcPointee = SrcPtr->getPointeeType();
10800
10801 // Whitelist casts from cv void*. We already implicitly
10802 // whitelisted casts to cv void*, since they have alignment 1.
10803 // Also whitelist casts involving incomplete types, which implicitly
10804 // includes 'void'.
10805 if (SrcPointee->isIncompleteType()) return;
10806
10807 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010808
10809 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10810 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10811 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10812 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10813 if (UO->getOpcode() == UO_AddrOf)
10814 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10815 }
10816
John McCall2b5c1b22010-08-12 21:44:57 +000010817 if (SrcAlign >= DestAlign) return;
10818
10819 Diag(TRange.getBegin(), diag::warn_cast_align)
10820 << Op->getType() << T
10821 << static_cast<unsigned>(SrcAlign.getQuantity())
10822 << static_cast<unsigned>(DestAlign.getQuantity())
10823 << TRange << Op->getSourceRange();
10824}
10825
Chandler Carruth28389f02011-08-05 09:10:50 +000010826/// \brief Check whether this array fits the idiom of a size-one tail padded
10827/// array member of a struct.
10828///
10829/// We avoid emitting out-of-bounds access warnings for such arrays as they are
10830/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000010831static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000010832 const NamedDecl *ND) {
10833 if (Size != 1 || !ND) return false;
10834
10835 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10836 if (!FD) return false;
10837
10838 // Don't consider sizes resulting from macro expansions or template argument
10839 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000010840
10841 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010842 while (TInfo) {
10843 TypeLoc TL = TInfo->getTypeLoc();
10844 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000010845 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10846 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010847 TInfo = TDL->getTypeSourceInfo();
10848 continue;
10849 }
David Blaikie6adc78e2013-02-18 22:06:02 +000010850 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10851 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000010852 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10853 return false;
10854 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010855 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000010856 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010857
10858 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000010859 if (!RD) return false;
10860 if (RD->isUnion()) return false;
10861 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10862 if (!CRD->isStandardLayout()) return false;
10863 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010864
Benjamin Kramer8c543672011-08-06 03:04:42 +000010865 // See if this is the last field decl in the record.
10866 const Decl *D = FD;
10867 while ((D = D->getNextDeclInContext()))
10868 if (isa<FieldDecl>(D))
10869 return false;
10870 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000010871}
10872
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010873void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010874 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000010875 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010876 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010877 if (IndexExpr->isValueDependent())
10878 return;
10879
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010880 const Type *EffectiveType =
10881 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010882 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010883 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010884 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010885 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000010886 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000010887
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010888 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000010889 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000010890 return;
Richard Smith13f67182011-12-16 19:31:14 +000010891 if (IndexNegated)
10892 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000010893
Craig Topperc3ec1492014-05-26 06:22:03 +000010894 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000010895 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10896 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +000010897 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +000010898 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +000010899
Ted Kremeneke4b316c2011-02-23 23:06:04 +000010900 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010901 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000010902 if (!size.isStrictlyPositive())
10903 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010904
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010905 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000010906 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010907 // Make sure we're comparing apples to apples when comparing index to size
10908 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10909 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000010910 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000010911 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010912 if (ptrarith_typesize != array_typesize) {
10913 // There's a cast to a different size type involved
10914 uint64_t ratio = array_typesize / ptrarith_typesize;
10915 // TODO: Be smarter about handling cases where array_typesize is not a
10916 // multiple of ptrarith_typesize
10917 if (ptrarith_typesize * ratio == array_typesize)
10918 size *= llvm::APInt(size.getBitWidth(), ratio);
10919 }
10920 }
10921
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010922 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010923 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010924 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010925 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010926
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010927 // For array subscripting the index must be less than size, but for pointer
10928 // arithmetic also allow the index (offset) to be equal to size since
10929 // computing the next address after the end of the array is legal and
10930 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010931 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000010932 return;
10933
10934 // Also don't warn for arrays of size 1 which are members of some
10935 // structure. These are often used to approximate flexible arrays in C89
10936 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010937 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000010938 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010939
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010940 // Suppress the warning if the subscript expression (as identified by the
10941 // ']' location) and the index expression are both from macro expansions
10942 // within a system header.
10943 if (ASE) {
10944 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10945 ASE->getRBracketLoc());
10946 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10947 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10948 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000010949 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010950 return;
10951 }
10952 }
10953
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010954 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010955 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010956 DiagID = diag::warn_array_index_exceeds_bounds;
10957
10958 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10959 PDiag(DiagID) << index.toString(10, true)
10960 << size.toString(10, true)
10961 << (unsigned)size.getLimitedValue(~0U)
10962 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010963 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010964 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010965 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010966 DiagID = diag::warn_ptr_arith_precedes_bounds;
10967 if (index.isNegative()) index = -index;
10968 }
10969
10970 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10971 PDiag(DiagID) << index.toString(10, true)
10972 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000010973 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000010974
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000010975 if (!ND) {
10976 // Try harder to find a NamedDecl to point at in the note.
10977 while (const ArraySubscriptExpr *ASE =
10978 dyn_cast<ArraySubscriptExpr>(BaseExpr))
10979 BaseExpr = ASE->getBase()->IgnoreParenCasts();
10980 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10981 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10982 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10983 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10984 }
10985
Chandler Carruth1af88f12011-02-17 21:10:52 +000010986 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010987 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10988 PDiag(diag::note_array_index_out_of_bounds)
10989 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000010990}
10991
Ted Kremenekdf26df72011-03-01 18:41:00 +000010992void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010993 int AllowOnePastEnd = 0;
10994 while (expr) {
10995 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000010996 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010997 case Stmt::ArraySubscriptExprClass: {
10998 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010999 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011000 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +000011001 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011002 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000011003 case Stmt::OMPArraySectionExprClass: {
11004 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11005 if (ASE->getLowerBound())
11006 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11007 /*ASE=*/nullptr, AllowOnePastEnd > 0);
11008 return;
11009 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011010 case Stmt::UnaryOperatorClass: {
11011 // Only unwrap the * and & unary operators
11012 const UnaryOperator *UO = cast<UnaryOperator>(expr);
11013 expr = UO->getSubExpr();
11014 switch (UO->getOpcode()) {
11015 case UO_AddrOf:
11016 AllowOnePastEnd++;
11017 break;
11018 case UO_Deref:
11019 AllowOnePastEnd--;
11020 break;
11021 default:
11022 return;
11023 }
11024 break;
11025 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011026 case Stmt::ConditionalOperatorClass: {
11027 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11028 if (const Expr *lhs = cond->getLHS())
11029 CheckArrayAccess(lhs);
11030 if (const Expr *rhs = cond->getRHS())
11031 CheckArrayAccess(rhs);
11032 return;
11033 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000011034 case Stmt::CXXOperatorCallExprClass: {
11035 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11036 for (const auto *Arg : OCE->arguments())
11037 CheckArrayAccess(Arg);
11038 return;
11039 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011040 default:
11041 return;
11042 }
Peter Collingbourne91147592011-04-15 00:35:48 +000011043 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011044}
John McCall31168b02011-06-15 23:02:42 +000011045
11046//===--- CHECK: Objective-C retain cycles ----------------------------------//
11047
11048namespace {
11049 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +000011050 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +000011051 VarDecl *Variable;
11052 SourceRange Range;
11053 SourceLocation Loc;
11054 bool Indirect;
11055
11056 void setLocsFrom(Expr *e) {
11057 Loc = e->getExprLoc();
11058 Range = e->getSourceRange();
11059 }
11060 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011061} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000011062
11063/// Consider whether capturing the given variable can possibly lead to
11064/// a retain cycle.
11065static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000011066 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000011067 // lifetime. In MRR, it's captured strongly if the variable is
11068 // __block and has an appropriate type.
11069 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11070 return false;
11071
11072 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011073 if (ref)
11074 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000011075 return true;
11076}
11077
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011078static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000011079 while (true) {
11080 e = e->IgnoreParens();
11081 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11082 switch (cast->getCastKind()) {
11083 case CK_BitCast:
11084 case CK_LValueBitCast:
11085 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000011086 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000011087 e = cast->getSubExpr();
11088 continue;
11089
John McCall31168b02011-06-15 23:02:42 +000011090 default:
11091 return false;
11092 }
11093 }
11094
11095 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11096 ObjCIvarDecl *ivar = ref->getDecl();
11097 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11098 return false;
11099
11100 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011101 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000011102 return false;
11103
11104 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11105 owner.Indirect = true;
11106 return true;
11107 }
11108
11109 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11110 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11111 if (!var) return false;
11112 return considerVariable(var, ref, owner);
11113 }
11114
John McCall31168b02011-06-15 23:02:42 +000011115 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11116 if (member->isArrow()) return false;
11117
11118 // Don't count this as an indirect ownership.
11119 e = member->getBase();
11120 continue;
11121 }
11122
John McCallfe96e0b2011-11-06 09:01:30 +000011123 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11124 // Only pay attention to pseudo-objects on property references.
11125 ObjCPropertyRefExpr *pre
11126 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11127 ->IgnoreParens());
11128 if (!pre) return false;
11129 if (pre->isImplicitProperty()) return false;
11130 ObjCPropertyDecl *property = pre->getExplicitProperty();
11131 if (!property->isRetaining() &&
11132 !(property->getPropertyIvarDecl() &&
11133 property->getPropertyIvarDecl()->getType()
11134 .getObjCLifetime() == Qualifiers::OCL_Strong))
11135 return false;
11136
11137 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011138 if (pre->isSuperReceiver()) {
11139 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11140 if (!owner.Variable)
11141 return false;
11142 owner.Loc = pre->getLocation();
11143 owner.Range = pre->getSourceRange();
11144 return true;
11145 }
John McCallfe96e0b2011-11-06 09:01:30 +000011146 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11147 ->getSourceExpr());
11148 continue;
11149 }
11150
John McCall31168b02011-06-15 23:02:42 +000011151 // Array ivars?
11152
11153 return false;
11154 }
11155}
11156
11157namespace {
11158 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
11159 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11160 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011161 Context(Context), Variable(variable), Capturer(nullptr),
11162 VarWillBeReased(false) {}
11163 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000011164 VarDecl *Variable;
11165 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011166 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +000011167
11168 void VisitDeclRefExpr(DeclRefExpr *ref) {
11169 if (ref->getDecl() == Variable && !Capturer)
11170 Capturer = ref;
11171 }
11172
John McCall31168b02011-06-15 23:02:42 +000011173 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11174 if (Capturer) return;
11175 Visit(ref->getBase());
11176 if (Capturer && ref->isFreeIvar())
11177 Capturer = ref;
11178 }
11179
11180 void VisitBlockExpr(BlockExpr *block) {
11181 // Look inside nested blocks
11182 if (block->getBlockDecl()->capturesVariable(Variable))
11183 Visit(block->getBlockDecl()->getBody());
11184 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000011185
11186 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11187 if (Capturer) return;
11188 if (OVE->getSourceExpr())
11189 Visit(OVE->getSourceExpr());
11190 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011191 void VisitBinaryOperator(BinaryOperator *BinOp) {
11192 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11193 return;
11194 Expr *LHS = BinOp->getLHS();
11195 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11196 if (DRE->getDecl() != Variable)
11197 return;
11198 if (Expr *RHS = BinOp->getRHS()) {
11199 RHS = RHS->IgnoreParenCasts();
11200 llvm::APSInt Value;
11201 VarWillBeReased =
11202 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11203 }
11204 }
11205 }
John McCall31168b02011-06-15 23:02:42 +000011206 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011207} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000011208
11209/// Check whether the given argument is a block which captures a
11210/// variable.
11211static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11212 assert(owner.Variable && owner.Loc.isValid());
11213
11214 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000011215
11216 // Look through [^{...} copy] and Block_copy(^{...}).
11217 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11218 Selector Cmd = ME->getSelector();
11219 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11220 e = ME->getInstanceReceiver();
11221 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000011222 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000011223 e = e->IgnoreParenCasts();
11224 }
11225 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11226 if (CE->getNumArgs() == 1) {
11227 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000011228 if (Fn) {
11229 const IdentifierInfo *FnI = Fn->getIdentifier();
11230 if (FnI && FnI->isStr("_Block_copy")) {
11231 e = CE->getArg(0)->IgnoreParenCasts();
11232 }
11233 }
Jordan Rose67e887c2012-09-17 17:54:30 +000011234 }
11235 }
11236
John McCall31168b02011-06-15 23:02:42 +000011237 BlockExpr *block = dyn_cast<BlockExpr>(e);
11238 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000011239 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011240
11241 FindCaptureVisitor visitor(S.Context, owner.Variable);
11242 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011243 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000011244}
11245
11246static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11247 RetainCycleOwner &owner) {
11248 assert(capturer);
11249 assert(owner.Variable && owner.Loc.isValid());
11250
11251 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11252 << owner.Variable << capturer->getSourceRange();
11253 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11254 << owner.Indirect << owner.Range;
11255}
11256
11257/// Check for a keyword selector that starts with the word 'add' or
11258/// 'set'.
11259static bool isSetterLikeSelector(Selector sel) {
11260 if (sel.isUnarySelector()) return false;
11261
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011262 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000011263 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011264 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000011265 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011266 else if (str.startswith("add")) {
11267 // Specially whitelist 'addOperationWithBlock:'.
11268 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11269 return false;
11270 str = str.substr(3);
11271 }
John McCall31168b02011-06-15 23:02:42 +000011272 else
11273 return false;
11274
11275 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000011276 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000011277}
11278
Benjamin Kramer3a743452015-03-09 15:03:32 +000011279static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11280 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011281 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11282 Message->getReceiverInterface(),
11283 NSAPI::ClassId_NSMutableArray);
11284 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011285 return None;
11286 }
11287
11288 Selector Sel = Message->getSelector();
11289
11290 Optional<NSAPI::NSArrayMethodKind> MKOpt =
11291 S.NSAPIObj->getNSArrayMethodKind(Sel);
11292 if (!MKOpt) {
11293 return None;
11294 }
11295
11296 NSAPI::NSArrayMethodKind MK = *MKOpt;
11297
11298 switch (MK) {
11299 case NSAPI::NSMutableArr_addObject:
11300 case NSAPI::NSMutableArr_insertObjectAtIndex:
11301 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11302 return 0;
11303 case NSAPI::NSMutableArr_replaceObjectAtIndex:
11304 return 1;
11305
11306 default:
11307 return None;
11308 }
11309
11310 return None;
11311}
11312
11313static
11314Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11315 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011316 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11317 Message->getReceiverInterface(),
11318 NSAPI::ClassId_NSMutableDictionary);
11319 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011320 return None;
11321 }
11322
11323 Selector Sel = Message->getSelector();
11324
11325 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11326 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11327 if (!MKOpt) {
11328 return None;
11329 }
11330
11331 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11332
11333 switch (MK) {
11334 case NSAPI::NSMutableDict_setObjectForKey:
11335 case NSAPI::NSMutableDict_setValueForKey:
11336 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11337 return 0;
11338
11339 default:
11340 return None;
11341 }
11342
11343 return None;
11344}
11345
11346static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011347 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11348 Message->getReceiverInterface(),
11349 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000011350
Alex Denisov5dfac812015-08-06 04:51:14 +000011351 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11352 Message->getReceiverInterface(),
11353 NSAPI::ClassId_NSMutableOrderedSet);
11354 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011355 return None;
11356 }
11357
11358 Selector Sel = Message->getSelector();
11359
11360 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11361 if (!MKOpt) {
11362 return None;
11363 }
11364
11365 NSAPI::NSSetMethodKind MK = *MKOpt;
11366
11367 switch (MK) {
11368 case NSAPI::NSMutableSet_addObject:
11369 case NSAPI::NSOrderedSet_setObjectAtIndex:
11370 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11371 case NSAPI::NSOrderedSet_insertObjectAtIndex:
11372 return 0;
11373 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11374 return 1;
11375 }
11376
11377 return None;
11378}
11379
11380void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11381 if (!Message->isInstanceMessage()) {
11382 return;
11383 }
11384
11385 Optional<int> ArgOpt;
11386
11387 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11388 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11389 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11390 return;
11391 }
11392
11393 int ArgIndex = *ArgOpt;
11394
Alex Denisove1d882c2015-03-04 17:55:52 +000011395 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11396 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11397 Arg = OE->getSourceExpr()->IgnoreImpCasts();
11398 }
11399
Alex Denisov5dfac812015-08-06 04:51:14 +000011400 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011401 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011402 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011403 Diag(Message->getSourceRange().getBegin(),
11404 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000011405 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000011406 }
11407 }
Alex Denisov5dfac812015-08-06 04:51:14 +000011408 } else {
11409 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11410
11411 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11412 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11413 }
11414
11415 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11416 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11417 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11418 ValueDecl *Decl = ReceiverRE->getDecl();
11419 Diag(Message->getSourceRange().getBegin(),
11420 diag::warn_objc_circular_container)
11421 << Decl->getName() << Decl->getName();
11422 if (!ArgRE->isObjCSelfExpr()) {
11423 Diag(Decl->getLocation(),
11424 diag::note_objc_circular_container_declared_here)
11425 << Decl->getName();
11426 }
11427 }
11428 }
11429 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11430 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11431 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11432 ObjCIvarDecl *Decl = IvarRE->getDecl();
11433 Diag(Message->getSourceRange().getBegin(),
11434 diag::warn_objc_circular_container)
11435 << Decl->getName() << Decl->getName();
11436 Diag(Decl->getLocation(),
11437 diag::note_objc_circular_container_declared_here)
11438 << Decl->getName();
11439 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011440 }
11441 }
11442 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011443}
11444
John McCall31168b02011-06-15 23:02:42 +000011445/// Check a message send to see if it's likely to cause a retain cycle.
11446void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11447 // Only check instance methods whose selector looks like a setter.
11448 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11449 return;
11450
11451 // Try to find a variable that the receiver is strongly owned by.
11452 RetainCycleOwner owner;
11453 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011454 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000011455 return;
11456 } else {
11457 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11458 owner.Variable = getCurMethodDecl()->getSelfDecl();
11459 owner.Loc = msg->getSuperLoc();
11460 owner.Range = msg->getSuperLoc();
11461 }
11462
11463 // Check whether the receiver is captured by any of the arguments.
11464 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
11465 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
11466 return diagnoseRetainCycle(*this, capturer, owner);
11467}
11468
11469/// Check a property assign to see if it's likely to cause a retain cycle.
11470void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11471 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011472 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000011473 return;
11474
11475 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11476 diagnoseRetainCycle(*this, capturer, owner);
11477}
11478
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011479void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11480 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000011481 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011482 return;
11483
11484 // Because we don't have an expression for the variable, we have to set the
11485 // location explicitly here.
11486 Owner.Loc = Var->getLocation();
11487 Owner.Range = Var->getSourceRange();
11488
11489 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11490 diagnoseRetainCycle(*this, Capturer, Owner);
11491}
11492
Ted Kremenek9304da92012-12-21 08:04:28 +000011493static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11494 Expr *RHS, bool isProperty) {
11495 // Check if RHS is an Objective-C object literal, which also can get
11496 // immediately zapped in a weak reference. Note that we explicitly
11497 // allow ObjCStringLiterals, since those are designed to never really die.
11498 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011499
Ted Kremenek64873352012-12-21 22:46:35 +000011500 // This enum needs to match with the 'select' in
11501 // warn_objc_arc_literal_assign (off-by-1).
11502 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11503 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11504 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011505
11506 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000011507 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000011508 << (isProperty ? 0 : 1)
11509 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011510
11511 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000011512}
11513
Ted Kremenekc1f014a2012-12-21 19:45:30 +000011514static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11515 Qualifiers::ObjCLifetime LT,
11516 Expr *RHS, bool isProperty) {
11517 // Strip off any implicit cast added to get to the one ARC-specific.
11518 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11519 if (cast->getCastKind() == CK_ARCConsumeObject) {
11520 S.Diag(Loc, diag::warn_arc_retained_assign)
11521 << (LT == Qualifiers::OCL_ExplicitNone)
11522 << (isProperty ? 0 : 1)
11523 << RHS->getSourceRange();
11524 return true;
11525 }
11526 RHS = cast->getSubExpr();
11527 }
11528
11529 if (LT == Qualifiers::OCL_Weak &&
11530 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11531 return true;
11532
11533 return false;
11534}
11535
Ted Kremenekb36234d2012-12-21 08:04:20 +000011536bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11537 QualType LHS, Expr *RHS) {
11538 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11539
11540 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11541 return false;
11542
11543 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11544 return true;
11545
11546 return false;
11547}
11548
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011549void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11550 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011551 QualType LHSType;
11552 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011553 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011554 ObjCPropertyRefExpr *PRE
11555 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11556 if (PRE && !PRE->isImplicitProperty()) {
11557 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11558 if (PD)
11559 LHSType = PD->getType();
11560 }
11561
11562 if (LHSType.isNull())
11563 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000011564
11565 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11566
11567 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011568 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000011569 getCurFunction()->markSafeWeakUse(LHS);
11570 }
11571
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011572 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11573 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000011574
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011575 // FIXME. Check for other life times.
11576 if (LT != Qualifiers::OCL_None)
11577 return;
11578
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011579 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011580 if (PRE->isImplicitProperty())
11581 return;
11582 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11583 if (!PD)
11584 return;
11585
Bill Wendling44426052012-12-20 19:22:21 +000011586 unsigned Attributes = PD->getPropertyAttributes();
11587 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011588 // when 'assign' attribute was not explicitly specified
11589 // by user, ignore it and rely on property type itself
11590 // for lifetime info.
11591 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11592 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11593 LHSType->isObjCRetainableType())
11594 return;
11595
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011596 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000011597 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011598 Diag(Loc, diag::warn_arc_retained_property_assign)
11599 << RHS->getSourceRange();
11600 return;
11601 }
11602 RHS = cast->getSubExpr();
11603 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011604 }
Bill Wendling44426052012-12-20 19:22:21 +000011605 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000011606 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11607 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000011608 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011609 }
11610}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011611
11612//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11613
11614namespace {
11615bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11616 SourceLocation StmtLoc,
11617 const NullStmt *Body) {
11618 // Do not warn if the body is a macro that expands to nothing, e.g:
11619 //
11620 // #define CALL(x)
11621 // if (condition)
11622 // CALL(0);
11623 //
11624 if (Body->hasLeadingEmptyMacro())
11625 return false;
11626
11627 // Get line numbers of statement and body.
11628 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000011629 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011630 &StmtLineInvalid);
11631 if (StmtLineInvalid)
11632 return false;
11633
11634 bool BodyLineInvalid;
11635 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11636 &BodyLineInvalid);
11637 if (BodyLineInvalid)
11638 return false;
11639
11640 // Warn if null statement and body are on the same line.
11641 if (StmtLine != BodyLine)
11642 return false;
11643
11644 return true;
11645}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011646} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011647
11648void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11649 const Stmt *Body,
11650 unsigned DiagID) {
11651 // Since this is a syntactic check, don't emit diagnostic for template
11652 // instantiations, this just adds noise.
11653 if (CurrentInstantiationScope)
11654 return;
11655
11656 // The body should be a null statement.
11657 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11658 if (!NBody)
11659 return;
11660
11661 // Do the usual checks.
11662 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11663 return;
11664
11665 Diag(NBody->getSemiLoc(), DiagID);
11666 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11667}
11668
11669void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11670 const Stmt *PossibleBody) {
11671 assert(!CurrentInstantiationScope); // Ensured by caller
11672
11673 SourceLocation StmtLoc;
11674 const Stmt *Body;
11675 unsigned DiagID;
11676 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11677 StmtLoc = FS->getRParenLoc();
11678 Body = FS->getBody();
11679 DiagID = diag::warn_empty_for_body;
11680 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11681 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11682 Body = WS->getBody();
11683 DiagID = diag::warn_empty_while_body;
11684 } else
11685 return; // Neither `for' nor `while'.
11686
11687 // The body should be a null statement.
11688 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11689 if (!NBody)
11690 return;
11691
11692 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011693 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011694 return;
11695
11696 // Do the usual checks.
11697 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11698 return;
11699
11700 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11701 // noise level low, emit diagnostics only if for/while is followed by a
11702 // CompoundStmt, e.g.:
11703 // for (int i = 0; i < n; i++);
11704 // {
11705 // a(i);
11706 // }
11707 // or if for/while is followed by a statement with more indentation
11708 // than for/while itself:
11709 // for (int i = 0; i < n; i++);
11710 // a(i);
11711 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11712 if (!ProbableTypo) {
11713 bool BodyColInvalid;
11714 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11715 PossibleBody->getLocStart(),
11716 &BodyColInvalid);
11717 if (BodyColInvalid)
11718 return;
11719
11720 bool StmtColInvalid;
11721 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11722 S->getLocStart(),
11723 &StmtColInvalid);
11724 if (StmtColInvalid)
11725 return;
11726
11727 if (BodyCol > StmtCol)
11728 ProbableTypo = true;
11729 }
11730
11731 if (ProbableTypo) {
11732 Diag(NBody->getSemiLoc(), DiagID);
11733 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11734 }
11735}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011736
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011737//===--- CHECK: Warn on self move with std::move. -------------------------===//
11738
11739/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11740void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11741 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011742 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11743 return;
11744
Richard Smith51ec0cf2017-02-21 01:17:38 +000011745 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011746 return;
11747
11748 // Strip parens and casts away.
11749 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11750 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11751
11752 // Check for a call expression
11753 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11754 if (!CE || CE->getNumArgs() != 1)
11755 return;
11756
11757 // Check for a call to std::move
11758 const FunctionDecl *FD = CE->getDirectCallee();
11759 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11760 !FD->getIdentifier()->isStr("move"))
11761 return;
11762
11763 // Get argument from std::move
11764 RHSExpr = CE->getArg(0);
11765
11766 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11767 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11768
11769 // Two DeclRefExpr's, check that the decls are the same.
11770 if (LHSDeclRef && RHSDeclRef) {
11771 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11772 return;
11773 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11774 RHSDeclRef->getDecl()->getCanonicalDecl())
11775 return;
11776
11777 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11778 << LHSExpr->getSourceRange()
11779 << RHSExpr->getSourceRange();
11780 return;
11781 }
11782
11783 // Member variables require a different approach to check for self moves.
11784 // MemberExpr's are the same if every nested MemberExpr refers to the same
11785 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11786 // the base Expr's are CXXThisExpr's.
11787 const Expr *LHSBase = LHSExpr;
11788 const Expr *RHSBase = RHSExpr;
11789 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11790 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11791 if (!LHSME || !RHSME)
11792 return;
11793
11794 while (LHSME && RHSME) {
11795 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11796 RHSME->getMemberDecl()->getCanonicalDecl())
11797 return;
11798
11799 LHSBase = LHSME->getBase();
11800 RHSBase = RHSME->getBase();
11801 LHSME = dyn_cast<MemberExpr>(LHSBase);
11802 RHSME = dyn_cast<MemberExpr>(RHSBase);
11803 }
11804
11805 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11806 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11807 if (LHSDeclRef && RHSDeclRef) {
11808 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11809 return;
11810 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11811 RHSDeclRef->getDecl()->getCanonicalDecl())
11812 return;
11813
11814 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11815 << LHSExpr->getSourceRange()
11816 << RHSExpr->getSourceRange();
11817 return;
11818 }
11819
11820 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11821 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11822 << LHSExpr->getSourceRange()
11823 << RHSExpr->getSourceRange();
11824}
11825
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011826//===--- Layout compatibility ----------------------------------------------//
11827
11828namespace {
11829
11830bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11831
11832/// \brief Check if two enumeration types are layout-compatible.
11833bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11834 // C++11 [dcl.enum] p8:
11835 // Two enumeration types are layout-compatible if they have the same
11836 // underlying type.
11837 return ED1->isComplete() && ED2->isComplete() &&
11838 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11839}
11840
11841/// \brief Check if two fields are layout-compatible.
11842bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11843 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11844 return false;
11845
11846 if (Field1->isBitField() != Field2->isBitField())
11847 return false;
11848
11849 if (Field1->isBitField()) {
11850 // Make sure that the bit-fields are the same length.
11851 unsigned Bits1 = Field1->getBitWidthValue(C);
11852 unsigned Bits2 = Field2->getBitWidthValue(C);
11853
11854 if (Bits1 != Bits2)
11855 return false;
11856 }
11857
11858 return true;
11859}
11860
11861/// \brief Check if two standard-layout structs are layout-compatible.
11862/// (C++11 [class.mem] p17)
11863bool isLayoutCompatibleStruct(ASTContext &C,
11864 RecordDecl *RD1,
11865 RecordDecl *RD2) {
11866 // If both records are C++ classes, check that base classes match.
11867 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11868 // If one of records is a CXXRecordDecl we are in C++ mode,
11869 // thus the other one is a CXXRecordDecl, too.
11870 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11871 // Check number of base classes.
11872 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11873 return false;
11874
11875 // Check the base classes.
11876 for (CXXRecordDecl::base_class_const_iterator
11877 Base1 = D1CXX->bases_begin(),
11878 BaseEnd1 = D1CXX->bases_end(),
11879 Base2 = D2CXX->bases_begin();
11880 Base1 != BaseEnd1;
11881 ++Base1, ++Base2) {
11882 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11883 return false;
11884 }
11885 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11886 // If only RD2 is a C++ class, it should have zero base classes.
11887 if (D2CXX->getNumBases() > 0)
11888 return false;
11889 }
11890
11891 // Check the fields.
11892 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11893 Field2End = RD2->field_end(),
11894 Field1 = RD1->field_begin(),
11895 Field1End = RD1->field_end();
11896 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11897 if (!isLayoutCompatible(C, *Field1, *Field2))
11898 return false;
11899 }
11900 if (Field1 != Field1End || Field2 != Field2End)
11901 return false;
11902
11903 return true;
11904}
11905
11906/// \brief Check if two standard-layout unions are layout-compatible.
11907/// (C++11 [class.mem] p18)
11908bool isLayoutCompatibleUnion(ASTContext &C,
11909 RecordDecl *RD1,
11910 RecordDecl *RD2) {
11911 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011912 for (auto *Field2 : RD2->fields())
11913 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011914
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011915 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011916 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11917 I = UnmatchedFields.begin(),
11918 E = UnmatchedFields.end();
11919
11920 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011921 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011922 bool Result = UnmatchedFields.erase(*I);
11923 (void) Result;
11924 assert(Result);
11925 break;
11926 }
11927 }
11928 if (I == E)
11929 return false;
11930 }
11931
11932 return UnmatchedFields.empty();
11933}
11934
11935bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11936 if (RD1->isUnion() != RD2->isUnion())
11937 return false;
11938
11939 if (RD1->isUnion())
11940 return isLayoutCompatibleUnion(C, RD1, RD2);
11941 else
11942 return isLayoutCompatibleStruct(C, RD1, RD2);
11943}
11944
11945/// \brief Check if two types are layout-compatible in C++11 sense.
11946bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11947 if (T1.isNull() || T2.isNull())
11948 return false;
11949
11950 // C++11 [basic.types] p11:
11951 // If two types T1 and T2 are the same type, then T1 and T2 are
11952 // layout-compatible types.
11953 if (C.hasSameType(T1, T2))
11954 return true;
11955
11956 T1 = T1.getCanonicalType().getUnqualifiedType();
11957 T2 = T2.getCanonicalType().getUnqualifiedType();
11958
11959 const Type::TypeClass TC1 = T1->getTypeClass();
11960 const Type::TypeClass TC2 = T2->getTypeClass();
11961
11962 if (TC1 != TC2)
11963 return false;
11964
11965 if (TC1 == Type::Enum) {
11966 return isLayoutCompatible(C,
11967 cast<EnumType>(T1)->getDecl(),
11968 cast<EnumType>(T2)->getDecl());
11969 } else if (TC1 == Type::Record) {
11970 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11971 return false;
11972
11973 return isLayoutCompatible(C,
11974 cast<RecordType>(T1)->getDecl(),
11975 cast<RecordType>(T2)->getDecl());
11976 }
11977
11978 return false;
11979}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011980} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011981
11982//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11983
11984namespace {
11985/// \brief Given a type tag expression find the type tag itself.
11986///
11987/// \param TypeExpr Type tag expression, as it appears in user's code.
11988///
11989/// \param VD Declaration of an identifier that appears in a type tag.
11990///
11991/// \param MagicValue Type tag magic value.
11992bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11993 const ValueDecl **VD, uint64_t *MagicValue) {
11994 while(true) {
11995 if (!TypeExpr)
11996 return false;
11997
11998 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11999
12000 switch (TypeExpr->getStmtClass()) {
12001 case Stmt::UnaryOperatorClass: {
12002 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12003 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12004 TypeExpr = UO->getSubExpr();
12005 continue;
12006 }
12007 return false;
12008 }
12009
12010 case Stmt::DeclRefExprClass: {
12011 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12012 *VD = DRE->getDecl();
12013 return true;
12014 }
12015
12016 case Stmt::IntegerLiteralClass: {
12017 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12018 llvm::APInt MagicValueAPInt = IL->getValue();
12019 if (MagicValueAPInt.getActiveBits() <= 64) {
12020 *MagicValue = MagicValueAPInt.getZExtValue();
12021 return true;
12022 } else
12023 return false;
12024 }
12025
12026 case Stmt::BinaryConditionalOperatorClass:
12027 case Stmt::ConditionalOperatorClass: {
12028 const AbstractConditionalOperator *ACO =
12029 cast<AbstractConditionalOperator>(TypeExpr);
12030 bool Result;
12031 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12032 if (Result)
12033 TypeExpr = ACO->getTrueExpr();
12034 else
12035 TypeExpr = ACO->getFalseExpr();
12036 continue;
12037 }
12038 return false;
12039 }
12040
12041 case Stmt::BinaryOperatorClass: {
12042 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12043 if (BO->getOpcode() == BO_Comma) {
12044 TypeExpr = BO->getRHS();
12045 continue;
12046 }
12047 return false;
12048 }
12049
12050 default:
12051 return false;
12052 }
12053 }
12054}
12055
12056/// \brief Retrieve the C type corresponding to type tag TypeExpr.
12057///
12058/// \param TypeExpr Expression that specifies a type tag.
12059///
12060/// \param MagicValues Registered magic values.
12061///
12062/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12063/// kind.
12064///
12065/// \param TypeInfo Information about the corresponding C type.
12066///
12067/// \returns true if the corresponding C type was found.
12068bool GetMatchingCType(
12069 const IdentifierInfo *ArgumentKind,
12070 const Expr *TypeExpr, const ASTContext &Ctx,
12071 const llvm::DenseMap<Sema::TypeTagMagicValue,
12072 Sema::TypeTagData> *MagicValues,
12073 bool &FoundWrongKind,
12074 Sema::TypeTagData &TypeInfo) {
12075 FoundWrongKind = false;
12076
12077 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000012078 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012079
12080 uint64_t MagicValue;
12081
12082 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12083 return false;
12084
12085 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000012086 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012087 if (I->getArgumentKind() != ArgumentKind) {
12088 FoundWrongKind = true;
12089 return false;
12090 }
12091 TypeInfo.Type = I->getMatchingCType();
12092 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12093 TypeInfo.MustBeNull = I->getMustBeNull();
12094 return true;
12095 }
12096 return false;
12097 }
12098
12099 if (!MagicValues)
12100 return false;
12101
12102 llvm::DenseMap<Sema::TypeTagMagicValue,
12103 Sema::TypeTagData>::const_iterator I =
12104 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12105 if (I == MagicValues->end())
12106 return false;
12107
12108 TypeInfo = I->second;
12109 return true;
12110}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000012111} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012112
12113void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12114 uint64_t MagicValue, QualType Type,
12115 bool LayoutCompatible,
12116 bool MustBeNull) {
12117 if (!TypeTagForDatatypeMagicValues)
12118 TypeTagForDatatypeMagicValues.reset(
12119 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12120
12121 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12122 (*TypeTagForDatatypeMagicValues)[Magic] =
12123 TypeTagData(Type, LayoutCompatible, MustBeNull);
12124}
12125
12126namespace {
12127bool IsSameCharType(QualType T1, QualType T2) {
12128 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12129 if (!BT1)
12130 return false;
12131
12132 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12133 if (!BT2)
12134 return false;
12135
12136 BuiltinType::Kind T1Kind = BT1->getKind();
12137 BuiltinType::Kind T2Kind = BT2->getKind();
12138
12139 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
12140 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
12141 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12142 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12143}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000012144} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012145
12146void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
12147 const Expr * const *ExprArgs) {
12148 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12149 bool IsPointerAttr = Attr->getIsPointer();
12150
12151 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
12152 bool FoundWrongKind;
12153 TypeTagData TypeInfo;
12154 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12155 TypeTagForDatatypeMagicValues.get(),
12156 FoundWrongKind, TypeInfo)) {
12157 if (FoundWrongKind)
12158 Diag(TypeTagExpr->getExprLoc(),
12159 diag::warn_type_tag_for_datatype_wrong_kind)
12160 << TypeTagExpr->getSourceRange();
12161 return;
12162 }
12163
12164 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
12165 if (IsPointerAttr) {
12166 // Skip implicit cast of pointer to `void *' (as a function argument).
12167 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000012168 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000012169 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012170 ArgumentExpr = ICE->getSubExpr();
12171 }
12172 QualType ArgumentType = ArgumentExpr->getType();
12173
12174 // Passing a `void*' pointer shouldn't trigger a warning.
12175 if (IsPointerAttr && ArgumentType->isVoidPointerType())
12176 return;
12177
12178 if (TypeInfo.MustBeNull) {
12179 // Type tag with matching void type requires a null pointer.
12180 if (!ArgumentExpr->isNullPointerConstant(Context,
12181 Expr::NPC_ValueDependentIsNotNull)) {
12182 Diag(ArgumentExpr->getExprLoc(),
12183 diag::warn_type_safety_null_pointer_required)
12184 << ArgumentKind->getName()
12185 << ArgumentExpr->getSourceRange()
12186 << TypeTagExpr->getSourceRange();
12187 }
12188 return;
12189 }
12190
12191 QualType RequiredType = TypeInfo.Type;
12192 if (IsPointerAttr)
12193 RequiredType = Context.getPointerType(RequiredType);
12194
12195 bool mismatch = false;
12196 if (!TypeInfo.LayoutCompatible) {
12197 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12198
12199 // C++11 [basic.fundamental] p1:
12200 // Plain char, signed char, and unsigned char are three distinct types.
12201 //
12202 // But we treat plain `char' as equivalent to `signed char' or `unsigned
12203 // char' depending on the current char signedness mode.
12204 if (mismatch)
12205 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12206 RequiredType->getPointeeType())) ||
12207 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12208 mismatch = false;
12209 } else
12210 if (IsPointerAttr)
12211 mismatch = !isLayoutCompatible(Context,
12212 ArgumentType->getPointeeType(),
12213 RequiredType->getPointeeType());
12214 else
12215 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12216
12217 if (mismatch)
12218 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000012219 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012220 << TypeInfo.LayoutCompatible << RequiredType
12221 << ArgumentExpr->getSourceRange()
12222 << TypeTagExpr->getSourceRange();
12223}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012224
12225void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12226 CharUnits Alignment) {
12227 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12228}
12229
12230void Sema::DiagnoseMisalignedMembers() {
12231 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000012232 const NamedDecl *ND = m.RD;
12233 if (ND->getName().empty()) {
12234 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12235 ND = TD;
12236 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012237 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000012238 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012239 }
12240 MisalignedMembers.clear();
12241}
12242
12243void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012244 E = E->IgnoreParens();
12245 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012246 return;
12247 if (isa<UnaryOperator>(E) &&
12248 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12249 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12250 if (isa<MemberExpr>(Op)) {
12251 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12252 MisalignedMember(Op));
12253 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012254 (T->isIntegerType() ||
12255 (T->isPointerType() &&
12256 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012257 MisalignedMembers.erase(MA);
12258 }
12259 }
12260}
12261
12262void Sema::RefersToMemberWithReducedAlignment(
12263 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000012264 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12265 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012266 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012267 if (!ME)
12268 return;
12269
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000012270 // No need to check expressions with an __unaligned-qualified type.
12271 if (E->getType().getQualifiers().hasUnaligned())
12272 return;
12273
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012274 // For a chain of MemberExpr like "a.b.c.d" this list
12275 // will keep FieldDecl's like [d, c, b].
12276 SmallVector<FieldDecl *, 4> ReverseMemberChain;
12277 const MemberExpr *TopME = nullptr;
12278 bool AnyIsPacked = false;
12279 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012280 QualType BaseType = ME->getBase()->getType();
12281 if (ME->isArrow())
12282 BaseType = BaseType->getPointeeType();
12283 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000012284 if (RD->isInvalidDecl())
12285 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012286
12287 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012288 auto *FD = dyn_cast<FieldDecl>(MD);
12289 // We do not care about non-data members.
12290 if (!FD || FD->isInvalidDecl())
12291 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012292
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012293 AnyIsPacked =
12294 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12295 ReverseMemberChain.push_back(FD);
12296
12297 TopME = ME;
12298 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12299 } while (ME);
12300 assert(TopME && "We did not compute a topmost MemberExpr!");
12301
12302 // Not the scope of this diagnostic.
12303 if (!AnyIsPacked)
12304 return;
12305
12306 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12307 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12308 // TODO: The innermost base of the member expression may be too complicated.
12309 // For now, just disregard these cases. This is left for future
12310 // improvement.
12311 if (!DRE && !isa<CXXThisExpr>(TopBase))
12312 return;
12313
12314 // Alignment expected by the whole expression.
12315 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12316
12317 // No need to do anything else with this case.
12318 if (ExpectedAlignment.isOne())
12319 return;
12320
12321 // Synthesize offset of the whole access.
12322 CharUnits Offset;
12323 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12324 I++) {
12325 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12326 }
12327
12328 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12329 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12330 ReverseMemberChain.back()->getParent()->getTypeForDecl());
12331
12332 // The base expression of the innermost MemberExpr may give
12333 // stronger guarantees than the class containing the member.
12334 if (DRE && !TopME->isArrow()) {
12335 const ValueDecl *VD = DRE->getDecl();
12336 if (!VD->getType()->isReferenceType())
12337 CompleteObjectAlignment =
12338 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12339 }
12340
12341 // Check if the synthesized offset fulfills the alignment.
12342 if (Offset % ExpectedAlignment != 0 ||
12343 // It may fulfill the offset it but the effective alignment may still be
12344 // lower than the expected expression alignment.
12345 CompleteObjectAlignment < ExpectedAlignment) {
12346 // If this happens, we want to determine a sensible culprit of this.
12347 // Intuitively, watching the chain of member expressions from right to
12348 // left, we start with the required alignment (as required by the field
12349 // type) but some packed attribute in that chain has reduced the alignment.
12350 // It may happen that another packed structure increases it again. But if
12351 // we are here such increase has not been enough. So pointing the first
12352 // FieldDecl that either is packed or else its RecordDecl is,
12353 // seems reasonable.
12354 FieldDecl *FD = nullptr;
12355 CharUnits Alignment;
12356 for (FieldDecl *FDI : ReverseMemberChain) {
12357 if (FDI->hasAttr<PackedAttr>() ||
12358 FDI->getParent()->hasAttr<PackedAttr>()) {
12359 FD = FDI;
12360 Alignment = std::min(
12361 Context.getTypeAlignInChars(FD->getType()),
12362 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12363 break;
12364 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012365 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012366 assert(FD && "We did not find a packed FieldDecl!");
12367 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012368 }
12369}
12370
12371void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12372 using namespace std::placeholders;
12373 RefersToMemberWithReducedAlignment(
12374 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12375 _2, _3, _4));
12376}
12377