blob: b4fdcc0f7e9ddea007640e1b9f4733a8b2d90b35 [file] [log] [blame]
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00001//===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002//
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
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000015#include "clang/AST/APValue.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000017#include "clang/AST/Attr.h"
18#include "clang/AST/AttrIterator.h"
Ken Dyck40775002010-01-11 17:06:35 +000019#include "clang/AST/CharUnits.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000020#include "clang/AST/Decl.h"
21#include "clang/AST/DeclBase.h"
John McCall28a0cf72010-08-25 07:42:41 +000022#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000023#include "clang/AST/DeclObjC.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000024#include "clang/AST/DeclarationName.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000026#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000027#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000028#include "clang/AST/ExprObjC.h"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000029#include "clang/AST/ExprOpenMP.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000030#include "clang/AST/NSAPI.h"
Akira Hatanaka2be04412018-04-17 19:13:41 +000031#include "clang/AST/NonTrivialTypeVisitor.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000032#include "clang/AST/OperationKinds.h"
33#include "clang/AST/Stmt.h"
34#include "clang/AST/TemplateBase.h"
35#include "clang/AST/Type.h"
36#include "clang/AST/TypeLoc.h"
37#include "clang/AST/UnresolvedSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "clang/Analysis/Analyses/FormatString.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000039#include "clang/Basic/AddressSpaces.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000040#include "clang/Basic/CharInfo.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000041#include "clang/Basic/Diagnostic.h"
42#include "clang/Basic/IdentifierTable.h"
43#include "clang/Basic/LLVM.h"
44#include "clang/Basic/LangOptions.h"
45#include "clang/Basic/OpenCLOptions.h"
46#include "clang/Basic/OperatorKinds.h"
47#include "clang/Basic/PartialDiagnostic.h"
48#include "clang/Basic/SourceLocation.h"
49#include "clang/Basic/SourceManager.h"
50#include "clang/Basic/Specifiers.h"
Yaxun Liu39195062017-08-04 18:16:31 +000051#include "clang/Basic/SyncScope.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000052#include "clang/Basic/TargetBuiltins.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000053#include "clang/Basic/TargetCXXABI.h"
Nate Begeman4904e322010-06-08 02:47:44 +000054#include "clang/Basic/TargetInfo.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000055#include "clang/Basic/TypeTraits.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000056#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000057#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000058#include "clang/Sema/Lookup.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000059#include "clang/Sema/Ownership.h"
60#include "clang/Sema/Scope.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000061#include "clang/Sema/ScopeInfo.h"
62#include "clang/Sema/Sema.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000063#include "clang/Sema/SemaInternal.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000064#include "llvm/ADT/APFloat.h"
65#include "llvm/ADT/APInt.h"
66#include "llvm/ADT/APSInt.h"
67#include "llvm/ADT/ArrayRef.h"
68#include "llvm/ADT/DenseMap.h"
69#include "llvm/ADT/FoldingSet.h"
70#include "llvm/ADT/None.h"
71#include "llvm/ADT/Optional.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000072#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000073#include "llvm/ADT/SmallBitVector.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000074#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000075#include "llvm/ADT/SmallString.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000076#include "llvm/ADT/SmallVector.h"
77#include "llvm/ADT/StringRef.h"
78#include "llvm/ADT/StringSwitch.h"
79#include "llvm/ADT/Triple.h"
80#include "llvm/Support/AtomicOrdering.h"
81#include "llvm/Support/Casting.h"
82#include "llvm/Support/Compiler.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000083#include "llvm/Support/ConvertUTF.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000084#include "llvm/Support/ErrorHandling.h"
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +000085#include "llvm/Support/Format.h"
86#include "llvm/Support/Locale.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000087#include "llvm/Support/MathExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000088#include "llvm/Support/raw_ostream.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000089#include <algorithm>
90#include <cassert>
91#include <cstddef>
92#include <cstdint>
93#include <functional>
94#include <limits>
95#include <string>
96#include <tuple>
97#include <utility>
Eugene Zelenko1ced5092016-02-12 22:53:10 +000098
Chris Lattnerb87b1b32007-08-10 20:18:51 +000099using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +0000100using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +0000101
Chris Lattnera26fb342009-02-18 17:49:48 +0000102SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
103 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +0000104 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
105 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +0000106}
107
John McCallbebede42011-02-26 05:39:39 +0000108/// Checks that a call expression's argument count is the desired number.
109/// This is useful when doing custom type-checking. Returns true on error.
110static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
111 unsigned argCount = call->getNumArgs();
112 if (argCount == desiredArgCount) return false;
113
114 if (argCount < desiredArgCount)
115 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
116 << 0 /*function call*/ << desiredArgCount << argCount
117 << call->getSourceRange();
118
119 // Highlight all the excess arguments.
120 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
121 call->getArg(argCount - 1)->getLocEnd());
Nico Weberade321e2018-04-10 18:53:28 +0000122
John McCallbebede42011-02-26 05:39:39 +0000123 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
124 << 0 /*function call*/ << desiredArgCount << argCount
125 << call->getArg(1)->getSourceRange();
126}
127
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000128/// Check that the first argument to __builtin_annotation is an integer
129/// and the second argument is a non-wide string literal.
130static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
131 if (checkArgCount(S, TheCall, 2))
132 return true;
133
134 // First argument should be an integer.
135 Expr *ValArg = TheCall->getArg(0);
136 QualType Ty = ValArg->getType();
137 if (!Ty->isIntegerType()) {
138 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
139 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000140 return true;
141 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000142
143 // Second argument should be a constant string.
144 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
145 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
146 if (!Literal || !Literal->isAscii()) {
147 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
148 << StrArg->getSourceRange();
149 return true;
150 }
151
152 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000153 return false;
154}
155
Reid Kleckner30701ed2017-09-05 20:27:35 +0000156static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
157 // We need at least one argument.
158 if (TheCall->getNumArgs() < 1) {
159 S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
160 << 0 << 1 << TheCall->getNumArgs()
161 << TheCall->getCallee()->getSourceRange();
162 return true;
163 }
164
165 // All arguments should be wide string literals.
166 for (Expr *Arg : TheCall->arguments()) {
167 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
168 if (!Literal || !Literal->isWide()) {
169 S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str)
170 << Arg->getSourceRange();
171 return true;
172 }
173 }
174
175 return false;
176}
177
Richard Smith6cbd65d2013-07-11 02:27:57 +0000178/// Check that the argument to __builtin_addressof is a glvalue, and set the
179/// result type to the corresponding pointer type.
180static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
181 if (checkArgCount(S, TheCall, 1))
182 return true;
183
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000184 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000185 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
186 if (ResultType.isNull())
187 return true;
188
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000189 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000190 TheCall->setType(ResultType);
191 return false;
192}
193
John McCall03107a42015-10-29 20:48:01 +0000194static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
195 if (checkArgCount(S, TheCall, 3))
196 return true;
197
198 // First two arguments should be integers.
199 for (unsigned I = 0; I < 2; ++I) {
200 Expr *Arg = TheCall->getArg(I);
201 QualType Ty = Arg->getType();
202 if (!Ty->isIntegerType()) {
203 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
204 << Ty << Arg->getSourceRange();
205 return true;
206 }
207 }
208
209 // Third argument should be a pointer to a non-const integer.
210 // IRGen correctly handles volatile, restrict, and address spaces, and
211 // the other qualifiers aren't possible.
212 {
213 Expr *Arg = TheCall->getArg(2);
214 QualType Ty = Arg->getType();
215 const auto *PtrTy = Ty->getAs<PointerType>();
216 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
217 !PtrTy->getPointeeType().isConstQualified())) {
218 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
219 << Ty << Arg->getSourceRange();
220 return true;
221 }
222 }
223
224 return false;
225}
226
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000227static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
Nico Weberade321e2018-04-10 18:53:28 +0000228 CallExpr *TheCall, unsigned SizeIdx,
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000229 unsigned DstSizeIdx) {
230 if (TheCall->getNumArgs() <= SizeIdx ||
231 TheCall->getNumArgs() <= DstSizeIdx)
232 return;
233
234 const Expr *SizeArg = TheCall->getArg(SizeIdx);
235 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
236
237 llvm::APSInt Size, DstSize;
238
239 // find out if both sizes are known at compile time
240 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
241 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
242 return;
243
244 if (Size.ule(DstSize))
245 return;
246
247 // confirmed overflow so generate the diagnostic.
248 IdentifierInfo *FnName = FDecl->getIdentifier();
249 SourceLocation SL = TheCall->getLocStart();
250 SourceRange SR = TheCall->getSourceRange();
251
252 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
253}
254
Peter Collingbournef7706832014-12-12 23:41:25 +0000255static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
256 if (checkArgCount(S, BuiltinCall, 2))
257 return true;
258
259 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
260 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
261 Expr *Call = BuiltinCall->getArg(0);
262 Expr *Chain = BuiltinCall->getArg(1);
263
264 if (Call->getStmtClass() != Stmt::CallExprClass) {
265 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
266 << Call->getSourceRange();
267 return true;
268 }
269
270 auto CE = cast<CallExpr>(Call);
271 if (CE->getCallee()->getType()->isBlockPointerType()) {
272 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
273 << Call->getSourceRange();
274 return true;
275 }
276
277 const Decl *TargetDecl = CE->getCalleeDecl();
278 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
279 if (FD->getBuiltinID()) {
280 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
281 << Call->getSourceRange();
282 return true;
283 }
284
285 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
286 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
287 << Call->getSourceRange();
288 return true;
289 }
290
291 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
292 if (ChainResult.isInvalid())
293 return true;
294 if (!ChainResult.get()->getType()->isPointerType()) {
295 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
296 << Chain->getSourceRange();
297 return true;
298 }
299
David Majnemerced8bdf2015-02-25 17:36:15 +0000300 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000301 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
302 QualType BuiltinTy = S.Context.getFunctionType(
303 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
304 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
305
306 Builtin =
307 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
308
309 BuiltinCall->setType(CE->getType());
310 BuiltinCall->setValueKind(CE->getValueKind());
311 BuiltinCall->setObjectKind(CE->getObjectKind());
312 BuiltinCall->setCallee(Builtin);
313 BuiltinCall->setArg(1, ChainResult.get());
314
315 return false;
316}
317
Reid Kleckner1d59f992015-01-22 01:36:17 +0000318static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
319 Scope::ScopeFlags NeededScopeFlags,
320 unsigned DiagID) {
321 // Scopes aren't available during instantiation. Fortunately, builtin
322 // functions cannot be template args so they cannot be formed through template
323 // instantiation. Therefore checking once during the parse is sufficient.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000324 if (SemaRef.inTemplateInstantiation())
Reid Kleckner1d59f992015-01-22 01:36:17 +0000325 return false;
326
327 Scope *S = SemaRef.getCurScope();
328 while (S && !S->isSEHExceptScope())
329 S = S->getParent();
330 if (!S || !(S->getFlags() & NeededScopeFlags)) {
331 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
332 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
333 << DRE->getDecl()->getIdentifier();
334 return true;
335 }
336
337 return false;
338}
339
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000340static inline bool isBlockPointer(Expr *Arg) {
341 return Arg->getType()->isBlockPointerType();
342}
343
344/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
345/// void*, which is a requirement of device side enqueue.
346static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
347 const BlockPointerType *BPT =
348 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
349 ArrayRef<QualType> Params =
350 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
351 unsigned ArgCounter = 0;
352 bool IllegalParams = false;
353 // Iterate through the block parameters until either one is found that is not
354 // a local void*, or the block is valid.
355 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
356 I != E; ++I, ++ArgCounter) {
357 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
358 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
359 LangAS::opencl_local) {
360 // Get the location of the error. If a block literal has been passed
361 // (BlockExpr) then we can point straight to the offending argument,
362 // else we just point to the variable reference.
363 SourceLocation ErrorLoc;
364 if (isa<BlockExpr>(BlockArg)) {
365 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
366 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
367 } else if (isa<DeclRefExpr>(BlockArg)) {
368 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
369 }
370 S.Diag(ErrorLoc,
371 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
372 IllegalParams = true;
373 }
374 }
375
376 return IllegalParams;
377}
378
Joey Gouly84ae3362017-07-31 15:15:59 +0000379static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
380 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
381 S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
382 << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
383 return true;
384 }
385 return false;
386}
387
Joey Goulyfa76b492017-08-01 13:27:09 +0000388static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
389 if (checkArgCount(S, TheCall, 2))
390 return true;
391
392 if (checkOpenCLSubgroupExt(S, TheCall))
393 return true;
394
395 // First argument is an ndrange_t type.
396 Expr *NDRangeArg = TheCall->getArg(0);
Yaxun Liub7318e02017-10-13 03:37:48 +0000397 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Joey Goulyfa76b492017-08-01 13:27:09 +0000398 S.Diag(NDRangeArg->getLocStart(),
399 diag::err_opencl_builtin_expected_type)
400 << TheCall->getDirectCallee() << "'ndrange_t'";
401 return true;
402 }
403
404 Expr *BlockArg = TheCall->getArg(1);
405 if (!isBlockPointer(BlockArg)) {
406 S.Diag(BlockArg->getLocStart(),
407 diag::err_opencl_builtin_expected_type)
408 << TheCall->getDirectCallee() << "block";
409 return true;
410 }
411 return checkOpenCLBlockArgs(S, BlockArg);
412}
413
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000414/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
415/// get_kernel_work_group_size
416/// and get_kernel_preferred_work_group_size_multiple builtin functions.
417static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
418 if (checkArgCount(S, TheCall, 1))
419 return true;
420
421 Expr *BlockArg = TheCall->getArg(0);
422 if (!isBlockPointer(BlockArg)) {
423 S.Diag(BlockArg->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000424 diag::err_opencl_builtin_expected_type)
425 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000426 return true;
427 }
428 return checkOpenCLBlockArgs(S, BlockArg);
429}
430
Simon Pilgrim2c518802017-03-30 14:13:19 +0000431/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000432static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
433 const QualType &IntType);
434
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000435static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000436 unsigned Start, unsigned End) {
437 bool IllegalParams = false;
438 for (unsigned I = Start; I <= End; ++I)
439 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
440 S.Context.getSizeType());
441 return IllegalParams;
442}
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000443
444/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
445/// 'local void*' parameter of passed block.
446static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
447 Expr *BlockArg,
448 unsigned NumNonVarArgs) {
449 const BlockPointerType *BPT =
450 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
451 unsigned NumBlockParams =
452 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
453 unsigned TotalNumArgs = TheCall->getNumArgs();
454
455 // For each argument passed to the block, a corresponding uint needs to
456 // be passed to describe the size of the local memory.
457 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
458 S.Diag(TheCall->getLocStart(),
459 diag::err_opencl_enqueue_kernel_local_size_args);
460 return true;
461 }
462
463 // Check that the sizes of the local memory are specified by integers.
464 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
465 TotalNumArgs - 1);
466}
467
468/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
469/// overload formats specified in Table 6.13.17.1.
470/// int enqueue_kernel(queue_t queue,
471/// kernel_enqueue_flags_t flags,
472/// const ndrange_t ndrange,
473/// void (^block)(void))
474/// int enqueue_kernel(queue_t queue,
475/// kernel_enqueue_flags_t flags,
476/// const ndrange_t ndrange,
477/// uint num_events_in_wait_list,
478/// clk_event_t *event_wait_list,
479/// clk_event_t *event_ret,
480/// void (^block)(void))
481/// int enqueue_kernel(queue_t queue,
482/// kernel_enqueue_flags_t flags,
483/// const ndrange_t ndrange,
484/// void (^block)(local void*, ...),
485/// uint size0, ...)
486/// int enqueue_kernel(queue_t queue,
487/// kernel_enqueue_flags_t flags,
488/// const ndrange_t ndrange,
489/// uint num_events_in_wait_list,
490/// clk_event_t *event_wait_list,
491/// clk_event_t *event_ret,
492/// void (^block)(local void*, ...),
493/// uint size0, ...)
494static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
495 unsigned NumArgs = TheCall->getNumArgs();
496
497 if (NumArgs < 4) {
498 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
499 return true;
500 }
501
502 Expr *Arg0 = TheCall->getArg(0);
503 Expr *Arg1 = TheCall->getArg(1);
504 Expr *Arg2 = TheCall->getArg(2);
505 Expr *Arg3 = TheCall->getArg(3);
506
507 // First argument always needs to be a queue_t type.
508 if (!Arg0->getType()->isQueueT()) {
509 S.Diag(TheCall->getArg(0)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000510 diag::err_opencl_builtin_expected_type)
511 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000512 return true;
513 }
514
515 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
516 if (!Arg1->getType()->isIntegerType()) {
517 S.Diag(TheCall->getArg(1)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000518 diag::err_opencl_builtin_expected_type)
519 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000520 return true;
521 }
522
523 // Third argument is always an ndrange_t type.
Anastasia Stulovab42f3c02017-04-21 15:13:24 +0000524 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000525 S.Diag(TheCall->getArg(2)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000526 diag::err_opencl_builtin_expected_type)
527 << TheCall->getDirectCallee() << "'ndrange_t'";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000528 return true;
529 }
530
531 // With four arguments, there is only one form that the function could be
532 // called in: no events and no variable arguments.
533 if (NumArgs == 4) {
534 // check that the last argument is the right block type.
535 if (!isBlockPointer(Arg3)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000536 S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
537 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000538 return true;
539 }
540 // we have a block type, check the prototype
541 const BlockPointerType *BPT =
542 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
543 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
544 S.Diag(Arg3->getLocStart(),
545 diag::err_opencl_enqueue_kernel_blocks_no_args);
546 return true;
547 }
548 return false;
549 }
550 // we can have block + varargs.
551 if (isBlockPointer(Arg3))
552 return (checkOpenCLBlockArgs(S, Arg3) ||
553 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
554 // last two cases with either exactly 7 args or 7 args and varargs.
555 if (NumArgs >= 7) {
556 // check common block argument.
557 Expr *Arg6 = TheCall->getArg(6);
558 if (!isBlockPointer(Arg6)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000559 S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
560 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000561 return true;
562 }
563 if (checkOpenCLBlockArgs(S, Arg6))
564 return true;
565
566 // Forth argument has to be any integer type.
567 if (!Arg3->getType()->isIntegerType()) {
568 S.Diag(TheCall->getArg(3)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000569 diag::err_opencl_builtin_expected_type)
570 << TheCall->getDirectCallee() << "integer";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000571 return true;
572 }
573 // check remaining common arguments.
574 Expr *Arg4 = TheCall->getArg(4);
575 Expr *Arg5 = TheCall->getArg(5);
576
Anastasia Stulova2b461202016-11-14 15:34:01 +0000577 // Fifth argument is always passed as a pointer to clk_event_t.
578 if (!Arg4->isNullPointerConstant(S.Context,
579 Expr::NPC_ValueDependentIsNotNull) &&
580 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000581 S.Diag(TheCall->getArg(4)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000582 diag::err_opencl_builtin_expected_type)
583 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000584 << S.Context.getPointerType(S.Context.OCLClkEventTy);
585 return true;
586 }
587
Anastasia Stulova2b461202016-11-14 15:34:01 +0000588 // Sixth argument is always passed as a pointer to clk_event_t.
589 if (!Arg5->isNullPointerConstant(S.Context,
590 Expr::NPC_ValueDependentIsNotNull) &&
591 !(Arg5->getType()->isPointerType() &&
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000592 Arg5->getType()->getPointeeType()->isClkEventT())) {
593 S.Diag(TheCall->getArg(5)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000594 diag::err_opencl_builtin_expected_type)
595 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000596 << S.Context.getPointerType(S.Context.OCLClkEventTy);
597 return true;
598 }
599
600 if (NumArgs == 7)
601 return false;
602
603 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
604 }
605
606 // None of the specific case has been detected, give generic error
607 S.Diag(TheCall->getLocStart(),
608 diag::err_opencl_enqueue_kernel_incorrect_args);
609 return true;
610}
611
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000612/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000613static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000614 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000615}
616
617/// Returns true if pipe element type is different from the pointer.
618static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
619 const Expr *Arg0 = Call->getArg(0);
620 // First argument type should always be pipe.
621 if (!Arg0->getType()->isPipeType()) {
622 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000623 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000624 return true;
625 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000626 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000627 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
628 // Validates the access qualifier is compatible with the call.
629 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
630 // read_only and write_only, and assumed to be read_only if no qualifier is
631 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000632 switch (Call->getDirectCallee()->getBuiltinID()) {
633 case Builtin::BIread_pipe:
634 case Builtin::BIreserve_read_pipe:
635 case Builtin::BIcommit_read_pipe:
636 case Builtin::BIwork_group_reserve_read_pipe:
637 case Builtin::BIsub_group_reserve_read_pipe:
638 case Builtin::BIwork_group_commit_read_pipe:
639 case Builtin::BIsub_group_commit_read_pipe:
640 if (!(!AccessQual || AccessQual->isReadOnly())) {
641 S.Diag(Arg0->getLocStart(),
642 diag::err_opencl_builtin_pipe_invalid_access_modifier)
643 << "read_only" << Arg0->getSourceRange();
644 return true;
645 }
646 break;
647 case Builtin::BIwrite_pipe:
648 case Builtin::BIreserve_write_pipe:
649 case Builtin::BIcommit_write_pipe:
650 case Builtin::BIwork_group_reserve_write_pipe:
651 case Builtin::BIsub_group_reserve_write_pipe:
652 case Builtin::BIwork_group_commit_write_pipe:
653 case Builtin::BIsub_group_commit_write_pipe:
654 if (!(AccessQual && AccessQual->isWriteOnly())) {
655 S.Diag(Arg0->getLocStart(),
656 diag::err_opencl_builtin_pipe_invalid_access_modifier)
657 << "write_only" << Arg0->getSourceRange();
658 return true;
659 }
660 break;
661 default:
662 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000663 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000664 return false;
665}
666
667/// Returns true if pipe element type is different from the pointer.
668static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
669 const Expr *Arg0 = Call->getArg(0);
670 const Expr *ArgIdx = Call->getArg(Idx);
671 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000672 const QualType EltTy = PipeTy->getElementType();
673 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000674 // The Idx argument should be a pointer and the type of the pointer and
675 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000676 if (!ArgTy ||
677 !S.Context.hasSameType(
678 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000679 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000680 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000681 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000682 return true;
683 }
684 return false;
685}
686
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000687// Performs semantic analysis for the read/write_pipe call.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000688// \param S Reference to the semantic analyzer.
689// \param Call A pointer to the builtin call.
690// \return True if a semantic error has been found, false otherwise.
691static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000692 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
693 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000694 switch (Call->getNumArgs()) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000695 case 2:
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000696 if (checkOpenCLPipeArg(S, Call))
697 return true;
698 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000699 // read/write_pipe(pipe T, T*).
700 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000701 if (checkOpenCLPipePacketType(S, Call, 1))
702 return true;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000703 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000704
705 case 4: {
706 if (checkOpenCLPipeArg(S, Call))
707 return true;
708 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000709 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
710 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000711 if (!Call->getArg(1)->getType()->isReserveIDT()) {
712 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000713 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000714 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000715 return true;
716 }
717
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000718 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000719 const Expr *Arg2 = Call->getArg(2);
720 if (!Arg2->getType()->isIntegerType() &&
721 !Arg2->getType()->isUnsignedIntegerType()) {
722 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000723 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000724 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000725 return true;
726 }
727
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000728 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000729 if (checkOpenCLPipePacketType(S, Call, 3))
730 return true;
731 } break;
732 default:
733 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000734 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000735 return true;
736 }
737
738 return false;
739}
740
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000741// Performs a semantic analysis on the {work_group_/sub_group_
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000742// /_}reserve_{read/write}_pipe
743// \param S Reference to the semantic analyzer.
744// \param Call The call to the builtin function to be analyzed.
745// \return True if a semantic error was found, false otherwise.
746static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
747 if (checkArgCount(S, Call, 2))
748 return true;
749
750 if (checkOpenCLPipeArg(S, Call))
751 return true;
752
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000753 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000754 if (!Call->getArg(1)->getType()->isIntegerType() &&
755 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
756 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000757 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000758 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000759 return true;
760 }
761
Joey Gouly922ca232017-08-09 14:52:47 +0000762 // Since return type of reserve_read/write_pipe built-in function is
763 // reserve_id_t, which is not defined in the builtin def file , we used int
764 // as return type and need to override the return type of these functions.
765 Call->setType(S.Context.OCLReserveIDTy);
766
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000767 return false;
768}
769
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000770// Performs a semantic analysis on {work_group_/sub_group_
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000771// /_}commit_{read/write}_pipe
772// \param S Reference to the semantic analyzer.
773// \param Call The call to the builtin function to be analyzed.
774// \return True if a semantic error was found, false otherwise.
775static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
776 if (checkArgCount(S, Call, 2))
777 return true;
778
779 if (checkOpenCLPipeArg(S, Call))
780 return true;
781
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000782 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000783 if (!Call->getArg(1)->getType()->isReserveIDT()) {
784 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000785 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000786 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000787 return true;
788 }
789
790 return false;
791}
792
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000793// Performs a semantic analysis on the call to built-in Pipe
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000794// Query Functions.
795// \param S Reference to the semantic analyzer.
796// \param Call The call to the builtin function to be analyzed.
797// \return True if a semantic error was found, false otherwise.
798static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
799 if (checkArgCount(S, Call, 1))
800 return true;
801
802 if (!Call->getArg(0)->getType()->isPipeType()) {
803 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000804 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000805 return true;
806 }
807
808 return false;
809}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000810
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000811// OpenCL v2.0 s6.13.9 - Address space qualifier functions.
812// Performs semantic analysis for the to_global/local/private call.
Yaxun Liuf7449a12016-05-20 19:54:38 +0000813// \param S Reference to the semantic analyzer.
814// \param BuiltinID ID of the builtin function.
815// \param Call A pointer to the builtin call.
816// \return True if a semantic error has been found, false otherwise.
817static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
818 CallExpr *Call) {
Yaxun Liuf7449a12016-05-20 19:54:38 +0000819 if (Call->getNumArgs() != 1) {
820 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
821 << Call->getDirectCallee() << Call->getSourceRange();
822 return true;
823 }
824
825 auto RT = Call->getArg(0)->getType();
826 if (!RT->isPointerType() || RT->getPointeeType()
827 .getAddressSpace() == LangAS::opencl_constant) {
828 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
829 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
830 return true;
831 }
832
833 RT = RT->getPointeeType();
834 auto Qual = RT.getQualifiers();
835 switch (BuiltinID) {
836 case Builtin::BIto_global:
837 Qual.setAddressSpace(LangAS::opencl_global);
838 break;
839 case Builtin::BIto_local:
840 Qual.setAddressSpace(LangAS::opencl_local);
841 break;
Yaxun Liub7318e02017-10-13 03:37:48 +0000842 case Builtin::BIto_private:
843 Qual.setAddressSpace(LangAS::opencl_private);
844 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +0000845 default:
Yaxun Liub7318e02017-10-13 03:37:48 +0000846 llvm_unreachable("Invalid builtin function");
Yaxun Liuf7449a12016-05-20 19:54:38 +0000847 }
848 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
849 RT.getUnqualifiedType(), Qual)));
850
851 return false;
852}
853
John McCalldadc5752010-08-24 06:29:42 +0000854ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000855Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
856 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000857 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000858
Chris Lattner3be167f2010-10-01 23:23:24 +0000859 // Find out if any arguments are required to be integer constant expressions.
860 unsigned ICEArguments = 0;
861 ASTContext::GetBuiltinTypeError Error;
862 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
863 if (Error != ASTContext::GE_None)
864 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
865
866 // If any arguments are required to be ICE's, check and diagnose.
867 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
868 // Skip arguments not required to be ICE's.
869 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
870
871 llvm::APSInt Result;
872 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
873 return true;
874 ICEArguments &= ~(1 << ArgNo);
875 }
876
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000877 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000878 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000879 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000880 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000881 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000882 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000883 break;
Martin Storsjo022e7822017-07-17 20:49:45 +0000884 case Builtin::BI__builtin_ms_va_start:
Ted Kremeneka174c522008-07-09 17:58:53 +0000885 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000886 case Builtin::BI__builtin_va_start:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000887 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000888 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000889 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000890 case Builtin::BI__va_start: {
891 switch (Context.getTargetInfo().getTriple().getArch()) {
892 case llvm::Triple::arm:
893 case llvm::Triple::thumb:
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +0000894 if (SemaBuiltinVAStartARMMicrosoft(TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000895 return ExprError();
896 break;
897 default:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000898 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000899 return ExprError();
900 break;
901 }
902 break;
903 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000904 case Builtin::BI__builtin_isgreater:
905 case Builtin::BI__builtin_isgreaterequal:
906 case Builtin::BI__builtin_isless:
907 case Builtin::BI__builtin_islessequal:
908 case Builtin::BI__builtin_islessgreater:
909 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000910 if (SemaBuiltinUnorderedCompare(TheCall))
911 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000912 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000913 case Builtin::BI__builtin_fpclassify:
914 if (SemaBuiltinFPClassification(TheCall, 6))
915 return ExprError();
916 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000917 case Builtin::BI__builtin_isfinite:
918 case Builtin::BI__builtin_isinf:
919 case Builtin::BI__builtin_isinf_sign:
920 case Builtin::BI__builtin_isnan:
921 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000922 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000923 return ExprError();
924 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000925 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000926 return SemaBuiltinShuffleVector(TheCall);
927 // TheCall will be freed by the smart pointer here, but that's fine, since
928 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000929 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000930 if (SemaBuiltinPrefetch(TheCall))
931 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000932 break;
David Majnemer51169932016-10-31 05:37:48 +0000933 case Builtin::BI__builtin_alloca_with_align:
934 if (SemaBuiltinAllocaWithAlign(TheCall))
935 return ExprError();
936 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000937 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000938 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000939 if (SemaBuiltinAssume(TheCall))
940 return ExprError();
941 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000942 case Builtin::BI__builtin_assume_aligned:
943 if (SemaBuiltinAssumeAligned(TheCall))
944 return ExprError();
945 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000946 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000947 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000948 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000949 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000950 case Builtin::BI__builtin_longjmp:
951 if (SemaBuiltinLongjmp(TheCall))
952 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000953 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000954 case Builtin::BI__builtin_setjmp:
955 if (SemaBuiltinSetjmp(TheCall))
956 return ExprError();
957 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000958 case Builtin::BI_setjmp:
959 case Builtin::BI_setjmpex:
960 if (checkArgCount(*this, TheCall, 1))
961 return true;
962 break;
John McCallbebede42011-02-26 05:39:39 +0000963 case Builtin::BI__builtin_classify_type:
964 if (checkArgCount(*this, TheCall, 1)) return true;
965 TheCall->setType(Context.IntTy);
966 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000967 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000968 if (checkArgCount(*this, TheCall, 1)) return true;
969 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000970 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000971 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000972 case Builtin::BI__sync_fetch_and_add_1:
973 case Builtin::BI__sync_fetch_and_add_2:
974 case Builtin::BI__sync_fetch_and_add_4:
975 case Builtin::BI__sync_fetch_and_add_8:
976 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000977 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000978 case Builtin::BI__sync_fetch_and_sub_1:
979 case Builtin::BI__sync_fetch_and_sub_2:
980 case Builtin::BI__sync_fetch_and_sub_4:
981 case Builtin::BI__sync_fetch_and_sub_8:
982 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000983 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000984 case Builtin::BI__sync_fetch_and_or_1:
985 case Builtin::BI__sync_fetch_and_or_2:
986 case Builtin::BI__sync_fetch_and_or_4:
987 case Builtin::BI__sync_fetch_and_or_8:
988 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000989 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000990 case Builtin::BI__sync_fetch_and_and_1:
991 case Builtin::BI__sync_fetch_and_and_2:
992 case Builtin::BI__sync_fetch_and_and_4:
993 case Builtin::BI__sync_fetch_and_and_8:
994 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000995 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000996 case Builtin::BI__sync_fetch_and_xor_1:
997 case Builtin::BI__sync_fetch_and_xor_2:
998 case Builtin::BI__sync_fetch_and_xor_4:
999 case Builtin::BI__sync_fetch_and_xor_8:
1000 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001001 case Builtin::BI__sync_fetch_and_nand:
1002 case Builtin::BI__sync_fetch_and_nand_1:
1003 case Builtin::BI__sync_fetch_and_nand_2:
1004 case Builtin::BI__sync_fetch_and_nand_4:
1005 case Builtin::BI__sync_fetch_and_nand_8:
1006 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001007 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001008 case Builtin::BI__sync_add_and_fetch_1:
1009 case Builtin::BI__sync_add_and_fetch_2:
1010 case Builtin::BI__sync_add_and_fetch_4:
1011 case Builtin::BI__sync_add_and_fetch_8:
1012 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001013 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001014 case Builtin::BI__sync_sub_and_fetch_1:
1015 case Builtin::BI__sync_sub_and_fetch_2:
1016 case Builtin::BI__sync_sub_and_fetch_4:
1017 case Builtin::BI__sync_sub_and_fetch_8:
1018 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001019 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001020 case Builtin::BI__sync_and_and_fetch_1:
1021 case Builtin::BI__sync_and_and_fetch_2:
1022 case Builtin::BI__sync_and_and_fetch_4:
1023 case Builtin::BI__sync_and_and_fetch_8:
1024 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001025 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001026 case Builtin::BI__sync_or_and_fetch_1:
1027 case Builtin::BI__sync_or_and_fetch_2:
1028 case Builtin::BI__sync_or_and_fetch_4:
1029 case Builtin::BI__sync_or_and_fetch_8:
1030 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001031 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001032 case Builtin::BI__sync_xor_and_fetch_1:
1033 case Builtin::BI__sync_xor_and_fetch_2:
1034 case Builtin::BI__sync_xor_and_fetch_4:
1035 case Builtin::BI__sync_xor_and_fetch_8:
1036 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001037 case Builtin::BI__sync_nand_and_fetch:
1038 case Builtin::BI__sync_nand_and_fetch_1:
1039 case Builtin::BI__sync_nand_and_fetch_2:
1040 case Builtin::BI__sync_nand_and_fetch_4:
1041 case Builtin::BI__sync_nand_and_fetch_8:
1042 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001043 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001044 case Builtin::BI__sync_val_compare_and_swap_1:
1045 case Builtin::BI__sync_val_compare_and_swap_2:
1046 case Builtin::BI__sync_val_compare_and_swap_4:
1047 case Builtin::BI__sync_val_compare_and_swap_8:
1048 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001049 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001050 case Builtin::BI__sync_bool_compare_and_swap_1:
1051 case Builtin::BI__sync_bool_compare_and_swap_2:
1052 case Builtin::BI__sync_bool_compare_and_swap_4:
1053 case Builtin::BI__sync_bool_compare_and_swap_8:
1054 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001055 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +00001056 case Builtin::BI__sync_lock_test_and_set_1:
1057 case Builtin::BI__sync_lock_test_and_set_2:
1058 case Builtin::BI__sync_lock_test_and_set_4:
1059 case Builtin::BI__sync_lock_test_and_set_8:
1060 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001061 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001062 case Builtin::BI__sync_lock_release_1:
1063 case Builtin::BI__sync_lock_release_2:
1064 case Builtin::BI__sync_lock_release_4:
1065 case Builtin::BI__sync_lock_release_8:
1066 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001067 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001068 case Builtin::BI__sync_swap_1:
1069 case Builtin::BI__sync_swap_2:
1070 case Builtin::BI__sync_swap_4:
1071 case Builtin::BI__sync_swap_8:
1072 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001073 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001074 case Builtin::BI__builtin_nontemporal_load:
1075 case Builtin::BI__builtin_nontemporal_store:
1076 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +00001077#define BUILTIN(ID, TYPE, ATTRS)
1078#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1079 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001080 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +00001081#include "clang/Basic/Builtins.def"
Reid Kleckner30701ed2017-09-05 20:27:35 +00001082 case Builtin::BI__annotation:
1083 if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1084 return ExprError();
1085 break;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001086 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +00001087 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001088 return ExprError();
1089 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +00001090 case Builtin::BI__builtin_addressof:
1091 if (SemaBuiltinAddressof(*this, TheCall))
1092 return ExprError();
1093 break;
John McCall03107a42015-10-29 20:48:01 +00001094 case Builtin::BI__builtin_add_overflow:
1095 case Builtin::BI__builtin_sub_overflow:
1096 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +00001097 if (SemaBuiltinOverflow(*this, TheCall))
1098 return ExprError();
1099 break;
Richard Smith760520b2014-06-03 23:27:44 +00001100 case Builtin::BI__builtin_operator_new:
Eric Fiselierfa752f22018-03-21 19:19:48 +00001101 case Builtin::BI__builtin_operator_delete: {
1102 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1103 ExprResult Res =
1104 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1105 if (Res.isInvalid())
1106 CorrectDelayedTyposInExpr(TheCallResult.get());
1107 return Res;
1108 }
Aaron Ballman06525342018-04-10 21:58:13 +00001109 case Builtin::BI__builtin_dump_struct: {
1110 // We first want to ensure we are called with 2 arguments
1111 if (checkArgCount(*this, TheCall, 2))
1112 return ExprError();
1113 // Ensure that the first argument is of type 'struct XX *'
1114 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1115 const QualType PtrArgType = PtrArg->getType();
1116 if (!PtrArgType->isPointerType() ||
1117 !PtrArgType->getPointeeType()->isRecordType()) {
1118 Diag(PtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1119 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1120 << "structure pointer";
1121 return ExprError();
1122 }
1123
1124 // Ensure that the second argument is of type 'FunctionType'
1125 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1126 const QualType FnPtrArgType = FnPtrArg->getType();
1127 if (!FnPtrArgType->isPointerType()) {
1128 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1129 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1130 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1131 return ExprError();
1132 }
1133
1134 const auto *FuncType =
1135 FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1136
1137 if (!FuncType) {
1138 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1139 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1140 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1141 return ExprError();
1142 }
1143
1144 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1145 if (!FT->getNumParams()) {
1146 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1147 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1148 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1149 return ExprError();
1150 }
1151 QualType PT = FT->getParamType(0);
1152 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1153 !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1154 !PT->getPointeeType().isConstQualified()) {
1155 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1156 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1157 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1158 return ExprError();
1159 }
1160 }
1161
1162 TheCall->setType(Context.IntTy);
1163 break;
1164 }
1165
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001166 // check secure string manipulation functions where overflows
1167 // are detectable at compile time
1168 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001169 case Builtin::BI__builtin___memmove_chk:
1170 case Builtin::BI__builtin___memset_chk:
1171 case Builtin::BI__builtin___strlcat_chk:
1172 case Builtin::BI__builtin___strlcpy_chk:
1173 case Builtin::BI__builtin___strncat_chk:
1174 case Builtin::BI__builtin___strncpy_chk:
1175 case Builtin::BI__builtin___stpncpy_chk:
1176 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1177 break;
Steven Wu566c14e2014-09-24 04:37:33 +00001178 case Builtin::BI__builtin___memccpy_chk:
1179 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1180 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001181 case Builtin::BI__builtin___snprintf_chk:
1182 case Builtin::BI__builtin___vsnprintf_chk:
1183 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1184 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001185 case Builtin::BI__builtin_call_with_static_chain:
1186 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1187 return ExprError();
1188 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001189 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001190 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001191 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1192 diag::err_seh___except_block))
1193 return ExprError();
1194 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001195 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001196 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001197 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1198 diag::err_seh___except_filter))
1199 return ExprError();
1200 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001201 case Builtin::BI__GetExceptionInfo:
1202 if (checkArgCount(*this, TheCall, 1))
1203 return ExprError();
1204
1205 if (CheckCXXThrowOperand(
1206 TheCall->getLocStart(),
1207 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1208 TheCall))
1209 return ExprError();
1210
1211 TheCall->setType(Context.VoidPtrTy);
1212 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001213 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001214 case Builtin::BIread_pipe:
1215 case Builtin::BIwrite_pipe:
1216 // Since those two functions are declared with var args, we need a semantic
1217 // check for the argument.
1218 if (SemaBuiltinRWPipe(*this, TheCall))
1219 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001220 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001221 break;
1222 case Builtin::BIreserve_read_pipe:
1223 case Builtin::BIreserve_write_pipe:
1224 case Builtin::BIwork_group_reserve_read_pipe:
1225 case Builtin::BIwork_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001226 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1227 return ExprError();
Joey Gouly84ae3362017-07-31 15:15:59 +00001228 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001229 case Builtin::BIsub_group_reserve_read_pipe:
1230 case Builtin::BIsub_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001231 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1232 SemaBuiltinReserveRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001233 return ExprError();
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001234 break;
1235 case Builtin::BIcommit_read_pipe:
1236 case Builtin::BIcommit_write_pipe:
1237 case Builtin::BIwork_group_commit_read_pipe:
1238 case Builtin::BIwork_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001239 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1240 return ExprError();
1241 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001242 case Builtin::BIsub_group_commit_read_pipe:
1243 case Builtin::BIsub_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001244 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1245 SemaBuiltinCommitRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001246 return ExprError();
1247 break;
1248 case Builtin::BIget_pipe_num_packets:
1249 case Builtin::BIget_pipe_max_packets:
1250 if (SemaBuiltinPipePackets(*this, TheCall))
1251 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001252 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001253 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001254 case Builtin::BIto_global:
1255 case Builtin::BIto_local:
1256 case Builtin::BIto_private:
1257 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1258 return ExprError();
1259 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001260 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1261 case Builtin::BIenqueue_kernel:
1262 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1263 return ExprError();
1264 break;
1265 case Builtin::BIget_kernel_work_group_size:
1266 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1267 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1268 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001269 break;
Joey Goulyfa76b492017-08-01 13:27:09 +00001270 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1271 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1272 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1273 return ExprError();
1274 break;
Mehdi Amini06d367c2016-10-24 20:39:34 +00001275 case Builtin::BI__builtin_os_log_format:
1276 case Builtin::BI__builtin_os_log_format_buffer_size:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00001277 if (SemaBuiltinOSLogFormat(TheCall))
Mehdi Amini06d367c2016-10-24 20:39:34 +00001278 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001279 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001280 }
Richard Smith760520b2014-06-03 23:27:44 +00001281
Nate Begeman4904e322010-06-08 02:47:44 +00001282 // Since the target specific builtins for each arch overlap, only check those
1283 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001284 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001285 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001286 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001287 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001288 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001289 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001290 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1291 return ExprError();
1292 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001293 case llvm::Triple::aarch64:
1294 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001295 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001296 return ExprError();
1297 break;
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00001298 case llvm::Triple::hexagon:
1299 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1300 return ExprError();
1301 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001302 case llvm::Triple::mips:
1303 case llvm::Triple::mipsel:
1304 case llvm::Triple::mips64:
1305 case llvm::Triple::mips64el:
1306 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1307 return ExprError();
1308 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001309 case llvm::Triple::systemz:
1310 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1311 return ExprError();
1312 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001313 case llvm::Triple::x86:
1314 case llvm::Triple::x86_64:
1315 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1316 return ExprError();
1317 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001318 case llvm::Triple::ppc:
1319 case llvm::Triple::ppc64:
1320 case llvm::Triple::ppc64le:
1321 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1322 return ExprError();
1323 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001324 default:
1325 break;
1326 }
1327 }
1328
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001329 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001330}
1331
Nate Begeman91e1fea2010-06-14 05:21:25 +00001332// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001333static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001334 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001335 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001336 switch (Type.getEltType()) {
1337 case NeonTypeFlags::Int8:
1338 case NeonTypeFlags::Poly8:
1339 return shift ? 7 : (8 << IsQuad) - 1;
1340 case NeonTypeFlags::Int16:
1341 case NeonTypeFlags::Poly16:
1342 return shift ? 15 : (4 << IsQuad) - 1;
1343 case NeonTypeFlags::Int32:
1344 return shift ? 31 : (2 << IsQuad) - 1;
1345 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001346 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001347 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001348 case NeonTypeFlags::Poly128:
1349 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001350 case NeonTypeFlags::Float16:
1351 assert(!shift && "cannot shift float types!");
1352 return (4 << IsQuad) - 1;
1353 case NeonTypeFlags::Float32:
1354 assert(!shift && "cannot shift float types!");
1355 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001356 case NeonTypeFlags::Float64:
1357 assert(!shift && "cannot shift float types!");
1358 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001359 }
David Blaikie8a40f702012-01-17 06:56:22 +00001360 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001361}
1362
Bob Wilsone4d77232011-11-08 05:04:11 +00001363/// getNeonEltType - Return the QualType corresponding to the elements of
1364/// the vector type specified by the NeonTypeFlags. This is used to check
1365/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001366static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001367 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001368 switch (Flags.getEltType()) {
1369 case NeonTypeFlags::Int8:
1370 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1371 case NeonTypeFlags::Int16:
1372 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1373 case NeonTypeFlags::Int32:
1374 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1375 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001376 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001377 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1378 else
1379 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1380 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001381 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001382 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001383 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001384 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001385 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001386 if (IsInt64Long)
1387 return Context.UnsignedLongTy;
1388 else
1389 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001390 case NeonTypeFlags::Poly128:
1391 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001392 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001393 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001394 case NeonTypeFlags::Float32:
1395 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001396 case NeonTypeFlags::Float64:
1397 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001398 }
David Blaikie8a40f702012-01-17 06:56:22 +00001399 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001400}
1401
Tim Northover12670412014-02-19 10:37:05 +00001402bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001403 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001404 uint64_t mask = 0;
1405 unsigned TV = 0;
1406 int PtrArgNum = -1;
1407 bool HasConstPtr = false;
1408 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001409#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001410#include "clang/Basic/arm_neon.inc"
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +00001411#include "clang/Basic/arm_fp16.inc"
Tim Northover12670412014-02-19 10:37:05 +00001412#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001413 }
1414
1415 // For NEON intrinsics which are overloaded on vector element type, validate
1416 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001417 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001418 if (mask) {
1419 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1420 return true;
1421
1422 TV = Result.getLimitedValue(64);
1423 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1424 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001425 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001426 }
1427
1428 if (PtrArgNum >= 0) {
1429 // Check that pointer arguments have the specified type.
1430 Expr *Arg = TheCall->getArg(PtrArgNum);
1431 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1432 Arg = ICE->getSubExpr();
1433 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1434 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001435
Tim Northovera2ee4332014-03-29 15:09:45 +00001436 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001437 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1438 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001439 bool IsInt64Long =
1440 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1441 QualType EltTy =
1442 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001443 if (HasConstPtr)
1444 EltTy = EltTy.withConst();
1445 QualType LHSTy = Context.getPointerType(EltTy);
1446 AssignConvertType ConvTy;
1447 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1448 if (RHS.isInvalid())
1449 return true;
1450 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1451 RHS.get(), AA_Assigning))
1452 return true;
1453 }
1454
1455 // For NEON intrinsics which take an immediate value as part of the
1456 // instruction, range check them here.
1457 unsigned i = 0, l = 0, u = 0;
1458 switch (BuiltinID) {
1459 default:
1460 return false;
Tim Northover12670412014-02-19 10:37:05 +00001461#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001462#include "clang/Basic/arm_neon.inc"
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +00001463#include "clang/Basic/arm_fp16.inc"
Tim Northover12670412014-02-19 10:37:05 +00001464#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001465 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001466
Richard Sandiford28940af2014-04-16 08:47:51 +00001467 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001468}
1469
Tim Northovera2ee4332014-03-29 15:09:45 +00001470bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1471 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001472 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001473 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001474 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001475 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001476 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001477 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1478 BuiltinID == AArch64::BI__builtin_arm_strex ||
1479 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001480 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001481 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001482 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1483 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1484 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001485
1486 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1487
1488 // Ensure that we have the proper number of arguments.
1489 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1490 return true;
1491
1492 // Inspect the pointer argument of the atomic builtin. This should always be
1493 // a pointer type, whose element is an integral scalar or pointer type.
1494 // Because it is a pointer type, we don't have to worry about any implicit
1495 // casts here.
1496 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1497 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1498 if (PointerArgRes.isInvalid())
1499 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001500 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001501
1502 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1503 if (!pointerType) {
1504 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1505 << PointerArg->getType() << PointerArg->getSourceRange();
1506 return true;
1507 }
1508
1509 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1510 // task is to insert the appropriate casts into the AST. First work out just
1511 // what the appropriate type is.
1512 QualType ValType = pointerType->getPointeeType();
1513 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1514 if (IsLdrex)
1515 AddrType.addConst();
1516
1517 // Issue a warning if the cast is dodgy.
1518 CastKind CastNeeded = CK_NoOp;
1519 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1520 CastNeeded = CK_BitCast;
1521 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1522 << PointerArg->getType()
1523 << Context.getPointerType(AddrType)
1524 << AA_Passing << PointerArg->getSourceRange();
1525 }
1526
1527 // Finally, do the cast and replace the argument with the corrected version.
1528 AddrType = Context.getPointerType(AddrType);
1529 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1530 if (PointerArgRes.isInvalid())
1531 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001532 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001533
1534 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1535
1536 // In general, we allow ints, floats and pointers to be loaded and stored.
1537 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1538 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1539 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1540 << PointerArg->getType() << PointerArg->getSourceRange();
1541 return true;
1542 }
1543
1544 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001545 if (Context.getTypeSize(ValType) > MaxWidth) {
1546 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001547 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1548 << PointerArg->getType() << PointerArg->getSourceRange();
1549 return true;
1550 }
1551
1552 switch (ValType.getObjCLifetime()) {
1553 case Qualifiers::OCL_None:
1554 case Qualifiers::OCL_ExplicitNone:
1555 // okay
1556 break;
1557
1558 case Qualifiers::OCL_Weak:
1559 case Qualifiers::OCL_Strong:
1560 case Qualifiers::OCL_Autoreleasing:
1561 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1562 << ValType << PointerArg->getSourceRange();
1563 return true;
1564 }
1565
Tim Northover6aacd492013-07-16 09:47:53 +00001566 if (IsLdrex) {
1567 TheCall->setType(ValType);
1568 return false;
1569 }
1570
1571 // Initialize the argument to be stored.
1572 ExprResult ValArg = TheCall->getArg(0);
1573 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1574 Context, ValType, /*consume*/ false);
1575 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1576 if (ValArg.isInvalid())
1577 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001578 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001579
1580 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1581 // but the custom checker bypasses all default analysis.
1582 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001583 return false;
1584}
1585
Nate Begeman4904e322010-06-08 02:47:44 +00001586bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover6aacd492013-07-16 09:47:53 +00001587 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001588 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1589 BuiltinID == ARM::BI__builtin_arm_strex ||
1590 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001591 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001592 }
1593
Yi Kong26d104a2014-08-13 19:18:14 +00001594 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1595 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1596 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1597 }
1598
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001599 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1600 BuiltinID == ARM::BI__builtin_arm_wsr64)
1601 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1602
1603 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1604 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1605 BuiltinID == ARM::BI__builtin_arm_wsr ||
1606 BuiltinID == ARM::BI__builtin_arm_wsrp)
1607 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1608
Tim Northover12670412014-02-19 10:37:05 +00001609 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1610 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001611
Yi Kong4efadfb2014-07-03 16:01:25 +00001612 // For intrinsics which take an immediate value as part of the instruction,
1613 // range check them here.
Sjoerd Meijer293da702017-12-07 09:54:39 +00001614 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begemand773fe62010-06-13 04:47:52 +00001615 switch (BuiltinID) {
1616 default: return false;
Sjoerd Meijer293da702017-12-07 09:54:39 +00001617 case ARM::BI__builtin_arm_ssat:
1618 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1619 case ARM::BI__builtin_arm_usat:
1620 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1621 case ARM::BI__builtin_arm_ssat16:
1622 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1623 case ARM::BI__builtin_arm_usat16:
1624 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
Nate Begemanf568b072010-08-03 21:32:34 +00001625 case ARM::BI__builtin_arm_vcvtr_f:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001626 case ARM::BI__builtin_arm_vcvtr_d:
1627 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
Weiming Zhao87bb4922013-11-12 21:42:50 +00001628 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001629 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001630 case ARM::BI__builtin_arm_isb:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001631 case ARM::BI__builtin_arm_dbg:
1632 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
Richard Sandiford28940af2014-04-16 08:47:51 +00001633 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001634}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001635
Tim Northover573cbee2014-05-24 12:52:07 +00001636bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001637 CallExpr *TheCall) {
Tim Northover573cbee2014-05-24 12:52:07 +00001638 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001639 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1640 BuiltinID == AArch64::BI__builtin_arm_strex ||
1641 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001642 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1643 }
1644
Yi Konga5548432014-08-13 19:18:20 +00001645 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1646 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1647 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1648 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1649 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1650 }
1651
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001652 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1653 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001654 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001655
1656 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1657 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1658 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1659 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1660 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1661
Tim Northovera2ee4332014-03-29 15:09:45 +00001662 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1663 return true;
1664
Yi Kong19a29ac2014-07-17 10:52:06 +00001665 // For intrinsics which take an immediate value as part of the instruction,
1666 // range check them here.
1667 unsigned i = 0, l = 0, u = 0;
1668 switch (BuiltinID) {
1669 default: return false;
1670 case AArch64::BI__builtin_arm_dmb:
1671 case AArch64::BI__builtin_arm_dsb:
1672 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1673 }
1674
Yi Kong19a29ac2014-07-17 10:52:06 +00001675 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001676}
1677
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00001678bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
1679 CallExpr *TheCall) {
1680 struct ArgInfo {
1681 ArgInfo(unsigned O, bool S, unsigned W, unsigned A)
1682 : OpNum(O), IsSigned(S), BitWidth(W), Align(A) {}
1683 unsigned OpNum = 0;
1684 bool IsSigned = false;
1685 unsigned BitWidth = 0;
1686 unsigned Align = 0;
1687 };
1688
1689 static const std::map<unsigned, std::vector<ArgInfo>> Infos = {
1690 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
1691 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
1692 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
1693 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} },
1694 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
1695 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
1696 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
1697 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
1698 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
1699 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
1700 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
1701
1702 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
1703 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
1704 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
1705 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
1706 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
1707 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
1708 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
1709 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
1710 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
1711 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
1712 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
1713
1714 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
1715 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
1716 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
1717 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
1718 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
1719 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
1720 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
1721 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
1722 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
1723 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
1724 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
1725 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
1726 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
1727 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
1728 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
1729 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
1730 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
1731 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
1732 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
1733 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
1734 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
1735 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
1736 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
1737 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
1738 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
1739 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
1740 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
1741 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
1742 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
1743 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
1744 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
1745 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
1746 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
1747 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
1748 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
1749 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
1750 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
1751 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
1752 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
1753 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
1754 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
1755 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
1756 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
1757 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
1758 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
1759 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
1760 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
1761 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
1762 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
1763 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
1764 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
1765 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
1766 {{ 1, false, 6, 0 }} },
1767 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
1768 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
1769 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
1770 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
1771 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
1772 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
1773 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
1774 {{ 1, false, 5, 0 }} },
1775 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
1776 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
1777 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
1778 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
1779 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
1780 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
1781 { 2, false, 5, 0 }} },
1782 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
1783 { 2, false, 6, 0 }} },
1784 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
1785 { 3, false, 5, 0 }} },
1786 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
1787 { 3, false, 6, 0 }} },
1788 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
1789 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
1790 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
1791 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
1792 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
1793 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
1794 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
1795 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
1796 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
1797 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
1798 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
1799 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
1800 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
1801 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
1802 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
1803 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
1804 {{ 2, false, 4, 0 },
1805 { 3, false, 5, 0 }} },
1806 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
1807 {{ 2, false, 4, 0 },
1808 { 3, false, 5, 0 }} },
1809 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
1810 {{ 2, false, 4, 0 },
1811 { 3, false, 5, 0 }} },
1812 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
1813 {{ 2, false, 4, 0 },
1814 { 3, false, 5, 0 }} },
1815 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
1816 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
1817 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
1818 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
1819 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
1820 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
1821 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
1822 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
1823 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
1824 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
1825 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
1826 { 2, false, 5, 0 }} },
1827 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
1828 { 2, false, 6, 0 }} },
1829 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
1830 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
1831 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
1832 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
1833 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
1834 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
1835 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
1836 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
1837 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
1838 {{ 1, false, 4, 0 }} },
1839 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
1840 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
1841 {{ 1, false, 4, 0 }} },
1842 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
1843 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
1844 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
1845 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
1846 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
1847 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
1848 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
1849 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
1850 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
1851 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
1852 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
1853 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
1854 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
1855 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
1856 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
1857 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
1858 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
1859 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
1860 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
1861 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
1862 {{ 3, false, 1, 0 }} },
1863 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
1864 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
1865 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
1866 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
1867 {{ 3, false, 1, 0 }} },
1868 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
1869 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
1870 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
1871 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
1872 {{ 3, false, 1, 0 }} },
1873 };
1874
1875 auto F = Infos.find(BuiltinID);
1876 if (F == Infos.end())
1877 return false;
1878
1879 bool Error = false;
1880
1881 for (const ArgInfo &A : F->second) {
1882 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth-1)) : 0;
1883 int32_t Max = (1 << (A.IsSigned ? A.BitWidth-1 : A.BitWidth)) - 1;
1884 if (!A.Align) {
1885 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
1886 } else {
1887 unsigned M = 1 << A.Align;
1888 Min *= M;
1889 Max *= M;
1890 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
1891 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
1892 }
1893 }
1894 return Error;
1895}
1896
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001897// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1898// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1899// ordering for DSP is unspecified. MSA is ordered by the data format used
1900// by the underlying instruction i.e., df/m, df/n and then by size.
1901//
1902// FIXME: The size tests here should instead be tablegen'd along with the
1903// definitions from include/clang/Basic/BuiltinsMips.def.
1904// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1905// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001906bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001907 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001908 switch (BuiltinID) {
1909 default: return false;
1910 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1911 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001912 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1913 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1914 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1915 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1916 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001917 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1918 // df/m field.
1919 // These intrinsics take an unsigned 3 bit immediate.
1920 case Mips::BI__builtin_msa_bclri_b:
1921 case Mips::BI__builtin_msa_bnegi_b:
1922 case Mips::BI__builtin_msa_bseti_b:
1923 case Mips::BI__builtin_msa_sat_s_b:
1924 case Mips::BI__builtin_msa_sat_u_b:
1925 case Mips::BI__builtin_msa_slli_b:
1926 case Mips::BI__builtin_msa_srai_b:
1927 case Mips::BI__builtin_msa_srari_b:
1928 case Mips::BI__builtin_msa_srli_b:
1929 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1930 case Mips::BI__builtin_msa_binsli_b:
1931 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1932 // These intrinsics take an unsigned 4 bit immediate.
1933 case Mips::BI__builtin_msa_bclri_h:
1934 case Mips::BI__builtin_msa_bnegi_h:
1935 case Mips::BI__builtin_msa_bseti_h:
1936 case Mips::BI__builtin_msa_sat_s_h:
1937 case Mips::BI__builtin_msa_sat_u_h:
1938 case Mips::BI__builtin_msa_slli_h:
1939 case Mips::BI__builtin_msa_srai_h:
1940 case Mips::BI__builtin_msa_srari_h:
1941 case Mips::BI__builtin_msa_srli_h:
1942 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1943 case Mips::BI__builtin_msa_binsli_h:
1944 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001945 // These intrinsics take an unsigned 5 bit immediate.
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001946 // The first block of intrinsics actually have an unsigned 5 bit field,
1947 // not a df/n field.
1948 case Mips::BI__builtin_msa_clei_u_b:
1949 case Mips::BI__builtin_msa_clei_u_h:
1950 case Mips::BI__builtin_msa_clei_u_w:
1951 case Mips::BI__builtin_msa_clei_u_d:
1952 case Mips::BI__builtin_msa_clti_u_b:
1953 case Mips::BI__builtin_msa_clti_u_h:
1954 case Mips::BI__builtin_msa_clti_u_w:
1955 case Mips::BI__builtin_msa_clti_u_d:
1956 case Mips::BI__builtin_msa_maxi_u_b:
1957 case Mips::BI__builtin_msa_maxi_u_h:
1958 case Mips::BI__builtin_msa_maxi_u_w:
1959 case Mips::BI__builtin_msa_maxi_u_d:
1960 case Mips::BI__builtin_msa_mini_u_b:
1961 case Mips::BI__builtin_msa_mini_u_h:
1962 case Mips::BI__builtin_msa_mini_u_w:
1963 case Mips::BI__builtin_msa_mini_u_d:
1964 case Mips::BI__builtin_msa_addvi_b:
1965 case Mips::BI__builtin_msa_addvi_h:
1966 case Mips::BI__builtin_msa_addvi_w:
1967 case Mips::BI__builtin_msa_addvi_d:
1968 case Mips::BI__builtin_msa_bclri_w:
1969 case Mips::BI__builtin_msa_bnegi_w:
1970 case Mips::BI__builtin_msa_bseti_w:
1971 case Mips::BI__builtin_msa_sat_s_w:
1972 case Mips::BI__builtin_msa_sat_u_w:
1973 case Mips::BI__builtin_msa_slli_w:
1974 case Mips::BI__builtin_msa_srai_w:
1975 case Mips::BI__builtin_msa_srari_w:
1976 case Mips::BI__builtin_msa_srli_w:
1977 case Mips::BI__builtin_msa_srlri_w:
1978 case Mips::BI__builtin_msa_subvi_b:
1979 case Mips::BI__builtin_msa_subvi_h:
1980 case Mips::BI__builtin_msa_subvi_w:
1981 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1982 case Mips::BI__builtin_msa_binsli_w:
1983 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1984 // These intrinsics take an unsigned 6 bit immediate.
1985 case Mips::BI__builtin_msa_bclri_d:
1986 case Mips::BI__builtin_msa_bnegi_d:
1987 case Mips::BI__builtin_msa_bseti_d:
1988 case Mips::BI__builtin_msa_sat_s_d:
1989 case Mips::BI__builtin_msa_sat_u_d:
1990 case Mips::BI__builtin_msa_slli_d:
1991 case Mips::BI__builtin_msa_srai_d:
1992 case Mips::BI__builtin_msa_srari_d:
1993 case Mips::BI__builtin_msa_srli_d:
1994 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1995 case Mips::BI__builtin_msa_binsli_d:
1996 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1997 // These intrinsics take a signed 5 bit immediate.
1998 case Mips::BI__builtin_msa_ceqi_b:
1999 case Mips::BI__builtin_msa_ceqi_h:
2000 case Mips::BI__builtin_msa_ceqi_w:
2001 case Mips::BI__builtin_msa_ceqi_d:
2002 case Mips::BI__builtin_msa_clti_s_b:
2003 case Mips::BI__builtin_msa_clti_s_h:
2004 case Mips::BI__builtin_msa_clti_s_w:
2005 case Mips::BI__builtin_msa_clti_s_d:
2006 case Mips::BI__builtin_msa_clei_s_b:
2007 case Mips::BI__builtin_msa_clei_s_h:
2008 case Mips::BI__builtin_msa_clei_s_w:
2009 case Mips::BI__builtin_msa_clei_s_d:
2010 case Mips::BI__builtin_msa_maxi_s_b:
2011 case Mips::BI__builtin_msa_maxi_s_h:
2012 case Mips::BI__builtin_msa_maxi_s_w:
2013 case Mips::BI__builtin_msa_maxi_s_d:
2014 case Mips::BI__builtin_msa_mini_s_b:
2015 case Mips::BI__builtin_msa_mini_s_h:
2016 case Mips::BI__builtin_msa_mini_s_w:
2017 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
2018 // These intrinsics take an unsigned 8 bit immediate.
2019 case Mips::BI__builtin_msa_andi_b:
2020 case Mips::BI__builtin_msa_nori_b:
2021 case Mips::BI__builtin_msa_ori_b:
2022 case Mips::BI__builtin_msa_shf_b:
2023 case Mips::BI__builtin_msa_shf_h:
2024 case Mips::BI__builtin_msa_shf_w:
2025 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
2026 case Mips::BI__builtin_msa_bseli_b:
2027 case Mips::BI__builtin_msa_bmnzi_b:
2028 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
2029 // df/n format
2030 // These intrinsics take an unsigned 4 bit immediate.
2031 case Mips::BI__builtin_msa_copy_s_b:
2032 case Mips::BI__builtin_msa_copy_u_b:
2033 case Mips::BI__builtin_msa_insve_b:
2034 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002035 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
2036 // These intrinsics take an unsigned 3 bit immediate.
2037 case Mips::BI__builtin_msa_copy_s_h:
2038 case Mips::BI__builtin_msa_copy_u_h:
2039 case Mips::BI__builtin_msa_insve_h:
2040 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002041 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
2042 // These intrinsics take an unsigned 2 bit immediate.
2043 case Mips::BI__builtin_msa_copy_s_w:
2044 case Mips::BI__builtin_msa_copy_u_w:
2045 case Mips::BI__builtin_msa_insve_w:
2046 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002047 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
2048 // These intrinsics take an unsigned 1 bit immediate.
2049 case Mips::BI__builtin_msa_copy_s_d:
2050 case Mips::BI__builtin_msa_copy_u_d:
2051 case Mips::BI__builtin_msa_insve_d:
2052 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002053 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
2054 // Memory offsets and immediate loads.
2055 // These intrinsics take a signed 10 bit immediate.
Petar Jovanovic9b8b9e82017-03-31 16:16:43 +00002056 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002057 case Mips::BI__builtin_msa_ldi_h:
2058 case Mips::BI__builtin_msa_ldi_w:
2059 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
2060 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
2061 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
2062 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
2063 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
2064 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
2065 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
2066 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
2067 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00002068 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00002069
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002070 if (!m)
2071 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2072
2073 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
2074 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00002075}
2076
Kit Bartone50adcb2015-03-30 19:40:59 +00002077bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2078 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00002079 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
2080 BuiltinID == PPC::BI__builtin_divdeu ||
2081 BuiltinID == PPC::BI__builtin_bpermd;
2082 bool IsTarget64Bit = Context.getTargetInfo()
2083 .getTypeWidth(Context
2084 .getTargetInfo()
2085 .getIntPtrType()) == 64;
2086 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
2087 BuiltinID == PPC::BI__builtin_divweu ||
2088 BuiltinID == PPC::BI__builtin_divde ||
2089 BuiltinID == PPC::BI__builtin_divdeu;
2090
2091 if (Is64BitBltin && !IsTarget64Bit)
2092 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
2093 << TheCall->getSourceRange();
2094
2095 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
2096 (BuiltinID == PPC::BI__builtin_bpermd &&
2097 !Context.getTargetInfo().hasFeature("bpermd")))
2098 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
2099 << TheCall->getSourceRange();
2100
Kit Bartone50adcb2015-03-30 19:40:59 +00002101 switch (BuiltinID) {
2102 default: return false;
2103 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
2104 case PPC::BI__builtin_altivec_crypto_vshasigmad:
2105 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2106 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
2107 case PPC::BI__builtin_tbegin:
2108 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
2109 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
2110 case PPC::BI__builtin_tabortwc:
2111 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
2112 case PPC::BI__builtin_tabortwci:
2113 case PPC::BI__builtin_tabortdci:
2114 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
2115 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
Tony Jiangbbc48e92017-05-24 15:13:32 +00002116 case PPC::BI__builtin_vsx_xxpermdi:
Tony Jiang9aa2c032017-05-24 15:54:13 +00002117 case PPC::BI__builtin_vsx_xxsldwi:
Tony Jiangbbc48e92017-05-24 15:13:32 +00002118 return SemaBuiltinVSX(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00002119 }
2120 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2121}
2122
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00002123bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
2124 CallExpr *TheCall) {
2125 if (BuiltinID == SystemZ::BI__builtin_tabort) {
2126 Expr *Arg = TheCall->getArg(0);
2127 llvm::APSInt AbortCode(32);
2128 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
2129 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
2130 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
2131 << Arg->getSourceRange();
2132 }
2133
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002134 // For intrinsics which take an immediate value as part of the instruction,
2135 // range check them here.
2136 unsigned i = 0, l = 0, u = 0;
2137 switch (BuiltinID) {
2138 default: return false;
2139 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
2140 case SystemZ::BI__builtin_s390_verimb:
2141 case SystemZ::BI__builtin_s390_verimh:
2142 case SystemZ::BI__builtin_s390_verimf:
2143 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
2144 case SystemZ::BI__builtin_s390_vfaeb:
2145 case SystemZ::BI__builtin_s390_vfaeh:
2146 case SystemZ::BI__builtin_s390_vfaef:
2147 case SystemZ::BI__builtin_s390_vfaebs:
2148 case SystemZ::BI__builtin_s390_vfaehs:
2149 case SystemZ::BI__builtin_s390_vfaefs:
2150 case SystemZ::BI__builtin_s390_vfaezb:
2151 case SystemZ::BI__builtin_s390_vfaezh:
2152 case SystemZ::BI__builtin_s390_vfaezf:
2153 case SystemZ::BI__builtin_s390_vfaezbs:
2154 case SystemZ::BI__builtin_s390_vfaezhs:
2155 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00002156 case SystemZ::BI__builtin_s390_vfisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002157 case SystemZ::BI__builtin_s390_vfidb:
2158 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
2159 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00002160 case SystemZ::BI__builtin_s390_vftcisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002161 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
2162 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
2163 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
2164 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
2165 case SystemZ::BI__builtin_s390_vstrcb:
2166 case SystemZ::BI__builtin_s390_vstrch:
2167 case SystemZ::BI__builtin_s390_vstrcf:
2168 case SystemZ::BI__builtin_s390_vstrczb:
2169 case SystemZ::BI__builtin_s390_vstrczh:
2170 case SystemZ::BI__builtin_s390_vstrczf:
2171 case SystemZ::BI__builtin_s390_vstrcbs:
2172 case SystemZ::BI__builtin_s390_vstrchs:
2173 case SystemZ::BI__builtin_s390_vstrcfs:
2174 case SystemZ::BI__builtin_s390_vstrczbs:
2175 case SystemZ::BI__builtin_s390_vstrczhs:
2176 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00002177 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
2178 case SystemZ::BI__builtin_s390_vfminsb:
2179 case SystemZ::BI__builtin_s390_vfmaxsb:
2180 case SystemZ::BI__builtin_s390_vfmindb:
2181 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002182 }
2183 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00002184}
2185
Craig Topper5ba2c502015-11-07 08:08:31 +00002186/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
2187/// This checks that the target supports __builtin_cpu_supports and
2188/// that the string argument is constant and valid.
2189static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
2190 Expr *Arg = TheCall->getArg(0);
2191
2192 // Check if the argument is a string literal.
2193 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2194 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2195 << Arg->getSourceRange();
2196
2197 // Check the contents of the string.
2198 StringRef Feature =
2199 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2200 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
2201 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
2202 << Arg->getSourceRange();
2203 return false;
2204}
2205
Craig Topper699ae0c2017-08-10 20:28:30 +00002206/// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
2207/// This checks that the target supports __builtin_cpu_is and
2208/// that the string argument is constant and valid.
2209static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
2210 Expr *Arg = TheCall->getArg(0);
2211
2212 // Check if the argument is a string literal.
2213 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2214 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2215 << Arg->getSourceRange();
2216
2217 // Check the contents of the string.
2218 StringRef Feature =
2219 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2220 if (!S.Context.getTargetInfo().validateCpuIs(Feature))
2221 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
2222 << Arg->getSourceRange();
2223 return false;
2224}
2225
Craig Toppera7e253e2016-09-23 04:48:31 +00002226// Check if the rounding mode is legal.
2227bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
2228 // Indicates if this instruction has rounding control or just SAE.
2229 bool HasRC = false;
2230
2231 unsigned ArgNum = 0;
2232 switch (BuiltinID) {
2233 default:
2234 return false;
2235 case X86::BI__builtin_ia32_vcvttsd2si32:
2236 case X86::BI__builtin_ia32_vcvttsd2si64:
2237 case X86::BI__builtin_ia32_vcvttsd2usi32:
2238 case X86::BI__builtin_ia32_vcvttsd2usi64:
2239 case X86::BI__builtin_ia32_vcvttss2si32:
2240 case X86::BI__builtin_ia32_vcvttss2si64:
2241 case X86::BI__builtin_ia32_vcvttss2usi32:
2242 case X86::BI__builtin_ia32_vcvttss2usi64:
2243 ArgNum = 1;
2244 break;
2245 case X86::BI__builtin_ia32_cvtps2pd512_mask:
2246 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
2247 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
2248 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
2249 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
2250 case X86::BI__builtin_ia32_cvttps2dq512_mask:
2251 case X86::BI__builtin_ia32_cvttps2qq512_mask:
2252 case X86::BI__builtin_ia32_cvttps2udq512_mask:
2253 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
2254 case X86::BI__builtin_ia32_exp2pd_mask:
2255 case X86::BI__builtin_ia32_exp2ps_mask:
2256 case X86::BI__builtin_ia32_getexppd512_mask:
2257 case X86::BI__builtin_ia32_getexpps512_mask:
2258 case X86::BI__builtin_ia32_rcp28pd_mask:
2259 case X86::BI__builtin_ia32_rcp28ps_mask:
2260 case X86::BI__builtin_ia32_rsqrt28pd_mask:
2261 case X86::BI__builtin_ia32_rsqrt28ps_mask:
2262 case X86::BI__builtin_ia32_vcomisd:
2263 case X86::BI__builtin_ia32_vcomiss:
2264 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
2265 ArgNum = 3;
2266 break;
2267 case X86::BI__builtin_ia32_cmppd512_mask:
2268 case X86::BI__builtin_ia32_cmpps512_mask:
2269 case X86::BI__builtin_ia32_cmpsd_mask:
2270 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002271 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00002272 case X86::BI__builtin_ia32_getexpsd128_round_mask:
2273 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002274 case X86::BI__builtin_ia32_maxpd512_mask:
2275 case X86::BI__builtin_ia32_maxps512_mask:
2276 case X86::BI__builtin_ia32_maxsd_round_mask:
2277 case X86::BI__builtin_ia32_maxss_round_mask:
2278 case X86::BI__builtin_ia32_minpd512_mask:
2279 case X86::BI__builtin_ia32_minps512_mask:
2280 case X86::BI__builtin_ia32_minsd_round_mask:
2281 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00002282 case X86::BI__builtin_ia32_rcp28sd_round_mask:
2283 case X86::BI__builtin_ia32_rcp28ss_round_mask:
2284 case X86::BI__builtin_ia32_reducepd512_mask:
2285 case X86::BI__builtin_ia32_reduceps512_mask:
2286 case X86::BI__builtin_ia32_rndscalepd_mask:
2287 case X86::BI__builtin_ia32_rndscaleps_mask:
2288 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
2289 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
2290 ArgNum = 4;
2291 break;
2292 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002293 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002294 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002295 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002296 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002297 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002298 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002299 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002300 case X86::BI__builtin_ia32_rangepd512_mask:
2301 case X86::BI__builtin_ia32_rangeps512_mask:
2302 case X86::BI__builtin_ia32_rangesd128_round_mask:
2303 case X86::BI__builtin_ia32_rangess128_round_mask:
2304 case X86::BI__builtin_ia32_reducesd_mask:
2305 case X86::BI__builtin_ia32_reducess_mask:
2306 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2307 case X86::BI__builtin_ia32_rndscaless_round_mask:
2308 ArgNum = 5;
2309 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00002310 case X86::BI__builtin_ia32_vcvtsd2si64:
2311 case X86::BI__builtin_ia32_vcvtsd2si32:
2312 case X86::BI__builtin_ia32_vcvtsd2usi32:
2313 case X86::BI__builtin_ia32_vcvtsd2usi64:
2314 case X86::BI__builtin_ia32_vcvtss2si32:
2315 case X86::BI__builtin_ia32_vcvtss2si64:
2316 case X86::BI__builtin_ia32_vcvtss2usi32:
2317 case X86::BI__builtin_ia32_vcvtss2usi64:
2318 ArgNum = 1;
2319 HasRC = true;
2320 break;
Craig Topper8e066312016-11-07 07:01:09 +00002321 case X86::BI__builtin_ia32_cvtsi2sd64:
2322 case X86::BI__builtin_ia32_cvtsi2ss32:
2323 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00002324 case X86::BI__builtin_ia32_cvtusi2sd64:
2325 case X86::BI__builtin_ia32_cvtusi2ss32:
2326 case X86::BI__builtin_ia32_cvtusi2ss64:
2327 ArgNum = 2;
2328 HasRC = true;
2329 break;
2330 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
2331 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
2332 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2333 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2334 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2335 case X86::BI__builtin_ia32_cvtps2qq512_mask:
2336 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2337 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2338 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2339 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2340 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002341 case X86::BI__builtin_ia32_sqrtpd512_mask:
2342 case X86::BI__builtin_ia32_sqrtps512_mask:
Gabor Buella70d8d512018-05-30 15:27:49 +00002343 case X86::BI__builtin_ia32_vfmaddpd512:
2344 case X86::BI__builtin_ia32_vfmaddps512:
2345 case X86::BI__builtin_ia32_vfmaddsubpd512:
2346 case X86::BI__builtin_ia32_vfmaddsubps512:
Craig Topper7609f1c2016-10-01 21:03:50 +00002347 ArgNum = 3;
2348 HasRC = true;
2349 break;
2350 case X86::BI__builtin_ia32_addpd512_mask:
2351 case X86::BI__builtin_ia32_addps512_mask:
2352 case X86::BI__builtin_ia32_divpd512_mask:
2353 case X86::BI__builtin_ia32_divps512_mask:
2354 case X86::BI__builtin_ia32_mulpd512_mask:
2355 case X86::BI__builtin_ia32_mulps512_mask:
2356 case X86::BI__builtin_ia32_subpd512_mask:
2357 case X86::BI__builtin_ia32_subps512_mask:
2358 case X86::BI__builtin_ia32_addss_round_mask:
2359 case X86::BI__builtin_ia32_addsd_round_mask:
2360 case X86::BI__builtin_ia32_divss_round_mask:
2361 case X86::BI__builtin_ia32_divsd_round_mask:
2362 case X86::BI__builtin_ia32_mulss_round_mask:
2363 case X86::BI__builtin_ia32_mulsd_round_mask:
2364 case X86::BI__builtin_ia32_subss_round_mask:
2365 case X86::BI__builtin_ia32_subsd_round_mask:
2366 case X86::BI__builtin_ia32_scalefpd512_mask:
2367 case X86::BI__builtin_ia32_scalefps512_mask:
2368 case X86::BI__builtin_ia32_scalefsd_round_mask:
2369 case X86::BI__builtin_ia32_scalefss_round_mask:
2370 case X86::BI__builtin_ia32_getmantpd512_mask:
2371 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002372 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2373 case X86::BI__builtin_ia32_sqrtsd_round_mask:
2374 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002375 case X86::BI__builtin_ia32_vfmaddsd3_mask:
2376 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2377 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2378 case X86::BI__builtin_ia32_vfmaddss3_mask:
2379 case X86::BI__builtin_ia32_vfmaddss3_maskz:
2380 case X86::BI__builtin_ia32_vfmaddss3_mask3:
2381 ArgNum = 4;
2382 HasRC = true;
2383 break;
2384 case X86::BI__builtin_ia32_getmantsd_round_mask:
2385 case X86::BI__builtin_ia32_getmantss_round_mask:
2386 ArgNum = 5;
2387 HasRC = true;
2388 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00002389 }
2390
2391 llvm::APSInt Result;
2392
2393 // We can't check the value of a dependent argument.
2394 Expr *Arg = TheCall->getArg(ArgNum);
2395 if (Arg->isTypeDependent() || Arg->isValueDependent())
2396 return false;
2397
2398 // Check constant-ness first.
2399 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2400 return true;
2401
2402 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2403 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2404 // combined with ROUND_NO_EXC.
2405 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2406 Result == 8/*ROUND_NO_EXC*/ ||
2407 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2408 return false;
2409
2410 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2411 << Arg->getSourceRange();
2412}
2413
Craig Topperdf5beb22017-03-13 17:16:50 +00002414// Check if the gather/scatter scale is legal.
2415bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2416 CallExpr *TheCall) {
2417 unsigned ArgNum = 0;
2418 switch (BuiltinID) {
2419 default:
2420 return false;
2421 case X86::BI__builtin_ia32_gatherpfdpd:
2422 case X86::BI__builtin_ia32_gatherpfdps:
2423 case X86::BI__builtin_ia32_gatherpfqpd:
2424 case X86::BI__builtin_ia32_gatherpfqps:
2425 case X86::BI__builtin_ia32_scatterpfdpd:
2426 case X86::BI__builtin_ia32_scatterpfdps:
2427 case X86::BI__builtin_ia32_scatterpfqpd:
2428 case X86::BI__builtin_ia32_scatterpfqps:
2429 ArgNum = 3;
2430 break;
2431 case X86::BI__builtin_ia32_gatherd_pd:
2432 case X86::BI__builtin_ia32_gatherd_pd256:
2433 case X86::BI__builtin_ia32_gatherq_pd:
2434 case X86::BI__builtin_ia32_gatherq_pd256:
2435 case X86::BI__builtin_ia32_gatherd_ps:
2436 case X86::BI__builtin_ia32_gatherd_ps256:
2437 case X86::BI__builtin_ia32_gatherq_ps:
2438 case X86::BI__builtin_ia32_gatherq_ps256:
2439 case X86::BI__builtin_ia32_gatherd_q:
2440 case X86::BI__builtin_ia32_gatherd_q256:
2441 case X86::BI__builtin_ia32_gatherq_q:
2442 case X86::BI__builtin_ia32_gatherq_q256:
2443 case X86::BI__builtin_ia32_gatherd_d:
2444 case X86::BI__builtin_ia32_gatherd_d256:
2445 case X86::BI__builtin_ia32_gatherq_d:
2446 case X86::BI__builtin_ia32_gatherq_d256:
2447 case X86::BI__builtin_ia32_gather3div2df:
2448 case X86::BI__builtin_ia32_gather3div2di:
2449 case X86::BI__builtin_ia32_gather3div4df:
2450 case X86::BI__builtin_ia32_gather3div4di:
2451 case X86::BI__builtin_ia32_gather3div4sf:
2452 case X86::BI__builtin_ia32_gather3div4si:
2453 case X86::BI__builtin_ia32_gather3div8sf:
2454 case X86::BI__builtin_ia32_gather3div8si:
2455 case X86::BI__builtin_ia32_gather3siv2df:
2456 case X86::BI__builtin_ia32_gather3siv2di:
2457 case X86::BI__builtin_ia32_gather3siv4df:
2458 case X86::BI__builtin_ia32_gather3siv4di:
2459 case X86::BI__builtin_ia32_gather3siv4sf:
2460 case X86::BI__builtin_ia32_gather3siv4si:
2461 case X86::BI__builtin_ia32_gather3siv8sf:
2462 case X86::BI__builtin_ia32_gather3siv8si:
2463 case X86::BI__builtin_ia32_gathersiv8df:
2464 case X86::BI__builtin_ia32_gathersiv16sf:
2465 case X86::BI__builtin_ia32_gatherdiv8df:
2466 case X86::BI__builtin_ia32_gatherdiv16sf:
2467 case X86::BI__builtin_ia32_gathersiv8di:
2468 case X86::BI__builtin_ia32_gathersiv16si:
2469 case X86::BI__builtin_ia32_gatherdiv8di:
2470 case X86::BI__builtin_ia32_gatherdiv16si:
2471 case X86::BI__builtin_ia32_scatterdiv2df:
2472 case X86::BI__builtin_ia32_scatterdiv2di:
2473 case X86::BI__builtin_ia32_scatterdiv4df:
2474 case X86::BI__builtin_ia32_scatterdiv4di:
2475 case X86::BI__builtin_ia32_scatterdiv4sf:
2476 case X86::BI__builtin_ia32_scatterdiv4si:
2477 case X86::BI__builtin_ia32_scatterdiv8sf:
2478 case X86::BI__builtin_ia32_scatterdiv8si:
2479 case X86::BI__builtin_ia32_scattersiv2df:
2480 case X86::BI__builtin_ia32_scattersiv2di:
2481 case X86::BI__builtin_ia32_scattersiv4df:
2482 case X86::BI__builtin_ia32_scattersiv4di:
2483 case X86::BI__builtin_ia32_scattersiv4sf:
2484 case X86::BI__builtin_ia32_scattersiv4si:
2485 case X86::BI__builtin_ia32_scattersiv8sf:
2486 case X86::BI__builtin_ia32_scattersiv8si:
2487 case X86::BI__builtin_ia32_scattersiv8df:
2488 case X86::BI__builtin_ia32_scattersiv16sf:
2489 case X86::BI__builtin_ia32_scatterdiv8df:
2490 case X86::BI__builtin_ia32_scatterdiv16sf:
2491 case X86::BI__builtin_ia32_scattersiv8di:
2492 case X86::BI__builtin_ia32_scattersiv16si:
2493 case X86::BI__builtin_ia32_scatterdiv8di:
2494 case X86::BI__builtin_ia32_scatterdiv16si:
2495 ArgNum = 4;
2496 break;
2497 }
2498
2499 llvm::APSInt Result;
2500
2501 // We can't check the value of a dependent argument.
2502 Expr *Arg = TheCall->getArg(ArgNum);
2503 if (Arg->isTypeDependent() || Arg->isValueDependent())
2504 return false;
2505
2506 // Check constant-ness first.
2507 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2508 return true;
2509
2510 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2511 return false;
2512
2513 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2514 << Arg->getSourceRange();
2515}
2516
Craig Topper51738f82018-04-26 20:14:46 +00002517static bool isX86_32Builtin(unsigned BuiltinID) {
2518 // These builtins only work on x86-32 targets.
2519 switch (BuiltinID) {
2520 case X86::BI__builtin_ia32_readeflags_u32:
2521 case X86::BI__builtin_ia32_writeeflags_u32:
2522 return true;
2523 }
2524
2525 return false;
2526}
2527
Craig Topperf0ddc892016-09-23 04:48:27 +00002528bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2529 if (BuiltinID == X86::BI__builtin_cpu_supports)
2530 return SemaBuiltinCpuSupports(*this, TheCall);
2531
Craig Topper699ae0c2017-08-10 20:28:30 +00002532 if (BuiltinID == X86::BI__builtin_cpu_is)
2533 return SemaBuiltinCpuIs(*this, TheCall);
2534
Craig Topper51738f82018-04-26 20:14:46 +00002535 // Check for 32-bit only builtins on a 64-bit target.
2536 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2537 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
2538 return Diag(TheCall->getCallee()->getLocStart(),
2539 diag::err_32_bit_builtin_64_bit_tgt);
2540
Craig Toppera7e253e2016-09-23 04:48:31 +00002541 // If the intrinsic has rounding or SAE make sure its valid.
2542 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2543 return true;
2544
Craig Topperdf5beb22017-03-13 17:16:50 +00002545 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2546 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2547 return true;
2548
Craig Topperf0ddc892016-09-23 04:48:27 +00002549 // For intrinsics which take an immediate value as part of the instruction,
2550 // range check them here.
2551 int i = 0, l = 0, u = 0;
2552 switch (BuiltinID) {
2553 default:
2554 return false;
Craig Topper11899b02018-06-05 21:54:35 +00002555 case X86::BI__builtin_ia32_vec_ext_v2si:
Craig Topperf3914b72018-06-06 00:24:55 +00002556 case X86::BI__builtin_ia32_vec_ext_v2di:
Craig Topper11899b02018-06-05 21:54:35 +00002557 i = 1; l = 0; u = 1;
2558 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002559 case X86::BI__builtin_ia32_vec_set_v2di:
2560 i = 2; l = 0; u = 1;
2561 break;
Craig Topper11899b02018-06-05 21:54:35 +00002562 case X86::BI__builtin_ia32_vec_ext_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00002563 case X86::BI__builtin_ia32_vec_ext_v4si:
2564 case X86::BI__builtin_ia32_vec_ext_v4sf:
2565 case X86::BI__builtin_ia32_vec_ext_v4di:
Craig Topper11899b02018-06-05 21:54:35 +00002566 i = 1; l = 0; u = 3;
2567 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002568 case X86::BI_mm_prefetch:
2569 case X86::BI__builtin_ia32_vec_ext_v8hi:
2570 case X86::BI__builtin_ia32_vec_ext_v8si:
2571 i = 1; l = 0; u = 7;
2572 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002573 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper11899b02018-06-05 21:54:35 +00002574 case X86::BI__builtin_ia32_vec_set_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00002575 case X86::BI__builtin_ia32_vec_set_v4si:
2576 case X86::BI__builtin_ia32_vec_set_v4di:
Craig Topper39c87102016-05-18 03:18:12 +00002577 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002578 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002579 case X86::BI__builtin_ia32_vpermil2pd:
2580 case X86::BI__builtin_ia32_vpermil2pd256:
2581 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002582 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002583 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002584 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002585 case X86::BI__builtin_ia32_cmpb128_mask:
2586 case X86::BI__builtin_ia32_cmpw128_mask:
2587 case X86::BI__builtin_ia32_cmpd128_mask:
2588 case X86::BI__builtin_ia32_cmpq128_mask:
2589 case X86::BI__builtin_ia32_cmpb256_mask:
2590 case X86::BI__builtin_ia32_cmpw256_mask:
2591 case X86::BI__builtin_ia32_cmpd256_mask:
2592 case X86::BI__builtin_ia32_cmpq256_mask:
2593 case X86::BI__builtin_ia32_cmpb512_mask:
2594 case X86::BI__builtin_ia32_cmpw512_mask:
2595 case X86::BI__builtin_ia32_cmpd512_mask:
2596 case X86::BI__builtin_ia32_cmpq512_mask:
2597 case X86::BI__builtin_ia32_ucmpb128_mask:
2598 case X86::BI__builtin_ia32_ucmpw128_mask:
2599 case X86::BI__builtin_ia32_ucmpd128_mask:
2600 case X86::BI__builtin_ia32_ucmpq128_mask:
2601 case X86::BI__builtin_ia32_ucmpb256_mask:
2602 case X86::BI__builtin_ia32_ucmpw256_mask:
2603 case X86::BI__builtin_ia32_ucmpd256_mask:
2604 case X86::BI__builtin_ia32_ucmpq256_mask:
2605 case X86::BI__builtin_ia32_ucmpb512_mask:
2606 case X86::BI__builtin_ia32_ucmpw512_mask:
2607 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002608 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002609 case X86::BI__builtin_ia32_vpcomub:
2610 case X86::BI__builtin_ia32_vpcomuw:
2611 case X86::BI__builtin_ia32_vpcomud:
2612 case X86::BI__builtin_ia32_vpcomuq:
2613 case X86::BI__builtin_ia32_vpcomb:
2614 case X86::BI__builtin_ia32_vpcomw:
2615 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002616 case X86::BI__builtin_ia32_vpcomq:
Craig Topperf3914b72018-06-06 00:24:55 +00002617 case X86::BI__builtin_ia32_vec_set_v8hi:
2618 case X86::BI__builtin_ia32_vec_set_v8si:
Craig Topper39c87102016-05-18 03:18:12 +00002619 i = 2; l = 0; u = 7;
2620 break;
2621 case X86::BI__builtin_ia32_roundps:
2622 case X86::BI__builtin_ia32_roundpd:
2623 case X86::BI__builtin_ia32_roundps256:
2624 case X86::BI__builtin_ia32_roundpd256:
Craig Topperf3914b72018-06-06 00:24:55 +00002625 case X86::BI__builtin_ia32_vec_ext_v16qi:
2626 case X86::BI__builtin_ia32_vec_ext_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00002627 i = 1; l = 0; u = 15;
2628 break;
2629 case X86::BI__builtin_ia32_roundss:
2630 case X86::BI__builtin_ia32_roundsd:
2631 case X86::BI__builtin_ia32_rangepd128_mask:
2632 case X86::BI__builtin_ia32_rangepd256_mask:
2633 case X86::BI__builtin_ia32_rangepd512_mask:
2634 case X86::BI__builtin_ia32_rangeps128_mask:
2635 case X86::BI__builtin_ia32_rangeps256_mask:
2636 case X86::BI__builtin_ia32_rangeps512_mask:
2637 case X86::BI__builtin_ia32_getmantsd_round_mask:
2638 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00002639 case X86::BI__builtin_ia32_vec_set_v16qi:
2640 case X86::BI__builtin_ia32_vec_set_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00002641 i = 2; l = 0; u = 15;
2642 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002643 case X86::BI__builtin_ia32_vec_ext_v32qi:
2644 i = 1; l = 0; u = 31;
2645 break;
Craig Topper39c87102016-05-18 03:18:12 +00002646 case X86::BI__builtin_ia32_cmpps:
2647 case X86::BI__builtin_ia32_cmpss:
2648 case X86::BI__builtin_ia32_cmppd:
2649 case X86::BI__builtin_ia32_cmpsd:
2650 case X86::BI__builtin_ia32_cmpps256:
2651 case X86::BI__builtin_ia32_cmppd256:
2652 case X86::BI__builtin_ia32_cmpps128_mask:
2653 case X86::BI__builtin_ia32_cmppd128_mask:
2654 case X86::BI__builtin_ia32_cmpps256_mask:
2655 case X86::BI__builtin_ia32_cmppd256_mask:
2656 case X86::BI__builtin_ia32_cmpps512_mask:
2657 case X86::BI__builtin_ia32_cmppd512_mask:
2658 case X86::BI__builtin_ia32_cmpsd_mask:
2659 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00002660 case X86::BI__builtin_ia32_vec_set_v32qi:
Craig Topper39c87102016-05-18 03:18:12 +00002661 i = 2; l = 0; u = 31;
2662 break;
Craig Topper39c87102016-05-18 03:18:12 +00002663 case X86::BI__builtin_ia32_vcvtps2ph:
Craig Topper23a30222017-11-08 04:54:26 +00002664 case X86::BI__builtin_ia32_vcvtps2ph_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002665 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper23a30222017-11-08 04:54:26 +00002666 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2667 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002668 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2669 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2670 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2671 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2672 case X86::BI__builtin_ia32_rndscaleps_mask:
2673 case X86::BI__builtin_ia32_rndscalepd_mask:
2674 case X86::BI__builtin_ia32_reducepd128_mask:
2675 case X86::BI__builtin_ia32_reducepd256_mask:
2676 case X86::BI__builtin_ia32_reducepd512_mask:
2677 case X86::BI__builtin_ia32_reduceps128_mask:
2678 case X86::BI__builtin_ia32_reduceps256_mask:
2679 case X86::BI__builtin_ia32_reduceps512_mask:
2680 case X86::BI__builtin_ia32_prold512_mask:
2681 case X86::BI__builtin_ia32_prolq512_mask:
2682 case X86::BI__builtin_ia32_prold128_mask:
2683 case X86::BI__builtin_ia32_prold256_mask:
2684 case X86::BI__builtin_ia32_prolq128_mask:
2685 case X86::BI__builtin_ia32_prolq256_mask:
2686 case X86::BI__builtin_ia32_prord128_mask:
2687 case X86::BI__builtin_ia32_prord256_mask:
2688 case X86::BI__builtin_ia32_prorq128_mask:
2689 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002690 case X86::BI__builtin_ia32_fpclasspd128_mask:
2691 case X86::BI__builtin_ia32_fpclasspd256_mask:
2692 case X86::BI__builtin_ia32_fpclassps128_mask:
2693 case X86::BI__builtin_ia32_fpclassps256_mask:
2694 case X86::BI__builtin_ia32_fpclassps512_mask:
2695 case X86::BI__builtin_ia32_fpclasspd512_mask:
2696 case X86::BI__builtin_ia32_fpclasssd_mask:
2697 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002698 i = 1; l = 0; u = 255;
2699 break;
Craig Topper39c87102016-05-18 03:18:12 +00002700 case X86::BI__builtin_ia32_palignr128:
2701 case X86::BI__builtin_ia32_palignr256:
Craig Topper8e3689c2018-05-22 20:48:24 +00002702 case X86::BI__builtin_ia32_palignr512:
Craig Topper39c87102016-05-18 03:18:12 +00002703 case X86::BI__builtin_ia32_vcomisd:
2704 case X86::BI__builtin_ia32_vcomiss:
Craig Topper39c87102016-05-18 03:18:12 +00002705 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2706 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2707 case X86::BI__builtin_ia32_dbpsadbw512_mask:
Craig Topper91926432018-01-11 01:38:02 +00002708 case X86::BI__builtin_ia32_vpshldd128_mask:
2709 case X86::BI__builtin_ia32_vpshldd256_mask:
2710 case X86::BI__builtin_ia32_vpshldd512_mask:
2711 case X86::BI__builtin_ia32_vpshldq128_mask:
2712 case X86::BI__builtin_ia32_vpshldq256_mask:
2713 case X86::BI__builtin_ia32_vpshldq512_mask:
2714 case X86::BI__builtin_ia32_vpshldw128_mask:
2715 case X86::BI__builtin_ia32_vpshldw256_mask:
2716 case X86::BI__builtin_ia32_vpshldw512_mask:
2717 case X86::BI__builtin_ia32_vpshrdd128_mask:
2718 case X86::BI__builtin_ia32_vpshrdd256_mask:
2719 case X86::BI__builtin_ia32_vpshrdd512_mask:
2720 case X86::BI__builtin_ia32_vpshrdq128_mask:
2721 case X86::BI__builtin_ia32_vpshrdq256_mask:
2722 case X86::BI__builtin_ia32_vpshrdq512_mask:
2723 case X86::BI__builtin_ia32_vpshrdw128_mask:
2724 case X86::BI__builtin_ia32_vpshrdw256_mask:
2725 case X86::BI__builtin_ia32_vpshrdw512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002726 i = 2; l = 0; u = 255;
2727 break;
2728 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2729 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2730 case X86::BI__builtin_ia32_fixupimmps512_mask:
2731 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2732 case X86::BI__builtin_ia32_fixupimmsd_mask:
2733 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2734 case X86::BI__builtin_ia32_fixupimmss_mask:
2735 case X86::BI__builtin_ia32_fixupimmss_maskz:
2736 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2737 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2738 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2739 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2740 case X86::BI__builtin_ia32_fixupimmps128_mask:
2741 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2742 case X86::BI__builtin_ia32_fixupimmps256_mask:
2743 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2744 case X86::BI__builtin_ia32_pternlogd512_mask:
2745 case X86::BI__builtin_ia32_pternlogd512_maskz:
2746 case X86::BI__builtin_ia32_pternlogq512_mask:
2747 case X86::BI__builtin_ia32_pternlogq512_maskz:
2748 case X86::BI__builtin_ia32_pternlogd128_mask:
2749 case X86::BI__builtin_ia32_pternlogd128_maskz:
2750 case X86::BI__builtin_ia32_pternlogd256_mask:
2751 case X86::BI__builtin_ia32_pternlogd256_maskz:
2752 case X86::BI__builtin_ia32_pternlogq128_mask:
2753 case X86::BI__builtin_ia32_pternlogq128_maskz:
2754 case X86::BI__builtin_ia32_pternlogq256_mask:
2755 case X86::BI__builtin_ia32_pternlogq256_maskz:
2756 i = 3; l = 0; u = 255;
2757 break;
Craig Topper9625db02017-03-12 22:19:10 +00002758 case X86::BI__builtin_ia32_gatherpfdpd:
2759 case X86::BI__builtin_ia32_gatherpfdps:
2760 case X86::BI__builtin_ia32_gatherpfqpd:
2761 case X86::BI__builtin_ia32_gatherpfqps:
2762 case X86::BI__builtin_ia32_scatterpfdpd:
2763 case X86::BI__builtin_ia32_scatterpfdps:
2764 case X86::BI__builtin_ia32_scatterpfqpd:
2765 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00002766 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00002767 break;
Craig Topper39c87102016-05-18 03:18:12 +00002768 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2769 case X86::BI__builtin_ia32_rndscaless_round_mask:
2770 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002771 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002772 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002773 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002774}
2775
Richard Smith55ce3522012-06-25 20:30:08 +00002776/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2777/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2778/// Returns true when the format fits the function and the FormatStringInfo has
2779/// been populated.
2780bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2781 FormatStringInfo *FSI) {
2782 FSI->HasVAListArg = Format->getFirstArg() == 0;
2783 FSI->FormatIdx = Format->getFormatIdx() - 1;
2784 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002785
Richard Smith55ce3522012-06-25 20:30:08 +00002786 // The way the format attribute works in GCC, the implicit this argument
2787 // of member functions is counted. However, it doesn't appear in our own
2788 // lists, so decrement format_idx in that case.
2789 if (IsCXXMember) {
2790 if(FSI->FormatIdx == 0)
2791 return false;
2792 --FSI->FormatIdx;
2793 if (FSI->FirstDataArg != 0)
2794 --FSI->FirstDataArg;
2795 }
2796 return true;
2797}
Mike Stump11289f42009-09-09 15:08:12 +00002798
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002799/// Checks if a the given expression evaluates to null.
2800///
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002801/// Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002802static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002803 // If the expression has non-null type, it doesn't evaluate to null.
2804 if (auto nullability
2805 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2806 if (*nullability == NullabilityKind::NonNull)
2807 return false;
2808 }
2809
Ted Kremeneka146db32014-01-17 06:24:47 +00002810 // As a special case, transparent unions initialized with zero are
2811 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002812 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002813 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2814 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002815 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002816 if (const InitListExpr *ILE =
2817 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002818 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002819 }
2820
2821 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002822 return (!Expr->isValueDependent() &&
2823 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2824 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002825}
2826
2827static void CheckNonNullArgument(Sema &S,
2828 const Expr *ArgExpr,
2829 SourceLocation CallSiteLoc) {
2830 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002831 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2832 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002833}
2834
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002835bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2836 FormatStringInfo FSI;
2837 if ((GetFormatStringType(Format) == FST_NSString) &&
2838 getFormatStringInfo(Format, false, &FSI)) {
2839 Idx = FSI.FormatIdx;
2840 return true;
2841 }
2842 return false;
2843}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002844
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002845/// Diagnose use of %s directive in an NSString which is being passed
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002846/// as formatting string to formatting method.
2847static void
2848DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2849 const NamedDecl *FDecl,
2850 Expr **Args,
2851 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002852 unsigned Idx = 0;
2853 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002854 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2855 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002856 Idx = 2;
2857 Format = true;
2858 }
2859 else
2860 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2861 if (S.GetFormatNSStringIdx(I, Idx)) {
2862 Format = true;
2863 break;
2864 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002865 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002866 if (!Format || NumArgs <= Idx)
2867 return;
2868 const Expr *FormatExpr = Args[Idx];
2869 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2870 FormatExpr = CSCE->getSubExpr();
2871 const StringLiteral *FormatString;
2872 if (const ObjCStringLiteral *OSL =
2873 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2874 FormatString = OSL->getString();
2875 else
2876 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2877 if (!FormatString)
2878 return;
2879 if (S.FormatStringHasSArg(FormatString)) {
2880 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2881 << "%s" << 1 << 1;
2882 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2883 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002884 }
2885}
2886
Douglas Gregorb4866e82015-06-19 18:13:19 +00002887/// Determine whether the given type has a non-null nullability annotation.
2888static bool isNonNullType(ASTContext &ctx, QualType type) {
2889 if (auto nullability = type->getNullability(ctx))
2890 return *nullability == NullabilityKind::NonNull;
2891
2892 return false;
2893}
2894
Ted Kremenek2bc73332014-01-17 06:24:43 +00002895static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002896 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002897 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002898 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002899 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002900 assert((FDecl || Proto) && "Need a function declaration or prototype");
2901
Ted Kremenek9aedc152014-01-17 06:24:56 +00002902 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002903 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002904 if (FDecl) {
2905 // Handle the nonnull attribute on the function/method declaration itself.
2906 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2907 if (!NonNull->args_size()) {
2908 // Easy case: all pointer arguments are nonnull.
2909 for (const auto *Arg : Args)
2910 if (S.isValidPointerAttrType(Arg->getType()))
2911 CheckNonNullArgument(S, Arg, CallSiteLoc);
2912 return;
2913 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002914
Joel E. Denny81508102018-03-13 14:51:22 +00002915 for (const ParamIdx &Idx : NonNull->args()) {
2916 unsigned IdxAST = Idx.getASTIndex();
2917 if (IdxAST >= Args.size())
Douglas Gregorb4866e82015-06-19 18:13:19 +00002918 continue;
2919 if (NonNullArgs.empty())
2920 NonNullArgs.resize(Args.size());
Joel E. Denny81508102018-03-13 14:51:22 +00002921 NonNullArgs.set(IdxAST);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002922 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002923 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002924 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002925
Douglas Gregorb4866e82015-06-19 18:13:19 +00002926 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2927 // Handle the nonnull attribute on the parameters of the
2928 // function/method.
2929 ArrayRef<ParmVarDecl*> parms;
2930 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2931 parms = FD->parameters();
2932 else
2933 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2934
2935 unsigned ParamIndex = 0;
2936 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2937 I != E; ++I, ++ParamIndex) {
2938 const ParmVarDecl *PVD = *I;
2939 if (PVD->hasAttr<NonNullAttr>() ||
2940 isNonNullType(S.Context, PVD->getType())) {
2941 if (NonNullArgs.empty())
2942 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002943
Douglas Gregorb4866e82015-06-19 18:13:19 +00002944 NonNullArgs.set(ParamIndex);
2945 }
2946 }
2947 } else {
2948 // If we have a non-function, non-method declaration but no
2949 // function prototype, try to dig out the function prototype.
2950 if (!Proto) {
2951 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2952 QualType type = VD->getType().getNonReferenceType();
2953 if (auto pointerType = type->getAs<PointerType>())
2954 type = pointerType->getPointeeType();
2955 else if (auto blockType = type->getAs<BlockPointerType>())
2956 type = blockType->getPointeeType();
2957 // FIXME: data member pointers?
2958
2959 // Dig out the function prototype, if there is one.
2960 Proto = type->getAs<FunctionProtoType>();
2961 }
2962 }
2963
2964 // Fill in non-null argument information from the nullability
2965 // information on the parameter types (if we have them).
2966 if (Proto) {
2967 unsigned Index = 0;
2968 for (auto paramType : Proto->getParamTypes()) {
2969 if (isNonNullType(S.Context, paramType)) {
2970 if (NonNullArgs.empty())
2971 NonNullArgs.resize(Args.size());
2972
2973 NonNullArgs.set(Index);
2974 }
2975
2976 ++Index;
2977 }
2978 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002979 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002980
Douglas Gregorb4866e82015-06-19 18:13:19 +00002981 // Check for non-null arguments.
2982 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2983 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002984 if (NonNullArgs[ArgIndex])
2985 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002986 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002987}
2988
Richard Smith55ce3522012-06-25 20:30:08 +00002989/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00002990/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2991/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002992void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00002993 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2994 bool IsMemberFunction, SourceLocation Loc,
2995 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002996 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002997 if (CurContext->isDependentContext())
2998 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002999
Ted Kremenekb8176da2010-09-09 04:33:05 +00003000 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00003001 llvm::SmallBitVector CheckedVarArgs;
3002 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003003 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00003004 // Only create vector if there are format attributes.
3005 CheckedVarArgs.resize(Args.size());
3006
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003007 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00003008 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00003009 }
Richard Smithd7293d72013-08-05 18:49:43 +00003010 }
Richard Smith55ce3522012-06-25 20:30:08 +00003011
3012 // Refuse POD arguments that weren't caught by the format string
3013 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00003014 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3015 if (CallType != VariadicDoesNotApply &&
3016 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00003017 unsigned NumParams = Proto ? Proto->getNumParams()
3018 : FDecl && isa<FunctionDecl>(FDecl)
3019 ? cast<FunctionDecl>(FDecl)->getNumParams()
3020 : FDecl && isa<ObjCMethodDecl>(FDecl)
3021 ? cast<ObjCMethodDecl>(FDecl)->param_size()
3022 : 0;
3023
Alp Toker9cacbab2014-01-20 20:26:09 +00003024 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00003025 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00003026 if (const Expr *Arg = Args[ArgIdx]) {
3027 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3028 checkVariadicArgument(Arg, CallType);
3029 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00003030 }
Richard Smithd7293d72013-08-05 18:49:43 +00003031 }
Mike Stump11289f42009-09-09 15:08:12 +00003032
Douglas Gregorb4866e82015-06-19 18:13:19 +00003033 if (FDecl || Proto) {
3034 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00003035
Richard Trieu41bc0992013-06-22 00:20:41 +00003036 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00003037 if (FDecl) {
3038 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +00003039 CheckArgumentWithTypeTag(I, Args, Loc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00003040 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00003041 }
George Burgess IVce6284b2017-01-28 02:19:40 +00003042
3043 if (FD)
3044 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00003045}
3046
3047/// CheckConstructorCall - Check a constructor call for correctness and safety
3048/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003049void Sema::CheckConstructorCall(FunctionDecl *FDecl,
3050 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003051 const FunctionProtoType *Proto,
3052 SourceLocation Loc) {
3053 VariadicCallType CallType =
3054 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00003055 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
3056 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00003057}
3058
3059/// CheckFunctionCall - Check a direct function call for various correctness
3060/// and safety properties not strictly enforced by the C type system.
3061bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
3062 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00003063 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
3064 isa<CXXMethodDecl>(FDecl);
3065 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
3066 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00003067 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
3068 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00003069 Expr** Args = TheCall->getArgs();
3070 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00003071
3072 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00003073 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00003074 // If this is a call to a member operator, hide the first argument
3075 // from checkCall.
3076 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00003077 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00003078 ++Args;
3079 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00003080 } else if (IsMemberFunction)
3081 ImplicitThis =
3082 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
3083
3084 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00003085 IsMemberFunction, TheCall->getRParenLoc(),
3086 TheCall->getCallee()->getSourceRange(), CallType);
3087
3088 IdentifierInfo *FnInfo = FDecl->getIdentifier();
3089 // None of the checks below are needed for functions that don't have
3090 // simple names (e.g., C++ conversion functions).
3091 if (!FnInfo)
3092 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003093
Richard Trieua7f30b12016-12-06 01:42:28 +00003094 CheckAbsoluteValueFunction(TheCall, FDecl);
3095 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00003096
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003097 if (getLangOpts().ObjC1)
3098 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003099
Anna Zaks22122702012-01-17 00:37:07 +00003100 unsigned CMId = FDecl->getMemoryFunctionKind();
3101 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00003102 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00003103
Anna Zaks201d4892012-01-13 21:52:01 +00003104 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00003105 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00003106 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00003107 else if (CMId == Builtin::BIstrncat)
3108 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00003109 else
Anna Zaks22122702012-01-17 00:37:07 +00003110 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003111
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003112 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00003113}
3114
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003115bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00003116 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00003117 VariadicCallType CallType =
3118 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003119
George Burgess IVce6284b2017-01-28 02:19:40 +00003120 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
3121 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00003122 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003123
3124 return false;
3125}
3126
Richard Trieu664c4c62013-06-20 21:03:13 +00003127bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
3128 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00003129 QualType Ty;
3130 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00003131 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00003132 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00003133 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00003134 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003135 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003136
Douglas Gregorb4866e82015-06-19 18:13:19 +00003137 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
3138 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003139 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003140
Richard Trieu664c4c62013-06-20 21:03:13 +00003141 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00003142 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00003143 CallType = VariadicDoesNotApply;
3144 } else if (Ty->isBlockPointerType()) {
3145 CallType = VariadicBlock;
3146 } else { // Ty->isFunctionPointerType()
3147 CallType = VariadicFunction;
3148 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003149
George Burgess IVce6284b2017-01-28 02:19:40 +00003150 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00003151 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
3152 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00003153 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00003154
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003155 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00003156}
3157
Richard Trieu41bc0992013-06-22 00:20:41 +00003158/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
3159/// such as function pointers returned from functions.
3160bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003161 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00003162 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00003163 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00003164 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00003165 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00003166 TheCall->getCallee()->getSourceRange(), CallType);
3167
3168 return false;
3169}
3170
Tim Northovere94a34c2014-03-11 10:49:14 +00003171static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00003172 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00003173 return false;
3174
JF Bastiendda2cb12016-04-18 18:01:49 +00003175 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00003176 switch (Op) {
3177 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00003178 case AtomicExpr::AO__opencl_atomic_init:
Tim Northovere94a34c2014-03-11 10:49:14 +00003179 llvm_unreachable("There is no ordering argument for an init");
3180
3181 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00003182 case AtomicExpr::AO__opencl_atomic_load:
Tim Northovere94a34c2014-03-11 10:49:14 +00003183 case AtomicExpr::AO__atomic_load_n:
3184 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00003185 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
3186 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00003187
3188 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00003189 case AtomicExpr::AO__opencl_atomic_store:
Tim Northovere94a34c2014-03-11 10:49:14 +00003190 case AtomicExpr::AO__atomic_store:
3191 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00003192 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
3193 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
3194 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00003195
3196 default:
3197 return true;
3198 }
3199}
3200
Richard Smithfeea8832012-04-12 05:08:17 +00003201ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
3202 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003203 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3204 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003205
Yaxun Liu39195062017-08-04 18:16:31 +00003206 // All the non-OpenCL operations take one of the following forms.
3207 // The OpenCL operations take the __c11 forms with one extra argument for
3208 // synchronization scope.
Richard Smithfeea8832012-04-12 05:08:17 +00003209 enum {
3210 // C __c11_atomic_init(A *, C)
3211 Init,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003212
Richard Smithfeea8832012-04-12 05:08:17 +00003213 // C __c11_atomic_load(A *, int)
3214 Load,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003215
Richard Smithfeea8832012-04-12 05:08:17 +00003216 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00003217 LoadCopy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003218
Eric Fiselier8d662442016-03-30 23:39:56 +00003219 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00003220 Copy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003221
Richard Smithfeea8832012-04-12 05:08:17 +00003222 // C __c11_atomic_add(A *, M, int)
3223 Arithmetic,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003224
Richard Smithfeea8832012-04-12 05:08:17 +00003225 // C __atomic_exchange_n(A *, CP, int)
3226 Xchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003227
Richard Smithfeea8832012-04-12 05:08:17 +00003228 // void __atomic_exchange(A *, C *, CP, int)
3229 GNUXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003230
Richard Smithfeea8832012-04-12 05:08:17 +00003231 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
3232 C11CmpXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003233
Richard Smithfeea8832012-04-12 05:08:17 +00003234 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
3235 GNUCmpXchg
3236 } Form = Init;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003237
Yaxun Liu39195062017-08-04 18:16:31 +00003238 const unsigned NumForm = GNUCmpXchg + 1;
Eric Fiselier8d662442016-03-30 23:39:56 +00003239 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
3240 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00003241 // where:
3242 // C is an appropriate type,
3243 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
3244 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
3245 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
3246 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003247
Yaxun Liu39195062017-08-04 18:16:31 +00003248 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
3249 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
3250 "need to update code for modified forms");
Gabor Horvath98bd0982015-03-16 09:59:54 +00003251 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
3252 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
3253 AtomicExpr::AO__atomic_load,
3254 "need to update code for modified C11 atomics");
Yaxun Liu39195062017-08-04 18:16:31 +00003255 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
3256 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
3257 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
3258 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
3259 IsOpenCL;
Richard Smithfeea8832012-04-12 05:08:17 +00003260 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
3261 Op == AtomicExpr::AO__atomic_store_n ||
3262 Op == AtomicExpr::AO__atomic_exchange_n ||
3263 Op == AtomicExpr::AO__atomic_compare_exchange_n;
3264 bool IsAddSub = false;
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003265 bool IsMinMax = false;
Richard Smithfeea8832012-04-12 05:08:17 +00003266
3267 switch (Op) {
3268 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00003269 case AtomicExpr::AO__opencl_atomic_init:
Richard Smithfeea8832012-04-12 05:08:17 +00003270 Form = Init;
3271 break;
3272
3273 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00003274 case AtomicExpr::AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00003275 case AtomicExpr::AO__atomic_load_n:
3276 Form = Load;
3277 break;
3278
Richard Smithfeea8832012-04-12 05:08:17 +00003279 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00003280 Form = LoadCopy;
3281 break;
3282
3283 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00003284 case AtomicExpr::AO__opencl_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00003285 case AtomicExpr::AO__atomic_store:
3286 case AtomicExpr::AO__atomic_store_n:
3287 Form = Copy;
3288 break;
3289
3290 case AtomicExpr::AO__c11_atomic_fetch_add:
3291 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00003292 case AtomicExpr::AO__opencl_atomic_fetch_add:
3293 case AtomicExpr::AO__opencl_atomic_fetch_sub:
3294 case AtomicExpr::AO__opencl_atomic_fetch_min:
3295 case AtomicExpr::AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00003296 case AtomicExpr::AO__atomic_fetch_add:
3297 case AtomicExpr::AO__atomic_fetch_sub:
3298 case AtomicExpr::AO__atomic_add_fetch:
3299 case AtomicExpr::AO__atomic_sub_fetch:
3300 IsAddSub = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00003301 LLVM_FALLTHROUGH;
Richard Smithfeea8832012-04-12 05:08:17 +00003302 case AtomicExpr::AO__c11_atomic_fetch_and:
3303 case AtomicExpr::AO__c11_atomic_fetch_or:
3304 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00003305 case AtomicExpr::AO__opencl_atomic_fetch_and:
3306 case AtomicExpr::AO__opencl_atomic_fetch_or:
3307 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Richard Smithfeea8832012-04-12 05:08:17 +00003308 case AtomicExpr::AO__atomic_fetch_and:
3309 case AtomicExpr::AO__atomic_fetch_or:
3310 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00003311 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00003312 case AtomicExpr::AO__atomic_and_fetch:
3313 case AtomicExpr::AO__atomic_or_fetch:
3314 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00003315 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00003316 Form = Arithmetic;
3317 break;
3318
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003319 case AtomicExpr::AO__atomic_fetch_min:
3320 case AtomicExpr::AO__atomic_fetch_max:
3321 IsMinMax = true;
3322 Form = Arithmetic;
3323 break;
3324
Richard Smithfeea8832012-04-12 05:08:17 +00003325 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00003326 case AtomicExpr::AO__opencl_atomic_exchange:
Richard Smithfeea8832012-04-12 05:08:17 +00003327 case AtomicExpr::AO__atomic_exchange_n:
3328 Form = Xchg;
3329 break;
3330
3331 case AtomicExpr::AO__atomic_exchange:
3332 Form = GNUXchg;
3333 break;
3334
3335 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3336 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +00003337 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3338 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00003339 Form = C11CmpXchg;
3340 break;
3341
3342 case AtomicExpr::AO__atomic_compare_exchange:
3343 case AtomicExpr::AO__atomic_compare_exchange_n:
3344 Form = GNUCmpXchg;
3345 break;
3346 }
3347
Yaxun Liu39195062017-08-04 18:16:31 +00003348 unsigned AdjustedNumArgs = NumArgs[Form];
3349 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3350 ++AdjustedNumArgs;
Richard Smithfeea8832012-04-12 05:08:17 +00003351 // Check we have the right number of arguments.
Yaxun Liu39195062017-08-04 18:16:31 +00003352 if (TheCall->getNumArgs() < AdjustedNumArgs) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003353 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003354 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003355 << TheCall->getCallee()->getSourceRange();
3356 return ExprError();
Yaxun Liu39195062017-08-04 18:16:31 +00003357 } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3358 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003359 diag::err_typecheck_call_too_many_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003360 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003361 << TheCall->getCallee()->getSourceRange();
3362 return ExprError();
3363 }
3364
Richard Smithfeea8832012-04-12 05:08:17 +00003365 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003366 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00003367 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3368 if (ConvertedPtr.isInvalid())
3369 return ExprError();
3370
3371 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003372 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3373 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00003374 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003375 << Ptr->getType() << Ptr->getSourceRange();
3376 return ExprError();
3377 }
3378
Richard Smithfeea8832012-04-12 05:08:17 +00003379 // For a __c11 builtin, this should be a pointer to an _Atomic type.
3380 QualType AtomTy = pointerType->getPointeeType(); // 'A'
3381 QualType ValType = AtomTy; // 'C'
3382 if (IsC11) {
3383 if (!AtomTy->isAtomicType()) {
3384 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3385 << Ptr->getType() << Ptr->getSourceRange();
3386 return ExprError();
3387 }
Yaxun Liu39195062017-08-04 18:16:31 +00003388 if (AtomTy.isConstQualified() ||
3389 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
Richard Smithe00921a2012-09-15 06:09:58 +00003390 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
Yaxun Liu39195062017-08-04 18:16:31 +00003391 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3392 << Ptr->getSourceRange();
Richard Smithe00921a2012-09-15 06:09:58 +00003393 return ExprError();
3394 }
Richard Smithfeea8832012-04-12 05:08:17 +00003395 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00003396 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00003397 if (ValType.isConstQualified()) {
3398 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3399 << Ptr->getType() << Ptr->getSourceRange();
3400 return ExprError();
3401 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003402 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003403
Richard Smithfeea8832012-04-12 05:08:17 +00003404 // For an arithmetic operation, the implied arithmetic must be well-formed.
3405 if (Form == Arithmetic) {
3406 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003407 if (IsAddSub && !ValType->isIntegerType()
3408 && !ValType->isPointerType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003409 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3410 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3411 return ExprError();
3412 }
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003413 if (IsMinMax) {
3414 const BuiltinType *BT = ValType->getAs<BuiltinType>();
3415 if (!BT || (BT->getKind() != BuiltinType::Int &&
3416 BT->getKind() != BuiltinType::UInt)) {
3417 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_int32_or_ptr);
3418 return ExprError();
3419 }
3420 }
3421 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003422 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3423 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3424 return ExprError();
3425 }
David Majnemere85cff82015-01-28 05:48:06 +00003426 if (IsC11 && ValType->isPointerType() &&
3427 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3428 diag::err_incomplete_type)) {
3429 return ExprError();
3430 }
Richard Smithfeea8832012-04-12 05:08:17 +00003431 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3432 // For __atomic_*_n operations, the value type must be a scalar integral or
3433 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003434 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00003435 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3436 return ExprError();
3437 }
3438
Eli Friedmanaa769812013-09-11 03:49:34 +00003439 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3440 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003441 // For GNU atomics, require a trivially-copyable type. This is not part of
3442 // the GNU atomics specification, but we enforce it for sanity.
3443 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003444 << Ptr->getType() << Ptr->getSourceRange();
3445 return ExprError();
3446 }
3447
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003448 switch (ValType.getObjCLifetime()) {
3449 case Qualifiers::OCL_None:
3450 case Qualifiers::OCL_ExplicitNone:
3451 // okay
3452 break;
3453
3454 case Qualifiers::OCL_Weak:
3455 case Qualifiers::OCL_Strong:
3456 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00003457 // FIXME: Can this happen? By this point, ValType should be known
3458 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003459 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3460 << ValType << Ptr->getSourceRange();
3461 return ExprError();
3462 }
3463
JF Bastien7f0a05a2018-05-25 00:07:09 +00003464 // All atomic operations have an overload which takes a pointer to a volatile
3465 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
3466 // into the result or the other operands. Similarly atomic_load takes a
3467 // pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00003468 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00003469 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003470 QualType ResultType = ValType;
Yaxun Liu39195062017-08-04 18:16:31 +00003471 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3472 Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003473 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00003474 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003475 ResultType = Context.BoolTy;
3476
Richard Smithfeea8832012-04-12 05:08:17 +00003477 // The type of a parameter passed 'by value'. In the GNU atomics, such
3478 // arguments are actually passed as pointers.
3479 QualType ByValType = ValType; // 'CP'
JF Bastien7f0a05a2018-05-25 00:07:09 +00003480 bool IsPassedByAddress = false;
3481 if (!IsC11 && !IsN) {
Richard Smithfeea8832012-04-12 05:08:17 +00003482 ByValType = Ptr->getType();
JF Bastien7f0a05a2018-05-25 00:07:09 +00003483 IsPassedByAddress = true;
3484 }
Richard Smithfeea8832012-04-12 05:08:17 +00003485
JF Bastien7f0a05a2018-05-25 00:07:09 +00003486 // The first argument's non-CV pointer type is used to deduce the type of
3487 // subsequent arguments, except for:
3488 // - weak flag (always converted to bool)
3489 // - memory order (always converted to int)
3490 // - scope (always converted to int)
3491 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003492 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00003493 if (i < NumVals[Form] + 1) {
3494 switch (i) {
JF Bastien7f0a05a2018-05-25 00:07:09 +00003495 case 0:
3496 // The first argument is always a pointer. It has a fixed type.
3497 // It is always dereferenced, a nullptr is undefined.
3498 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
3499 // Nothing else to do: we already know all we want about this pointer.
3500 continue;
Richard Smithfeea8832012-04-12 05:08:17 +00003501 case 1:
3502 // The second argument is the non-atomic operand. For arithmetic, this
3503 // is always passed by value, and for a compare_exchange it is always
3504 // passed by address. For the rest, GNU uses by-address and C11 uses
3505 // by-value.
3506 assert(Form != Load);
3507 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3508 Ty = ValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00003509 else if (Form == Copy || Form == Xchg) {
3510 if (IsPassedByAddress)
3511 // The value pointer is always dereferenced, a nullptr is undefined.
3512 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
Richard Smithfeea8832012-04-12 05:08:17 +00003513 Ty = ByValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00003514 } else if (Form == Arithmetic)
Richard Smithfeea8832012-04-12 05:08:17 +00003515 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003516 else {
3517 Expr *ValArg = TheCall->getArg(i);
JF Bastien7f0a05a2018-05-25 00:07:09 +00003518 // The value pointer is always dereferenced, a nullptr is undefined.
Alex Lorenz67522152016-11-23 16:57:03 +00003519 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Alexander Richardson6d989432017-10-15 18:48:14 +00003520 LangAS AS = LangAS::Default;
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003521 // Keep address space of non-atomic pointer type.
3522 if (const PointerType *PtrTy =
3523 ValArg->getType()->getAs<PointerType>()) {
3524 AS = PtrTy->getPointeeType().getAddressSpace();
3525 }
3526 Ty = Context.getPointerType(
3527 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3528 }
Richard Smithfeea8832012-04-12 05:08:17 +00003529 break;
3530 case 2:
JF Bastien7f0a05a2018-05-25 00:07:09 +00003531 // The third argument to compare_exchange / GNU exchange is the desired
JF Bastien7853d5f2018-05-25 17:36:49 +00003532 // value, either by-value (for the C11 and *_n variant) or as a pointer.
3533 if (IsPassedByAddress)
JF Bastien7f0a05a2018-05-25 00:07:09 +00003534 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
Richard Smithfeea8832012-04-12 05:08:17 +00003535 Ty = ByValType;
3536 break;
3537 case 3:
3538 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3539 Ty = Context.BoolTy;
3540 break;
3541 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003542 } else {
Yaxun Liu39195062017-08-04 18:16:31 +00003543 // The order(s) and scope are always converted to int.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003544 Ty = Context.IntTy;
3545 }
Richard Smithfeea8832012-04-12 05:08:17 +00003546
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003547 InitializedEntity Entity =
3548 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00003549 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003550 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3551 if (Arg.isInvalid())
3552 return true;
3553 TheCall->setArg(i, Arg.get());
3554 }
3555
Richard Smithfeea8832012-04-12 05:08:17 +00003556 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003557 SmallVector<Expr*, 5> SubExprs;
3558 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00003559 switch (Form) {
3560 case Init:
3561 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00003562 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003563 break;
3564 case Load:
3565 SubExprs.push_back(TheCall->getArg(1)); // Order
3566 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00003567 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00003568 case Copy:
3569 case Arithmetic:
3570 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003571 SubExprs.push_back(TheCall->getArg(2)); // Order
3572 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003573 break;
3574 case GNUXchg:
3575 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3576 SubExprs.push_back(TheCall->getArg(3)); // Order
3577 SubExprs.push_back(TheCall->getArg(1)); // Val1
3578 SubExprs.push_back(TheCall->getArg(2)); // Val2
3579 break;
3580 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003581 SubExprs.push_back(TheCall->getArg(3)); // Order
3582 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003583 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00003584 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00003585 break;
3586 case GNUCmpXchg:
3587 SubExprs.push_back(TheCall->getArg(4)); // Order
3588 SubExprs.push_back(TheCall->getArg(1)); // Val1
3589 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3590 SubExprs.push_back(TheCall->getArg(2)); // Val2
3591 SubExprs.push_back(TheCall->getArg(3)); // Weak
3592 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003593 }
Tim Northovere94a34c2014-03-11 10:49:14 +00003594
3595 if (SubExprs.size() >= 2 && Form != Init) {
3596 llvm::APSInt Result(32);
3597 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3598 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00003599 Diag(SubExprs[1]->getLocStart(),
3600 diag::warn_atomic_op_has_invalid_memory_order)
3601 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00003602 }
3603
Yaxun Liu30d652a2017-08-15 16:02:49 +00003604 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3605 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3606 llvm::APSInt Result(32);
3607 if (Scope->isIntegerConstantExpr(Result, Context) &&
3608 !ScopeModel->isValid(Result.getZExtValue())) {
3609 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3610 << Scope->getSourceRange();
3611 }
3612 SubExprs.push_back(Scope);
3613 }
3614
Fariborz Jahanian615de762013-05-28 17:37:39 +00003615 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3616 SubExprs, ResultType, Op,
3617 TheCall->getRParenLoc());
3618
3619 if ((Op == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00003620 Op == AtomicExpr::AO__c11_atomic_store ||
3621 Op == AtomicExpr::AO__opencl_atomic_load ||
3622 Op == AtomicExpr::AO__opencl_atomic_store ) &&
Fariborz Jahanian615de762013-05-28 17:37:39 +00003623 Context.AtomicUsesUnsupportedLibcall(AE))
Yaxun Liu39195062017-08-04 18:16:31 +00003624 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3625 << ((Op == AtomicExpr::AO__c11_atomic_load ||
3626 Op == AtomicExpr::AO__opencl_atomic_load)
3627 ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003628
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003629 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003630}
3631
John McCall29ad95b2011-08-27 01:09:30 +00003632/// checkBuiltinArgument - Given a call to a builtin function, perform
3633/// normal type-checking on the given argument, updating the call in
3634/// place. This is useful when a builtin function requires custom
3635/// type-checking for some of its arguments but not necessarily all of
3636/// them.
3637///
3638/// Returns true on error.
3639static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3640 FunctionDecl *Fn = E->getDirectCallee();
3641 assert(Fn && "builtin call without direct callee!");
3642
3643 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3644 InitializedEntity Entity =
3645 InitializedEntity::InitializeParameter(S.Context, Param);
3646
3647 ExprResult Arg = E->getArg(0);
3648 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3649 if (Arg.isInvalid())
3650 return true;
3651
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003652 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003653 return false;
3654}
3655
Chris Lattnerdc046542009-05-08 06:58:22 +00003656/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3657/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3658/// type of its first argument. The main ActOnCallExpr routines have already
3659/// promoted the types of arguments because all of these calls are prototyped as
3660/// void(...).
3661///
3662/// This function goes through and does final semantic checking for these
3663/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003664ExprResult
3665Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003666 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003667 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3668 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3669
3670 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003671 if (TheCall->getNumArgs() < 1) {
3672 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3673 << 0 << 1 << TheCall->getNumArgs()
3674 << TheCall->getCallee()->getSourceRange();
3675 return ExprError();
3676 }
Mike Stump11289f42009-09-09 15:08:12 +00003677
Chris Lattnerdc046542009-05-08 06:58:22 +00003678 // Inspect the first argument of the atomic builtin. This should always be
3679 // a pointer type, whose element is an integral scalar or pointer type.
3680 // Because it is a pointer type, we don't have to worry about any implicit
3681 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003682 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003683 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003684 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3685 if (FirstArgResult.isInvalid())
3686 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003687 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003688 TheCall->setArg(0, FirstArg);
3689
John McCall31168b02011-06-15 23:02:42 +00003690 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3691 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003692 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3693 << FirstArg->getType() << FirstArg->getSourceRange();
3694 return ExprError();
3695 }
Mike Stump11289f42009-09-09 15:08:12 +00003696
John McCall31168b02011-06-15 23:02:42 +00003697 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003698 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003699 !ValType->isBlockPointerType()) {
3700 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3701 << FirstArg->getType() << FirstArg->getSourceRange();
3702 return ExprError();
3703 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003704
Aaron Ballmana383c942018-05-05 17:38:42 +00003705 if (ValType.isConstQualified()) {
3706 Diag(DRE->getLocStart(), diag::err_atomic_builtin_cannot_be_const)
3707 << FirstArg->getType() << FirstArg->getSourceRange();
3708 return ExprError();
3709 }
3710
John McCall31168b02011-06-15 23:02:42 +00003711 switch (ValType.getObjCLifetime()) {
3712 case Qualifiers::OCL_None:
3713 case Qualifiers::OCL_ExplicitNone:
3714 // okay
3715 break;
3716
3717 case Qualifiers::OCL_Weak:
3718 case Qualifiers::OCL_Strong:
3719 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003720 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003721 << ValType << FirstArg->getSourceRange();
3722 return ExprError();
3723 }
3724
John McCallb50451a2011-10-05 07:41:44 +00003725 // Strip any qualifiers off ValType.
3726 ValType = ValType.getUnqualifiedType();
3727
Chandler Carruth3973af72010-07-18 20:54:12 +00003728 // The majority of builtins return a value, but a few have special return
3729 // types, so allow them to override appropriately below.
3730 QualType ResultType = ValType;
3731
Chris Lattnerdc046542009-05-08 06:58:22 +00003732 // We need to figure out which concrete builtin this maps onto. For example,
3733 // __sync_fetch_and_add with a 2 byte object turns into
3734 // __sync_fetch_and_add_2.
3735#define BUILTIN_ROW(x) \
3736 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3737 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003738
Chris Lattnerdc046542009-05-08 06:58:22 +00003739 static const unsigned BuiltinIndices[][5] = {
3740 BUILTIN_ROW(__sync_fetch_and_add),
3741 BUILTIN_ROW(__sync_fetch_and_sub),
3742 BUILTIN_ROW(__sync_fetch_and_or),
3743 BUILTIN_ROW(__sync_fetch_and_and),
3744 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003745 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003746
Chris Lattnerdc046542009-05-08 06:58:22 +00003747 BUILTIN_ROW(__sync_add_and_fetch),
3748 BUILTIN_ROW(__sync_sub_and_fetch),
3749 BUILTIN_ROW(__sync_and_and_fetch),
3750 BUILTIN_ROW(__sync_or_and_fetch),
3751 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003752 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003753
Chris Lattnerdc046542009-05-08 06:58:22 +00003754 BUILTIN_ROW(__sync_val_compare_and_swap),
3755 BUILTIN_ROW(__sync_bool_compare_and_swap),
3756 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003757 BUILTIN_ROW(__sync_lock_release),
3758 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003759 };
Mike Stump11289f42009-09-09 15:08:12 +00003760#undef BUILTIN_ROW
3761
Chris Lattnerdc046542009-05-08 06:58:22 +00003762 // Determine the index of the size.
3763 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003764 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003765 case 1: SizeIndex = 0; break;
3766 case 2: SizeIndex = 1; break;
3767 case 4: SizeIndex = 2; break;
3768 case 8: SizeIndex = 3; break;
3769 case 16: SizeIndex = 4; break;
3770 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003771 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3772 << FirstArg->getType() << FirstArg->getSourceRange();
3773 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003774 }
Mike Stump11289f42009-09-09 15:08:12 +00003775
Chris Lattnerdc046542009-05-08 06:58:22 +00003776 // Each of these builtins has one pointer argument, followed by some number of
3777 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3778 // that we ignore. Find out which row of BuiltinIndices to read from as well
3779 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003780 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003781 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003782 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003783 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003784 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003785 case Builtin::BI__sync_fetch_and_add:
3786 case Builtin::BI__sync_fetch_and_add_1:
3787 case Builtin::BI__sync_fetch_and_add_2:
3788 case Builtin::BI__sync_fetch_and_add_4:
3789 case Builtin::BI__sync_fetch_and_add_8:
3790 case Builtin::BI__sync_fetch_and_add_16:
3791 BuiltinIndex = 0;
3792 break;
3793
3794 case Builtin::BI__sync_fetch_and_sub:
3795 case Builtin::BI__sync_fetch_and_sub_1:
3796 case Builtin::BI__sync_fetch_and_sub_2:
3797 case Builtin::BI__sync_fetch_and_sub_4:
3798 case Builtin::BI__sync_fetch_and_sub_8:
3799 case Builtin::BI__sync_fetch_and_sub_16:
3800 BuiltinIndex = 1;
3801 break;
3802
3803 case Builtin::BI__sync_fetch_and_or:
3804 case Builtin::BI__sync_fetch_and_or_1:
3805 case Builtin::BI__sync_fetch_and_or_2:
3806 case Builtin::BI__sync_fetch_and_or_4:
3807 case Builtin::BI__sync_fetch_and_or_8:
3808 case Builtin::BI__sync_fetch_and_or_16:
3809 BuiltinIndex = 2;
3810 break;
3811
3812 case Builtin::BI__sync_fetch_and_and:
3813 case Builtin::BI__sync_fetch_and_and_1:
3814 case Builtin::BI__sync_fetch_and_and_2:
3815 case Builtin::BI__sync_fetch_and_and_4:
3816 case Builtin::BI__sync_fetch_and_and_8:
3817 case Builtin::BI__sync_fetch_and_and_16:
3818 BuiltinIndex = 3;
3819 break;
Mike Stump11289f42009-09-09 15:08:12 +00003820
Douglas Gregor73722482011-11-28 16:30:08 +00003821 case Builtin::BI__sync_fetch_and_xor:
3822 case Builtin::BI__sync_fetch_and_xor_1:
3823 case Builtin::BI__sync_fetch_and_xor_2:
3824 case Builtin::BI__sync_fetch_and_xor_4:
3825 case Builtin::BI__sync_fetch_and_xor_8:
3826 case Builtin::BI__sync_fetch_and_xor_16:
3827 BuiltinIndex = 4;
3828 break;
3829
Hal Finkeld2208b52014-10-02 20:53:50 +00003830 case Builtin::BI__sync_fetch_and_nand:
3831 case Builtin::BI__sync_fetch_and_nand_1:
3832 case Builtin::BI__sync_fetch_and_nand_2:
3833 case Builtin::BI__sync_fetch_and_nand_4:
3834 case Builtin::BI__sync_fetch_and_nand_8:
3835 case Builtin::BI__sync_fetch_and_nand_16:
3836 BuiltinIndex = 5;
3837 WarnAboutSemanticsChange = true;
3838 break;
3839
Douglas Gregor73722482011-11-28 16:30:08 +00003840 case Builtin::BI__sync_add_and_fetch:
3841 case Builtin::BI__sync_add_and_fetch_1:
3842 case Builtin::BI__sync_add_and_fetch_2:
3843 case Builtin::BI__sync_add_and_fetch_4:
3844 case Builtin::BI__sync_add_and_fetch_8:
3845 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003846 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003847 break;
3848
3849 case Builtin::BI__sync_sub_and_fetch:
3850 case Builtin::BI__sync_sub_and_fetch_1:
3851 case Builtin::BI__sync_sub_and_fetch_2:
3852 case Builtin::BI__sync_sub_and_fetch_4:
3853 case Builtin::BI__sync_sub_and_fetch_8:
3854 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003855 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003856 break;
3857
3858 case Builtin::BI__sync_and_and_fetch:
3859 case Builtin::BI__sync_and_and_fetch_1:
3860 case Builtin::BI__sync_and_and_fetch_2:
3861 case Builtin::BI__sync_and_and_fetch_4:
3862 case Builtin::BI__sync_and_and_fetch_8:
3863 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003864 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003865 break;
3866
3867 case Builtin::BI__sync_or_and_fetch:
3868 case Builtin::BI__sync_or_and_fetch_1:
3869 case Builtin::BI__sync_or_and_fetch_2:
3870 case Builtin::BI__sync_or_and_fetch_4:
3871 case Builtin::BI__sync_or_and_fetch_8:
3872 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003873 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003874 break;
3875
3876 case Builtin::BI__sync_xor_and_fetch:
3877 case Builtin::BI__sync_xor_and_fetch_1:
3878 case Builtin::BI__sync_xor_and_fetch_2:
3879 case Builtin::BI__sync_xor_and_fetch_4:
3880 case Builtin::BI__sync_xor_and_fetch_8:
3881 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003882 BuiltinIndex = 10;
3883 break;
3884
3885 case Builtin::BI__sync_nand_and_fetch:
3886 case Builtin::BI__sync_nand_and_fetch_1:
3887 case Builtin::BI__sync_nand_and_fetch_2:
3888 case Builtin::BI__sync_nand_and_fetch_4:
3889 case Builtin::BI__sync_nand_and_fetch_8:
3890 case Builtin::BI__sync_nand_and_fetch_16:
3891 BuiltinIndex = 11;
3892 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003893 break;
Mike Stump11289f42009-09-09 15:08:12 +00003894
Chris Lattnerdc046542009-05-08 06:58:22 +00003895 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003896 case Builtin::BI__sync_val_compare_and_swap_1:
3897 case Builtin::BI__sync_val_compare_and_swap_2:
3898 case Builtin::BI__sync_val_compare_and_swap_4:
3899 case Builtin::BI__sync_val_compare_and_swap_8:
3900 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003901 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003902 NumFixed = 2;
3903 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003904
Chris Lattnerdc046542009-05-08 06:58:22 +00003905 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003906 case Builtin::BI__sync_bool_compare_and_swap_1:
3907 case Builtin::BI__sync_bool_compare_and_swap_2:
3908 case Builtin::BI__sync_bool_compare_and_swap_4:
3909 case Builtin::BI__sync_bool_compare_and_swap_8:
3910 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003911 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003912 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003913 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003914 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003915
JF Bastien7f0a05a2018-05-25 00:07:09 +00003916 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +00003917 case Builtin::BI__sync_lock_test_and_set_1:
3918 case Builtin::BI__sync_lock_test_and_set_2:
3919 case Builtin::BI__sync_lock_test_and_set_4:
3920 case Builtin::BI__sync_lock_test_and_set_8:
3921 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003922 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003923 break;
3924
Chris Lattnerdc046542009-05-08 06:58:22 +00003925 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003926 case Builtin::BI__sync_lock_release_1:
3927 case Builtin::BI__sync_lock_release_2:
3928 case Builtin::BI__sync_lock_release_4:
3929 case Builtin::BI__sync_lock_release_8:
3930 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003931 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003932 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003933 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003934 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003935
3936 case Builtin::BI__sync_swap:
3937 case Builtin::BI__sync_swap_1:
3938 case Builtin::BI__sync_swap_2:
3939 case Builtin::BI__sync_swap_4:
3940 case Builtin::BI__sync_swap_8:
3941 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003942 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003943 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003944 }
Mike Stump11289f42009-09-09 15:08:12 +00003945
Chris Lattnerdc046542009-05-08 06:58:22 +00003946 // Now that we know how many fixed arguments we expect, first check that we
3947 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003948 if (TheCall->getNumArgs() < 1+NumFixed) {
3949 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3950 << 0 << 1+NumFixed << TheCall->getNumArgs()
3951 << TheCall->getCallee()->getSourceRange();
3952 return ExprError();
3953 }
Mike Stump11289f42009-09-09 15:08:12 +00003954
Hal Finkeld2208b52014-10-02 20:53:50 +00003955 if (WarnAboutSemanticsChange) {
3956 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3957 << TheCall->getCallee()->getSourceRange();
3958 }
3959
Chris Lattner5b9241b2009-05-08 15:36:58 +00003960 // Get the decl for the concrete builtin from this, we can tell what the
3961 // concrete integer type we should convert to is.
3962 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003963 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003964 FunctionDecl *NewBuiltinDecl;
3965 if (NewBuiltinID == BuiltinID)
3966 NewBuiltinDecl = FDecl;
3967 else {
3968 // Perform builtin lookup to avoid redeclaring it.
3969 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3970 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3971 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3972 assert(Res.getFoundDecl());
3973 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003974 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003975 return ExprError();
3976 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003977
John McCallcf142162010-08-07 06:22:56 +00003978 // The first argument --- the pointer --- has a fixed type; we
3979 // deduce the types of the rest of the arguments accordingly. Walk
3980 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003981 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003982 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003983
Chris Lattnerdc046542009-05-08 06:58:22 +00003984 // GCC does an implicit conversion to the pointer or integer ValType. This
3985 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003986 // Initialize the argument.
3987 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3988 ValType, /*consume*/ false);
3989 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003990 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003991 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003992
Chris Lattnerdc046542009-05-08 06:58:22 +00003993 // Okay, we have something that *can* be converted to the right type. Check
3994 // to see if there is a potentially weird extension going on here. This can
3995 // happen when you do an atomic operation on something like an char* and
3996 // pass in 42. The 42 gets converted to char. This is even more strange
3997 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003998 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003999 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00004000 }
Mike Stump11289f42009-09-09 15:08:12 +00004001
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004002 ASTContext& Context = this->getASTContext();
4003
4004 // Create a new DeclRefExpr to refer to the new decl.
4005 DeclRefExpr* NewDRE = DeclRefExpr::Create(
4006 Context,
4007 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00004008 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004009 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00004010 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004011 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00004012 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004013 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00004014
Chris Lattnerdc046542009-05-08 06:58:22 +00004015 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00004016 // FIXME: This loses syntactic information.
4017 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
4018 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
4019 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004020 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00004021
Chandler Carruthbc8cab12010-07-18 07:23:17 +00004022 // Change the result type of the call to match the original value type. This
4023 // is arbitrary, but the codegen for these builtins ins design to handle it
4024 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00004025 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004026
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004027 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00004028}
4029
Michael Zolotukhin84df1232015-09-08 23:52:33 +00004030/// SemaBuiltinNontemporalOverloaded - We have a call to
4031/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
4032/// overloaded function based on the pointer type of its last argument.
4033///
4034/// This function goes through and does final semantic checking for these
4035/// builtins.
4036ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
4037 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
4038 DeclRefExpr *DRE =
4039 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4040 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4041 unsigned BuiltinID = FDecl->getBuiltinID();
4042 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
4043 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
4044 "Unexpected nontemporal load/store builtin!");
4045 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
4046 unsigned numArgs = isStore ? 2 : 1;
4047
4048 // Ensure that we have the proper number of arguments.
4049 if (checkArgCount(*this, TheCall, numArgs))
4050 return ExprError();
4051
4052 // Inspect the last argument of the nontemporal builtin. This should always
4053 // be a pointer type, from which we imply the type of the memory access.
4054 // Because it is a pointer type, we don't have to worry about any implicit
4055 // casts here.
4056 Expr *PointerArg = TheCall->getArg(numArgs - 1);
4057 ExprResult PointerArgResult =
4058 DefaultFunctionArrayLvalueConversion(PointerArg);
4059
4060 if (PointerArgResult.isInvalid())
4061 return ExprError();
4062 PointerArg = PointerArgResult.get();
4063 TheCall->setArg(numArgs - 1, PointerArg);
4064
4065 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
4066 if (!pointerType) {
4067 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
4068 << PointerArg->getType() << PointerArg->getSourceRange();
4069 return ExprError();
4070 }
4071
4072 QualType ValType = pointerType->getPointeeType();
4073
4074 // Strip any qualifiers off ValType.
4075 ValType = ValType.getUnqualifiedType();
4076 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4077 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
4078 !ValType->isVectorType()) {
4079 Diag(DRE->getLocStart(),
4080 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
4081 << PointerArg->getType() << PointerArg->getSourceRange();
4082 return ExprError();
4083 }
4084
4085 if (!isStore) {
4086 TheCall->setType(ValType);
4087 return TheCallResult;
4088 }
4089
4090 ExprResult ValArg = TheCall->getArg(0);
4091 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4092 Context, ValType, /*consume*/ false);
4093 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
4094 if (ValArg.isInvalid())
4095 return ExprError();
4096
4097 TheCall->setArg(0, ValArg.get());
4098 TheCall->setType(Context.VoidTy);
4099 return TheCallResult;
4100}
4101
Chris Lattner6436fb62009-02-18 06:01:06 +00004102/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00004103/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00004104/// Note: It might also make sense to do the UTF-16 conversion here (would
4105/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00004106bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00004107 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00004108 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
4109
Douglas Gregorfb65e592011-07-27 05:40:30 +00004110 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00004111 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
4112 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00004113 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00004114 }
Mike Stump11289f42009-09-09 15:08:12 +00004115
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004116 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004117 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004118 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00004119 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
4120 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4121 llvm::UTF16 *ToPtr = &ToBuf[0];
4122
4123 llvm::ConversionResult Result =
4124 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4125 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004126 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00004127 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004128 Diag(Arg->getLocStart(),
4129 diag::warn_cfstring_truncated) << Arg->getSourceRange();
4130 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00004131 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004132}
4133
Mehdi Amini06d367c2016-10-24 20:39:34 +00004134/// CheckObjCString - Checks that the format string argument to the os_log()
4135/// and os_trace() functions is correct, and converts it to const char *.
4136ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
4137 Arg = Arg->IgnoreParenCasts();
4138 auto *Literal = dyn_cast<StringLiteral>(Arg);
4139 if (!Literal) {
4140 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
4141 Literal = ObjcLiteral->getString();
4142 }
4143 }
4144
4145 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
4146 return ExprError(
4147 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
4148 << Arg->getSourceRange());
4149 }
4150
4151 ExprResult Result(Literal);
4152 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
4153 InitializedEntity Entity =
4154 InitializedEntity::InitializeParameter(Context, ResultTy, false);
4155 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
4156 return Result;
4157}
4158
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004159/// Check that the user is calling the appropriate va_start builtin for the
4160/// target and calling convention.
4161static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
4162 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
4163 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
Martin Storsjo022e7822017-07-17 20:49:45 +00004164 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004165 bool IsWindows = TT.isOSWindows();
Martin Storsjo022e7822017-07-17 20:49:45 +00004166 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
4167 if (IsX64 || IsAArch64) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004168 CallingConv CC = CC_C;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004169 if (const FunctionDecl *FD = S.getCurFunctionDecl())
4170 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
4171 if (IsMSVAStart) {
4172 // Don't allow this in System V ABI functions.
Martin Storsjo022e7822017-07-17 20:49:45 +00004173 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004174 return S.Diag(Fn->getLocStart(),
4175 diag::err_ms_va_start_used_in_sysv_function);
4176 } else {
Martin Storsjo022e7822017-07-17 20:49:45 +00004177 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004178 // On x64 Windows, don't allow this in System V ABI functions.
4179 // (Yes, that means there's no corresponding way to support variadic
4180 // System V ABI functions on Windows.)
4181 if ((IsWindows && CC == CC_X86_64SysV) ||
Martin Storsjo022e7822017-07-17 20:49:45 +00004182 (!IsWindows && CC == CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004183 return S.Diag(Fn->getLocStart(),
4184 diag::err_va_start_used_in_wrong_abi_function)
4185 << !IsWindows;
4186 }
4187 return false;
4188 }
4189
4190 if (IsMSVAStart)
Martin Storsjo022e7822017-07-17 20:49:45 +00004191 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004192 return false;
4193}
4194
4195static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
4196 ParmVarDecl **LastParam = nullptr) {
4197 // Determine whether the current function, block, or obj-c method is variadic
4198 // and get its parameter list.
4199 bool IsVariadic = false;
4200 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00004201 DeclContext *Caller = S.CurContext;
4202 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
4203 IsVariadic = Block->isVariadic();
4204 Params = Block->parameters();
4205 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004206 IsVariadic = FD->isVariadic();
4207 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00004208 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004209 IsVariadic = MD->isVariadic();
4210 // FIXME: This isn't correct for methods (results in bogus warning).
4211 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00004212 } else if (isa<CapturedDecl>(Caller)) {
4213 // We don't support va_start in a CapturedDecl.
4214 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
4215 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004216 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00004217 // This must be some other declcontext that parses exprs.
4218 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
4219 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004220 }
4221
4222 if (!IsVariadic) {
Reid Klecknerf1deb832017-05-04 19:51:05 +00004223 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004224 return true;
4225 }
4226
4227 if (LastParam)
4228 *LastParam = Params.empty() ? nullptr : Params.back();
4229
4230 return false;
4231}
4232
Charles Davisc7d5c942015-09-17 20:55:33 +00004233/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
4234/// for validity. Emit an error and return true on failure; return false
4235/// on success.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004236bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00004237 Expr *Fn = TheCall->getCallee();
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004238
4239 if (checkVAStartABI(*this, BuiltinID, Fn))
4240 return true;
4241
Chris Lattner08464942007-12-28 05:29:59 +00004242 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00004243 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004244 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004245 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4246 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00004247 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004248 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00004249 return true;
4250 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00004251
4252 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00004253 return Diag(TheCall->getLocEnd(),
4254 diag::err_typecheck_call_too_few_args_at_least)
4255 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00004256 }
4257
John McCall29ad95b2011-08-27 01:09:30 +00004258 // Type-check the first argument normally.
4259 if (checkBuiltinArgument(*this, TheCall, 0))
4260 return true;
4261
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004262 // Check that the current function is variadic, and get its last parameter.
4263 ParmVarDecl *LastParam;
4264 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
Chris Lattner43be2e62007-12-19 23:59:04 +00004265 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004266
Chris Lattner43be2e62007-12-19 23:59:04 +00004267 // Verify that the second argument to the builtin is the last argument of the
4268 // current function or method.
4269 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00004270 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004271
Nico Weber9eea7642013-05-24 23:31:57 +00004272 // These are valid if SecondArgIsLastNamedArgument is false after the next
4273 // block.
4274 QualType Type;
4275 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00004276 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00004277
Anders Carlsson6a8350b2008-02-11 04:20:54 +00004278 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
4279 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004280 SecondArgIsLastNamedArgument = PV == LastParam;
Nico Weber9eea7642013-05-24 23:31:57 +00004281
4282 Type = PV->getType();
4283 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00004284 IsCRegister =
4285 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00004286 }
4287 }
Mike Stump11289f42009-09-09 15:08:12 +00004288
Chris Lattner43be2e62007-12-19 23:59:04 +00004289 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00004290 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00004291 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00004292 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00004293 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
4294 // Promotable integers are UB, but enumerations need a bit of
4295 // extra checking to see what their promotable type actually is.
4296 if (!Type->isPromotableIntegerType())
4297 return false;
4298 if (!Type->isEnumeralType())
4299 return true;
4300 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
4301 return !(ED &&
4302 Context.typesAreCompatible(ED->getPromotionType(), Type));
4303 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00004304 unsigned Reason = 0;
4305 if (Type->isReferenceType()) Reason = 1;
4306 else if (IsCRegister) Reason = 2;
4307 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00004308 Diag(ParamLoc, diag::note_parameter_type) << Type;
4309 }
4310
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00004311 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00004312 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00004313}
Chris Lattner43be2e62007-12-19 23:59:04 +00004314
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +00004315bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004316 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
4317 // const char *named_addr);
4318
4319 Expr *Func = Call->getCallee();
4320
4321 if (Call->getNumArgs() < 3)
4322 return Diag(Call->getLocEnd(),
4323 diag::err_typecheck_call_too_few_args_at_least)
4324 << 0 /*function call*/ << 3 << Call->getNumArgs();
4325
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004326 // Type-check the first argument normally.
4327 if (checkBuiltinArgument(*this, Call, 0))
4328 return true;
4329
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004330 // Check that the current function is variadic.
4331 if (checkVAStartIsInVariadicFunction(*this, Func))
4332 return true;
4333
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004334 // __va_start on Windows does not validate the parameter qualifiers
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004335
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004336 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4337 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4338
4339 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4340 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4341
4342 const QualType &ConstCharPtrTy =
4343 Context.getPointerType(Context.CharTy.withConst());
4344 if (!Arg1Ty->isPointerType() ||
4345 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4346 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4347 << Arg1->getType() << ConstCharPtrTy
4348 << 1 /* different class */
4349 << 0 /* qualifier difference */
4350 << 3 /* parameter mismatch */
4351 << 2 << Arg1->getType() << ConstCharPtrTy;
4352
4353 const QualType SizeTy = Context.getSizeType();
4354 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4355 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4356 << Arg2->getType() << SizeTy
4357 << 1 /* different class */
4358 << 0 /* qualifier difference */
4359 << 3 /* parameter mismatch */
4360 << 3 << Arg2->getType() << SizeTy;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004361
4362 return false;
4363}
4364
Chris Lattner2da14fb2007-12-20 00:26:33 +00004365/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4366/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00004367bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4368 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00004369 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004370 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00004371 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00004372 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004373 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004374 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00004375 << SourceRange(TheCall->getArg(2)->getLocStart(),
4376 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004377
John Wiegley01296292011-04-08 18:41:53 +00004378 ExprResult OrigArg0 = TheCall->getArg(0);
4379 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004380
Chris Lattner2da14fb2007-12-20 00:26:33 +00004381 // Do standard promotions between the two arguments, returning their common
4382 // type.
Chris Lattner08464942007-12-28 05:29:59 +00004383 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00004384 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4385 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00004386
4387 // Make sure any conversions are pushed back into the call; this is
4388 // type safe since unordered compare builtins are declared as "_Bool
4389 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00004390 TheCall->setArg(0, OrigArg0.get());
4391 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00004392
John Wiegley01296292011-04-08 18:41:53 +00004393 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00004394 return false;
4395
Chris Lattner2da14fb2007-12-20 00:26:33 +00004396 // If the common type isn't a real floating type, then the arguments were
4397 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00004398 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00004399 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004400 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00004401 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4402 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004403
Chris Lattner2da14fb2007-12-20 00:26:33 +00004404 return false;
4405}
4406
Benjamin Kramer634fc102010-02-15 22:42:31 +00004407/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4408/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00004409/// to check everything. We expect the last argument to be a floating point
4410/// value.
4411bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4412 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00004413 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004414 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00004415 if (TheCall->getNumArgs() > NumArgs)
4416 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004417 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004418 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00004419 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004420 (*(TheCall->arg_end()-1))->getLocEnd());
4421
Benjamin Kramer64aae502010-02-16 10:07:31 +00004422 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00004423
Eli Friedman7e4faac2009-08-31 20:06:00 +00004424 if (OrigArg->isTypeDependent())
4425 return false;
4426
Chris Lattner68784ef2010-05-06 05:50:07 +00004427 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00004428 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00004429 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004430 diag::err_typecheck_call_invalid_unary_fp)
4431 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004432
Neil Hickey88c0fac2016-12-13 16:22:50 +00004433 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00004434 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00004435 // Only remove standard FloatCasts, leaving other casts inplace
4436 if (Cast->getCastKind() == CK_FloatingCast) {
4437 Expr *CastArg = Cast->getSubExpr();
4438 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4439 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4440 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4441 "promotion from float to either float or double is the only expected cast here");
4442 Cast->setSubExpr(nullptr);
4443 TheCall->setArg(NumArgs-1, CastArg);
4444 }
Chris Lattner68784ef2010-05-06 05:50:07 +00004445 }
4446 }
4447
Eli Friedman7e4faac2009-08-31 20:06:00 +00004448 return false;
4449}
4450
Tony Jiangbbc48e92017-05-24 15:13:32 +00004451// Customized Sema Checking for VSX builtins that have the following signature:
4452// vector [...] builtinName(vector [...], vector [...], const int);
4453// Which takes the same type of vectors (any legal vector type) for the first
4454// two arguments and takes compile time constant for the third argument.
4455// Example builtins are :
4456// vector double vec_xxpermdi(vector double, vector double, int);
4457// vector short vec_xxsldwi(vector short, vector short, int);
4458bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4459 unsigned ExpectedNumArgs = 3;
4460 if (TheCall->getNumArgs() < ExpectedNumArgs)
4461 return Diag(TheCall->getLocEnd(),
4462 diag::err_typecheck_call_too_few_args_at_least)
4463 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4464 << TheCall->getSourceRange();
4465
4466 if (TheCall->getNumArgs() > ExpectedNumArgs)
4467 return Diag(TheCall->getLocEnd(),
4468 diag::err_typecheck_call_too_many_args_at_most)
4469 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4470 << TheCall->getSourceRange();
4471
4472 // Check the third argument is a compile time constant
4473 llvm::APSInt Value;
4474 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4475 return Diag(TheCall->getLocStart(),
4476 diag::err_vsx_builtin_nonconstant_argument)
4477 << 3 /* argument index */ << TheCall->getDirectCallee()
4478 << SourceRange(TheCall->getArg(2)->getLocStart(),
4479 TheCall->getArg(2)->getLocEnd());
4480
4481 QualType Arg1Ty = TheCall->getArg(0)->getType();
4482 QualType Arg2Ty = TheCall->getArg(1)->getType();
4483
4484 // Check the type of argument 1 and argument 2 are vectors.
4485 SourceLocation BuiltinLoc = TheCall->getLocStart();
4486 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4487 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4488 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4489 << TheCall->getDirectCallee()
4490 << SourceRange(TheCall->getArg(0)->getLocStart(),
4491 TheCall->getArg(1)->getLocEnd());
4492 }
4493
4494 // Check the first two arguments are the same type.
4495 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4496 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4497 << TheCall->getDirectCallee()
4498 << SourceRange(TheCall->getArg(0)->getLocStart(),
4499 TheCall->getArg(1)->getLocEnd());
4500 }
4501
4502 // When default clang type checking is turned off and the customized type
4503 // checking is used, the returning type of the function must be explicitly
4504 // set. Otherwise it is _Bool by default.
4505 TheCall->setType(Arg1Ty);
4506
4507 return false;
4508}
4509
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004510/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4511// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00004512ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00004513 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004514 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00004515 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00004516 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4517 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004518
Nate Begemana0110022010-06-08 00:16:34 +00004519 // Determine which of the following types of shufflevector we're checking:
4520 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00004521 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00004522 QualType resType = TheCall->getArg(0)->getType();
4523 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00004524
Douglas Gregorc25f7662009-05-19 22:10:17 +00004525 if (!TheCall->getArg(0)->isTypeDependent() &&
4526 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00004527 QualType LHSType = TheCall->getArg(0)->getType();
4528 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00004529
Craig Topperbaca3892013-07-29 06:47:04 +00004530 if (!LHSType->isVectorType() || !RHSType->isVectorType())
4531 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004532 diag::err_vec_builtin_non_vector)
4533 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004534 << SourceRange(TheCall->getArg(0)->getLocStart(),
4535 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004536
Nate Begemana0110022010-06-08 00:16:34 +00004537 numElements = LHSType->getAs<VectorType>()->getNumElements();
4538 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00004539
Nate Begemana0110022010-06-08 00:16:34 +00004540 // Check to see if we have a call with 2 vector arguments, the unary shuffle
4541 // with mask. If so, verify that RHS is an integer vector type with the
4542 // same number of elts as lhs.
4543 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00004544 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00004545 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00004546 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004547 diag::err_vec_builtin_incompatible_vector)
4548 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004549 << SourceRange(TheCall->getArg(1)->getLocStart(),
4550 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004551 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00004552 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004553 diag::err_vec_builtin_incompatible_vector)
4554 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004555 << SourceRange(TheCall->getArg(0)->getLocStart(),
4556 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00004557 } else if (numElements != numResElements) {
4558 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00004559 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00004560 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004561 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004562 }
4563
4564 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00004565 if (TheCall->getArg(i)->isTypeDependent() ||
4566 TheCall->getArg(i)->isValueDependent())
4567 continue;
4568
Nate Begemana0110022010-06-08 00:16:34 +00004569 llvm::APSInt Result(32);
4570 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4571 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004572 diag::err_shufflevector_nonconstant_argument)
4573 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004574
Craig Topper50ad5b72013-08-03 17:40:38 +00004575 // Allow -1 which will be translated to undef in the IR.
4576 if (Result.isSigned() && Result.isAllOnesValue())
4577 continue;
4578
Chris Lattner7ab824e2008-08-10 02:05:13 +00004579 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004580 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004581 diag::err_shufflevector_argument_too_large)
4582 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004583 }
4584
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004585 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004586
Chris Lattner7ab824e2008-08-10 02:05:13 +00004587 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004588 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00004589 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004590 }
4591
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004592 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4593 TheCall->getCallee()->getLocStart(),
4594 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004595}
Chris Lattner43be2e62007-12-19 23:59:04 +00004596
Hal Finkelc4d7c822013-09-18 03:29:45 +00004597/// SemaConvertVectorExpr - Handle __builtin_convertvector
4598ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4599 SourceLocation BuiltinLoc,
4600 SourceLocation RParenLoc) {
4601 ExprValueKind VK = VK_RValue;
4602 ExprObjectKind OK = OK_Ordinary;
4603 QualType DstTy = TInfo->getType();
4604 QualType SrcTy = E->getType();
4605
4606 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4607 return ExprError(Diag(BuiltinLoc,
4608 diag::err_convertvector_non_vector)
4609 << E->getSourceRange());
4610 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4611 return ExprError(Diag(BuiltinLoc,
4612 diag::err_convertvector_non_vector_type));
4613
4614 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4615 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4616 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4617 if (SrcElts != DstElts)
4618 return ExprError(Diag(BuiltinLoc,
4619 diag::err_convertvector_incompatible_vector)
4620 << E->getSourceRange());
4621 }
4622
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004623 return new (Context)
4624 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00004625}
4626
Daniel Dunbarb7257262008-07-21 22:59:13 +00004627/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4628// This is declared to take (const void*, ...) and can take two
4629// optional constant int args.
4630bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00004631 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004632
Chris Lattner3b054132008-11-19 05:08:23 +00004633 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004634 return Diag(TheCall->getLocEnd(),
4635 diag::err_typecheck_call_too_many_args_at_most)
4636 << 0 /*function call*/ << 3 << NumArgs
4637 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004638
4639 // Argument 0 is checked for us and the remaining arguments must be
4640 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00004641 for (unsigned i = 1; i != NumArgs; ++i)
4642 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004643 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004644
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004645 return false;
4646}
4647
Hal Finkelf0417332014-07-17 14:25:55 +00004648/// SemaBuiltinAssume - Handle __assume (MS Extension).
4649// __assume does not evaluate its arguments, and should warn if its argument
4650// has side effects.
4651bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4652 Expr *Arg = TheCall->getArg(0);
4653 if (Arg->isInstantiationDependent()) return false;
4654
4655 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00004656 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00004657 << Arg->getSourceRange()
4658 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4659
4660 return false;
4661}
4662
David Majnemer86b1bfa2016-10-31 18:07:57 +00004663/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00004664/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4665/// than 8.
4666bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4667 // The alignment must be a constant integer.
4668 Expr *Arg = TheCall->getArg(1);
4669
4670 // We can't check the value of a dependent argument.
4671 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00004672 if (const auto *UE =
4673 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4674 if (UE->getKind() == UETT_AlignOf)
4675 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4676 << Arg->getSourceRange();
4677
David Majnemer51169932016-10-31 05:37:48 +00004678 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4679
4680 if (!Result.isPowerOf2())
4681 return Diag(TheCall->getLocStart(),
4682 diag::err_alignment_not_power_of_two)
4683 << Arg->getSourceRange();
4684
4685 if (Result < Context.getCharWidth())
4686 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4687 << (unsigned)Context.getCharWidth()
4688 << Arg->getSourceRange();
4689
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004690 if (Result > std::numeric_limits<int32_t>::max())
David Majnemer51169932016-10-31 05:37:48 +00004691 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004692 << std::numeric_limits<int32_t>::max()
David Majnemer51169932016-10-31 05:37:48 +00004693 << Arg->getSourceRange();
4694 }
4695
4696 return false;
4697}
4698
4699/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00004700/// as (const void*, size_t, ...) and can take one optional constant int arg.
4701bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4702 unsigned NumArgs = TheCall->getNumArgs();
4703
4704 if (NumArgs > 3)
4705 return Diag(TheCall->getLocEnd(),
4706 diag::err_typecheck_call_too_many_args_at_most)
4707 << 0 /*function call*/ << 3 << NumArgs
4708 << TheCall->getSourceRange();
4709
4710 // The alignment must be a constant integer.
4711 Expr *Arg = TheCall->getArg(1);
4712
4713 // We can't check the value of a dependent argument.
4714 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4715 llvm::APSInt Result;
4716 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4717 return true;
4718
4719 if (!Result.isPowerOf2())
4720 return Diag(TheCall->getLocStart(),
4721 diag::err_alignment_not_power_of_two)
4722 << Arg->getSourceRange();
4723 }
4724
4725 if (NumArgs > 2) {
4726 ExprResult Arg(TheCall->getArg(2));
4727 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4728 Context.getSizeType(), false);
4729 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4730 if (Arg.isInvalid()) return true;
4731 TheCall->setArg(2, Arg.get());
4732 }
Hal Finkelf0417332014-07-17 14:25:55 +00004733
4734 return false;
4735}
4736
Mehdi Amini06d367c2016-10-24 20:39:34 +00004737bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4738 unsigned BuiltinID =
4739 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4740 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4741
4742 unsigned NumArgs = TheCall->getNumArgs();
4743 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4744 if (NumArgs < NumRequiredArgs) {
4745 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4746 << 0 /* function call */ << NumRequiredArgs << NumArgs
4747 << TheCall->getSourceRange();
4748 }
4749 if (NumArgs >= NumRequiredArgs + 0x100) {
4750 return Diag(TheCall->getLocEnd(),
4751 diag::err_typecheck_call_too_many_args_at_most)
4752 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4753 << TheCall->getSourceRange();
4754 }
4755 unsigned i = 0;
4756
4757 // For formatting call, check buffer arg.
4758 if (!IsSizeCall) {
4759 ExprResult Arg(TheCall->getArg(i));
4760 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4761 Context, Context.VoidPtrTy, false);
4762 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4763 if (Arg.isInvalid())
4764 return true;
4765 TheCall->setArg(i, Arg.get());
4766 i++;
4767 }
4768
4769 // Check string literal arg.
4770 unsigned FormatIdx = i;
4771 {
4772 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4773 if (Arg.isInvalid())
4774 return true;
4775 TheCall->setArg(i, Arg.get());
4776 i++;
4777 }
4778
4779 // Make sure variadic args are scalar.
4780 unsigned FirstDataArg = i;
4781 while (i < NumArgs) {
4782 ExprResult Arg = DefaultVariadicArgumentPromotion(
4783 TheCall->getArg(i), VariadicFunction, nullptr);
4784 if (Arg.isInvalid())
4785 return true;
4786 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4787 if (ArgSize.getQuantity() >= 0x100) {
4788 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4789 << i << (int)ArgSize.getQuantity() << 0xff
4790 << TheCall->getSourceRange();
4791 }
4792 TheCall->setArg(i, Arg.get());
4793 i++;
4794 }
4795
4796 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4797 // call to avoid duplicate diagnostics.
4798 if (!IsSizeCall) {
4799 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4800 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4801 bool Success = CheckFormatArguments(
4802 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4803 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4804 CheckedVarArgs);
4805 if (!Success)
4806 return true;
4807 }
4808
4809 if (IsSizeCall) {
4810 TheCall->setType(Context.getSizeType());
4811 } else {
4812 TheCall->setType(Context.VoidPtrTy);
4813 }
4814 return false;
4815}
4816
Eric Christopher8d0c6212010-04-17 02:26:23 +00004817/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4818/// TheCall is a constant expression.
4819bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4820 llvm::APSInt &Result) {
4821 Expr *Arg = TheCall->getArg(ArgNum);
4822 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4823 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4824
4825 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4826
4827 if (!Arg->isIntegerConstantExpr(Result, Context))
4828 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004829 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004830
Chris Lattnerd545ad12009-09-23 06:06:36 +00004831 return false;
4832}
4833
Richard Sandiford28940af2014-04-16 08:47:51 +00004834/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4835/// TheCall is a constant expression in the range [Low, High].
4836bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4837 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004838 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004839
4840 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004841 Expr *Arg = TheCall->getArg(ArgNum);
4842 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004843 return false;
4844
Eric Christopher8d0c6212010-04-17 02:26:23 +00004845 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004846 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004847 return true;
4848
Richard Sandiford28940af2014-04-16 08:47:51 +00004849 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004850 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004851 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004852
4853 return false;
4854}
4855
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004856/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4857/// TheCall is a constant expression is a multiple of Num..
4858bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4859 unsigned Num) {
4860 llvm::APSInt Result;
4861
4862 // We can't check the value of a dependent argument.
4863 Expr *Arg = TheCall->getArg(ArgNum);
4864 if (Arg->isTypeDependent() || Arg->isValueDependent())
4865 return false;
4866
4867 // Check constant-ness first.
4868 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4869 return true;
4870
4871 if (Result.getSExtValue() % Num != 0)
4872 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4873 << Num << Arg->getSourceRange();
4874
4875 return false;
4876}
4877
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004878/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4879/// TheCall is an ARM/AArch64 special register string literal.
4880bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4881 int ArgNum, unsigned ExpectedFieldNum,
4882 bool AllowName) {
4883 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4884 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4885 BuiltinID == ARM::BI__builtin_arm_rsr ||
4886 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4887 BuiltinID == ARM::BI__builtin_arm_wsr ||
4888 BuiltinID == ARM::BI__builtin_arm_wsrp;
4889 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4890 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4891 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4892 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4893 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4894 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4895 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4896
4897 // We can't check the value of a dependent argument.
4898 Expr *Arg = TheCall->getArg(ArgNum);
4899 if (Arg->isTypeDependent() || Arg->isValueDependent())
4900 return false;
4901
4902 // Check if the argument is a string literal.
4903 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4904 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4905 << Arg->getSourceRange();
4906
4907 // Check the type of special register given.
4908 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4909 SmallVector<StringRef, 6> Fields;
4910 Reg.split(Fields, ":");
4911
4912 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4913 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4914 << Arg->getSourceRange();
4915
4916 // If the string is the name of a register then we cannot check that it is
4917 // valid here but if the string is of one the forms described in ACLE then we
4918 // can check that the supplied fields are integers and within the valid
4919 // ranges.
4920 if (Fields.size() > 1) {
4921 bool FiveFields = Fields.size() == 5;
4922
4923 bool ValidString = true;
4924 if (IsARMBuiltin) {
4925 ValidString &= Fields[0].startswith_lower("cp") ||
4926 Fields[0].startswith_lower("p");
4927 if (ValidString)
4928 Fields[0] =
4929 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4930
4931 ValidString &= Fields[2].startswith_lower("c");
4932 if (ValidString)
4933 Fields[2] = Fields[2].drop_front(1);
4934
4935 if (FiveFields) {
4936 ValidString &= Fields[3].startswith_lower("c");
4937 if (ValidString)
4938 Fields[3] = Fields[3].drop_front(1);
4939 }
4940 }
4941
4942 SmallVector<int, 5> Ranges;
4943 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00004944 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004945 else
4946 Ranges.append({15, 7, 15});
4947
4948 for (unsigned i=0; i<Fields.size(); ++i) {
4949 int IntField;
4950 ValidString &= !Fields[i].getAsInteger(10, IntField);
4951 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4952 }
4953
4954 if (!ValidString)
4955 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4956 << Arg->getSourceRange();
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004957 } else if (IsAArch64Builtin && Fields.size() == 1) {
4958 // If the register name is one of those that appear in the condition below
4959 // and the special register builtin being used is one of the write builtins,
4960 // then we require that the argument provided for writing to the register
4961 // is an integer constant expression. This is because it will be lowered to
4962 // an MSR (immediate) instruction, so we need to know the immediate at
4963 // compile time.
4964 if (TheCall->getNumArgs() != 2)
4965 return false;
4966
4967 std::string RegLower = Reg.lower();
4968 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4969 RegLower != "pan" && RegLower != "uao")
4970 return false;
4971
4972 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4973 }
4974
4975 return false;
4976}
4977
Eli Friedmanc97d0142009-05-03 06:04:26 +00004978/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004979/// This checks that the target supports __builtin_longjmp and
4980/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004981bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004982 if (!Context.getTargetInfo().hasSjLjLowering())
4983 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4984 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4985
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004986 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004987 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004988
Eric Christopher8d0c6212010-04-17 02:26:23 +00004989 // TODO: This is less than ideal. Overload this to take a value.
4990 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4991 return true;
4992
4993 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004994 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4995 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4996
4997 return false;
4998}
4999
Joerg Sonnenberger27173282015-03-11 23:46:32 +00005000/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
5001/// This checks that the target supports __builtin_setjmp.
5002bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
5003 if (!Context.getTargetInfo().hasSjLjLowering())
5004 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
5005 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
5006 return false;
5007}
5008
Richard Smithd7293d72013-08-05 18:49:43 +00005009namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005010
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005011class UncoveredArgHandler {
5012 enum { Unknown = -1, AllCovered = -2 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005013
5014 signed FirstUncoveredArg = Unknown;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005015 SmallVector<const Expr *, 4> DiagnosticExprs;
5016
5017public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005018 UncoveredArgHandler() = default;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005019
5020 bool hasUncoveredArg() const {
5021 return (FirstUncoveredArg >= 0);
5022 }
5023
5024 unsigned getUncoveredArg() const {
5025 assert(hasUncoveredArg() && "no uncovered argument");
5026 return FirstUncoveredArg;
5027 }
5028
5029 void setAllCovered() {
5030 // A string has been found with all arguments covered, so clear out
5031 // the diagnostics.
5032 DiagnosticExprs.clear();
5033 FirstUncoveredArg = AllCovered;
5034 }
5035
5036 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
5037 assert(NewFirstUncoveredArg >= 0 && "Outside range");
5038
5039 // Don't update if a previous string covers all arguments.
5040 if (FirstUncoveredArg == AllCovered)
5041 return;
5042
5043 // UncoveredArgHandler tracks the highest uncovered argument index
5044 // and with it all the strings that match this index.
5045 if (NewFirstUncoveredArg == FirstUncoveredArg)
5046 DiagnosticExprs.push_back(StrExpr);
5047 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
5048 DiagnosticExprs.clear();
5049 DiagnosticExprs.push_back(StrExpr);
5050 FirstUncoveredArg = NewFirstUncoveredArg;
5051 }
5052 }
5053
5054 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
5055};
5056
Richard Smithd7293d72013-08-05 18:49:43 +00005057enum StringLiteralCheckType {
5058 SLCT_NotALiteral,
5059 SLCT_UncheckedLiteral,
5060 SLCT_CheckedLiteral
5061};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005062
5063} // namespace
Richard Smithd7293d72013-08-05 18:49:43 +00005064
Stephen Hines648c3692016-09-16 01:07:04 +00005065static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
5066 BinaryOperatorKind BinOpKind,
5067 bool AddendIsRight) {
5068 unsigned BitWidth = Offset.getBitWidth();
5069 unsigned AddendBitWidth = Addend.getBitWidth();
5070 // There might be negative interim results.
5071 if (Addend.isUnsigned()) {
5072 Addend = Addend.zext(++AddendBitWidth);
5073 Addend.setIsSigned(true);
5074 }
5075 // Adjust the bit width of the APSInts.
5076 if (AddendBitWidth > BitWidth) {
5077 Offset = Offset.sext(AddendBitWidth);
5078 BitWidth = AddendBitWidth;
5079 } else if (BitWidth > AddendBitWidth) {
5080 Addend = Addend.sext(BitWidth);
5081 }
5082
5083 bool Ov = false;
5084 llvm::APSInt ResOffset = Offset;
5085 if (BinOpKind == BO_Add)
5086 ResOffset = Offset.sadd_ov(Addend, Ov);
5087 else {
5088 assert(AddendIsRight && BinOpKind == BO_Sub &&
5089 "operator must be add or sub with addend on the right");
5090 ResOffset = Offset.ssub_ov(Addend, Ov);
5091 }
5092
5093 // We add an offset to a pointer here so we should support an offset as big as
5094 // possible.
5095 if (Ov) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005096 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
5097 "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00005098 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00005099 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
5100 return;
5101 }
5102
5103 Offset = ResOffset;
5104}
5105
5106namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005107
Stephen Hines648c3692016-09-16 01:07:04 +00005108// This is a wrapper class around StringLiteral to support offsetted string
5109// literals as format strings. It takes the offset into account when returning
5110// the string and its length or the source locations to display notes correctly.
5111class FormatStringLiteral {
5112 const StringLiteral *FExpr;
5113 int64_t Offset;
5114
5115 public:
5116 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
5117 : FExpr(fexpr), Offset(Offset) {}
5118
5119 StringRef getString() const {
5120 return FExpr->getString().drop_front(Offset);
5121 }
5122
5123 unsigned getByteLength() const {
5124 return FExpr->getByteLength() - getCharByteWidth() * Offset;
5125 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005126
Stephen Hines648c3692016-09-16 01:07:04 +00005127 unsigned getLength() const { return FExpr->getLength() - Offset; }
5128 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
5129
5130 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
5131
5132 QualType getType() const { return FExpr->getType(); }
5133
5134 bool isAscii() const { return FExpr->isAscii(); }
5135 bool isWide() const { return FExpr->isWide(); }
5136 bool isUTF8() const { return FExpr->isUTF8(); }
5137 bool isUTF16() const { return FExpr->isUTF16(); }
5138 bool isUTF32() const { return FExpr->isUTF32(); }
5139 bool isPascal() const { return FExpr->isPascal(); }
5140
5141 SourceLocation getLocationOfByte(
5142 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
5143 const TargetInfo &Target, unsigned *StartToken = nullptr,
5144 unsigned *StartTokenByteOffset = nullptr) const {
5145 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
5146 StartToken, StartTokenByteOffset);
5147 }
5148
5149 SourceLocation getLocStart() const LLVM_READONLY {
5150 return FExpr->getLocStart().getLocWithOffset(Offset);
5151 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005152
Stephen Hines648c3692016-09-16 01:07:04 +00005153 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
5154};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005155
5156} // namespace
Stephen Hines648c3692016-09-16 01:07:04 +00005157
5158static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005159 const Expr *OrigFormatExpr,
5160 ArrayRef<const Expr *> Args,
5161 bool HasVAListArg, unsigned format_idx,
5162 unsigned firstDataArg,
5163 Sema::FormatStringType Type,
5164 bool inFunctionCall,
5165 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005166 llvm::SmallBitVector &CheckedVarArgs,
5167 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005168
Richard Smith55ce3522012-06-25 20:30:08 +00005169// Determine if an expression is a string literal or constant string.
5170// If this function returns false on the arguments to a function expecting a
5171// format string, we will usually need to emit a warning.
5172// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00005173static StringLiteralCheckType
5174checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
5175 bool HasVAListArg, unsigned format_idx,
5176 unsigned firstDataArg, Sema::FormatStringType Type,
5177 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005178 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005179 UncoveredArgHandler &UncoveredArg,
5180 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00005181 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00005182 assert(Offset.isSigned() && "invalid offset");
5183
Douglas Gregorc25f7662009-05-19 22:10:17 +00005184 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00005185 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005186
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005187 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00005188
Richard Smithd7293d72013-08-05 18:49:43 +00005189 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00005190 // Technically -Wformat-nonliteral does not warn about this case.
5191 // The behavior of printf and friends in this case is implementation
5192 // dependent. Ideally if the format string cannot be null then
5193 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00005194 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00005195
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005196 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00005197 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005198 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00005199 // The expression is a literal if both sub-expressions were, and it was
5200 // completely checked only if both sub-expressions were checked.
5201 const AbstractConditionalOperator *C =
5202 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005203
5204 // Determine whether it is necessary to check both sub-expressions, for
5205 // example, because the condition expression is a constant that can be
5206 // evaluated at compile time.
5207 bool CheckLeft = true, CheckRight = true;
5208
5209 bool Cond;
5210 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
5211 if (Cond)
5212 CheckRight = false;
5213 else
5214 CheckLeft = false;
5215 }
5216
Stephen Hines648c3692016-09-16 01:07:04 +00005217 // We need to maintain the offsets for the right and the left hand side
5218 // separately to check if every possible indexed expression is a valid
5219 // string literal. They might have different offsets for different string
5220 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005221 StringLiteralCheckType Left;
5222 if (!CheckLeft)
5223 Left = SLCT_UncheckedLiteral;
5224 else {
5225 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
5226 HasVAListArg, format_idx, firstDataArg,
5227 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00005228 CheckedVarArgs, UncoveredArg, Offset);
5229 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005230 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00005231 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005232 }
5233
Richard Smith55ce3522012-06-25 20:30:08 +00005234 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00005235 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005236 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005237 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005238 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005239
5240 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005241 }
5242
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005243 case Stmt::ImplicitCastExprClass:
Ted Kremenek808829352010-09-09 03:51:39 +00005244 E = cast<ImplicitCastExpr>(E)->getSubExpr();
5245 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005246
John McCallc07a0c72011-02-17 10:25:35 +00005247 case Stmt::OpaqueValueExprClass:
5248 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
5249 E = src;
5250 goto tryAgain;
5251 }
Richard Smith55ce3522012-06-25 20:30:08 +00005252 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00005253
Ted Kremeneka8890832011-02-24 23:03:04 +00005254 case Stmt::PredefinedExprClass:
5255 // While __func__, etc., are technically not string literals, they
5256 // cannot contain format specifiers and thus are not a security
5257 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00005258 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00005259
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005260 case Stmt::DeclRefExprClass: {
5261 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005262
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005263 // As an exception, do not flag errors for variables binding to
5264 // const string literals.
5265 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
5266 bool isConstant = false;
5267 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005268
Richard Smithd7293d72013-08-05 18:49:43 +00005269 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
5270 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00005271 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00005272 isConstant = T.isConstant(S.Context) &&
5273 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00005274 } else if (T->isObjCObjectPointerType()) {
5275 // In ObjC, there is usually no "const ObjectPointer" type,
5276 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00005277 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005278 }
Mike Stump11289f42009-09-09 15:08:12 +00005279
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005280 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00005281 if (const Expr *Init = VD->getAnyInitializer()) {
5282 // Look through initializers like const char c[] = { "foo" }
5283 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
5284 if (InitList->isStringLiteralInit())
5285 Init = InitList->getInit(0)->IgnoreParenImpCasts();
5286 }
Richard Smithd7293d72013-08-05 18:49:43 +00005287 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005288 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005289 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005290 /*InFunctionCall*/ false, CheckedVarArgs,
5291 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00005292 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005293 }
Mike Stump11289f42009-09-09 15:08:12 +00005294
Anders Carlssonb012ca92009-06-28 19:55:58 +00005295 // For vprintf* functions (i.e., HasVAListArg==true), we add a
5296 // special check to see if the format string is a function parameter
5297 // of the function calling the printf function. If the function
5298 // has an attribute indicating it is a printf-like function, then we
5299 // should suppress warnings concerning non-literals being used in a call
5300 // to a vprintf function. For example:
5301 //
5302 // void
5303 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
5304 // va_list ap;
5305 // va_start(ap, fmt);
5306 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
5307 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00005308 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005309 if (HasVAListArg) {
5310 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
5311 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
5312 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00005313 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005314 // adjust for implicit parameter
5315 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5316 if (MD->isInstance())
5317 ++PVIndex;
5318 // We also check if the formats are compatible.
5319 // We can't pass a 'scanf' string to a 'printf' function.
5320 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00005321 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00005322 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005323 }
5324 }
5325 }
5326 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005327 }
Mike Stump11289f42009-09-09 15:08:12 +00005328
Richard Smith55ce3522012-06-25 20:30:08 +00005329 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005330 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005331
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005332 case Stmt::CallExprClass:
5333 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005334 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005335 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
5336 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00005337 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
Richard Smithd7293d72013-08-05 18:49:43 +00005338 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005339 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00005340 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00005341 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005342 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5343 unsigned BuiltinID = FD->getBuiltinID();
5344 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5345 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5346 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00005347 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005348 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005349 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005350 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005351 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005352 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005353 }
5354 }
Mike Stump11289f42009-09-09 15:08:12 +00005355
Richard Smith55ce3522012-06-25 20:30:08 +00005356 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005357 }
Alex Lorenzd9007142016-10-24 09:42:34 +00005358 case Stmt::ObjCMessageExprClass: {
5359 const auto *ME = cast<ObjCMessageExpr>(E);
5360 if (const auto *ND = ME->getMethodDecl()) {
5361 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00005362 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
Alex Lorenzd9007142016-10-24 09:42:34 +00005363 return checkFormatStringExpr(
5364 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5365 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5366 }
5367 }
5368
5369 return SLCT_NotALiteral;
5370 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005371 case Stmt::ObjCStringLiteralClass:
5372 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00005373 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005374
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005375 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005376 StrE = ObjCFExpr->getString();
5377 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005378 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005379
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005380 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005381 if (Offset.isNegative() || Offset > StrE->getLength()) {
5382 // TODO: It would be better to have an explicit warning for out of
5383 // bounds literals.
5384 return SLCT_NotALiteral;
5385 }
5386 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5387 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005388 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005389 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00005390 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005391 }
Mike Stump11289f42009-09-09 15:08:12 +00005392
Richard Smith55ce3522012-06-25 20:30:08 +00005393 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005394 }
Stephen Hines648c3692016-09-16 01:07:04 +00005395 case Stmt::BinaryOperatorClass: {
5396 llvm::APSInt LResult;
5397 llvm::APSInt RResult;
5398
5399 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5400
5401 // A string literal + an int offset is still a string literal.
5402 if (BinOp->isAdditiveOp()) {
5403 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5404 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5405
5406 if (LIsInt != RIsInt) {
5407 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5408
5409 if (LIsInt) {
5410 if (BinOpKind == BO_Add) {
5411 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5412 E = BinOp->getRHS();
5413 goto tryAgain;
5414 }
5415 } else {
5416 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5417 E = BinOp->getLHS();
5418 goto tryAgain;
5419 }
5420 }
Stephen Hines648c3692016-09-16 01:07:04 +00005421 }
George Burgess IVd273aab2016-09-22 00:00:26 +00005422
5423 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00005424 }
5425 case Stmt::UnaryOperatorClass: {
5426 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5427 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005428 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005429 llvm::APSInt IndexResult;
5430 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5431 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5432 E = ASE->getBase();
5433 goto tryAgain;
5434 }
5435 }
5436
5437 return SLCT_NotALiteral;
5438 }
Mike Stump11289f42009-09-09 15:08:12 +00005439
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005440 default:
Richard Smith55ce3522012-06-25 20:30:08 +00005441 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005442 }
5443}
5444
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005445Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00005446 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00005447 .Case("scanf", FST_Scanf)
5448 .Cases("printf", "printf0", FST_Printf)
5449 .Cases("NSString", "CFString", FST_NSString)
5450 .Case("strftime", FST_Strftime)
5451 .Case("strfmon", FST_Strfmon)
5452 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5453 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5454 .Case("os_trace", FST_OSLog)
5455 .Case("os_log", FST_OSLog)
5456 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005457}
5458
Jordan Rose3e0ec582012-07-19 18:10:23 +00005459/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00005460/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00005461/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005462bool Sema::CheckFormatArguments(const FormatAttr *Format,
5463 ArrayRef<const Expr *> Args,
5464 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005465 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005466 SourceLocation Loc, SourceRange Range,
5467 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00005468 FormatStringInfo FSI;
5469 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005470 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00005471 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00005472 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00005473 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005474}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00005475
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005476bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005477 bool HasVAListArg, unsigned format_idx,
5478 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005479 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005480 SourceLocation Loc, SourceRange Range,
5481 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00005482 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005483 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005484 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00005485 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005486 }
Mike Stump11289f42009-09-09 15:08:12 +00005487
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005488 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005489
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005490 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00005491 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005492 // Dynamically generated format strings are difficult to
5493 // automatically vet at compile time. Requiring that format strings
5494 // are string literals: (1) permits the checking of format strings by
5495 // the compiler and thereby (2) can practically remove the source of
5496 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00005497
Mike Stump11289f42009-09-09 15:08:12 +00005498 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00005499 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00005500 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00005501 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005502 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00005503 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00005504 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5505 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005506 /*IsFunctionCall*/ true, CheckedVarArgs,
5507 UncoveredArg,
5508 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005509
5510 // Generate a diagnostic where an uncovered argument is detected.
5511 if (UncoveredArg.hasUncoveredArg()) {
5512 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5513 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5514 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5515 }
5516
Richard Smith55ce3522012-06-25 20:30:08 +00005517 if (CT != SLCT_NotALiteral)
5518 // Literal format string found, check done!
5519 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00005520
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005521 // Strftime is particular as it always uses a single 'time' argument,
5522 // so it is safe to pass a non-literal string.
5523 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00005524 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005525
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005526 // Do not emit diag when the string param is a macro expansion and the
5527 // format is either NSString or CFString. This is a hack to prevent
5528 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5529 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005530 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5531 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00005532 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005533
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005534 // If there are no arguments specified, warn with -Wformat-security, otherwise
5535 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005536 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00005537 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5538 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005539 switch (Type) {
5540 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005541 break;
5542 case FST_Kprintf:
5543 case FST_FreeBSDKPrintf:
5544 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00005545 Diag(FormatLoc, diag::note_format_security_fixit)
5546 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005547 break;
5548 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00005549 Diag(FormatLoc, diag::note_format_security_fixit)
5550 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005551 break;
5552 }
5553 } else {
5554 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005555 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005556 }
Richard Smith55ce3522012-06-25 20:30:08 +00005557 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005558}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005559
Ted Kremenekab278de2010-01-28 23:39:18 +00005560namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005561
Ted Kremenek02087932010-07-16 02:11:22 +00005562class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5563protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00005564 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00005565 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00005566 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005567 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00005568 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00005569 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00005570 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00005571 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005572 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00005573 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00005574 llvm::SmallBitVector CoveredArgs;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005575 bool usesPositionalArgs = false;
5576 bool atFirstArg = true;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005577 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00005578 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00005579 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005580 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005581
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005582public:
Stephen Hines648c3692016-09-16 01:07:04 +00005583 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005584 const Expr *origFormatExpr,
5585 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005586 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005587 ArrayRef<const Expr *> Args, unsigned formatIdx,
5588 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005589 llvm::SmallBitVector &CheckedVarArgs,
5590 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005591 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5592 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5593 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
Mehdi Amini06d367c2016-10-24 20:39:34 +00005594 inFunctionCall(inFunctionCall), CallType(callType),
5595 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00005596 CoveredArgs.resize(numDataArgs);
5597 CoveredArgs.reset();
5598 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005599
Ted Kremenek019d2242010-01-29 01:50:07 +00005600 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005601
Ted Kremenek02087932010-07-16 02:11:22 +00005602 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005603 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005604
Jordan Rose92303592012-09-08 04:00:03 +00005605 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005606 const analyze_format_string::FormatSpecifier &FS,
5607 const analyze_format_string::ConversionSpecifier &CS,
5608 const char *startSpecifier, unsigned specifierLen,
5609 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00005610
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005611 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005612 const analyze_format_string::FormatSpecifier &FS,
5613 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005614
5615 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005616 const analyze_format_string::ConversionSpecifier &CS,
5617 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005618
Craig Toppere14c0f82014-03-12 04:55:44 +00005619 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005620
Craig Toppere14c0f82014-03-12 04:55:44 +00005621 void HandleInvalidPosition(const char *startSpecifier,
5622 unsigned specifierLen,
5623 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005624
Craig Toppere14c0f82014-03-12 04:55:44 +00005625 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005626
Craig Toppere14c0f82014-03-12 04:55:44 +00005627 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005628
Richard Trieu03cf7b72011-10-28 00:41:25 +00005629 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00005630 static void
5631 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5632 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5633 bool IsStringLocation, Range StringRange,
5634 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005635
Ted Kremenek02087932010-07-16 02:11:22 +00005636protected:
Ted Kremenekce815422010-07-19 21:25:57 +00005637 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5638 const char *startSpec,
5639 unsigned specifierLen,
5640 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005641
5642 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5643 const char *startSpec,
5644 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00005645
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005646 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00005647 CharSourceRange getSpecifierRange(const char *startSpecifier,
5648 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00005649 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005650
Ted Kremenek5739de72010-01-29 01:06:55 +00005651 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005652
5653 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5654 const analyze_format_string::ConversionSpecifier &CS,
5655 const char *startSpecifier, unsigned specifierLen,
5656 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005657
5658 template <typename Range>
5659 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5660 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005661 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00005662};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005663
5664} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005665
Ted Kremenek02087932010-07-16 02:11:22 +00005666SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00005667 return OrigFormatExpr->getSourceRange();
5668}
5669
Ted Kremenek02087932010-07-16 02:11:22 +00005670CharSourceRange CheckFormatHandler::
5671getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00005672 SourceLocation Start = getLocationOfByte(startSpecifier);
5673 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5674
5675 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00005676 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00005677
5678 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005679}
5680
Ted Kremenek02087932010-07-16 02:11:22 +00005681SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00005682 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5683 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00005684}
5685
Ted Kremenek02087932010-07-16 02:11:22 +00005686void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5687 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00005688 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5689 getLocationOfByte(startSpecifier),
5690 /*IsStringLocation*/true,
5691 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00005692}
5693
Jordan Rose92303592012-09-08 04:00:03 +00005694void CheckFormatHandler::HandleInvalidLengthModifier(
5695 const analyze_format_string::FormatSpecifier &FS,
5696 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00005697 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00005698 using namespace analyze_format_string;
5699
5700 const LengthModifier &LM = FS.getLengthModifier();
5701 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5702
5703 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005704 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00005705 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005706 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005707 getLocationOfByte(LM.getStart()),
5708 /*IsStringLocation*/true,
5709 getSpecifierRange(startSpecifier, specifierLen));
5710
5711 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5712 << FixedLM->toString()
5713 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5714
5715 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005716 FixItHint Hint;
5717 if (DiagID == diag::warn_format_nonsensical_length)
5718 Hint = FixItHint::CreateRemoval(LMRange);
5719
5720 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005721 getLocationOfByte(LM.getStart()),
5722 /*IsStringLocation*/true,
5723 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00005724 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00005725 }
5726}
5727
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005728void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005729 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005730 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005731 using namespace analyze_format_string;
5732
5733 const LengthModifier &LM = FS.getLengthModifier();
5734 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5735
5736 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005737 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005738 if (FixedLM) {
5739 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5740 << LM.toString() << 0,
5741 getLocationOfByte(LM.getStart()),
5742 /*IsStringLocation*/true,
5743 getSpecifierRange(startSpecifier, specifierLen));
5744
5745 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5746 << FixedLM->toString()
5747 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5748
5749 } else {
5750 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5751 << LM.toString() << 0,
5752 getLocationOfByte(LM.getStart()),
5753 /*IsStringLocation*/true,
5754 getSpecifierRange(startSpecifier, specifierLen));
5755 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005756}
5757
5758void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5759 const analyze_format_string::ConversionSpecifier &CS,
5760 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005761 using namespace analyze_format_string;
5762
5763 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005764 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005765 if (FixedCS) {
5766 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5767 << CS.toString() << /*conversion specifier*/1,
5768 getLocationOfByte(CS.getStart()),
5769 /*IsStringLocation*/true,
5770 getSpecifierRange(startSpecifier, specifierLen));
5771
5772 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5773 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5774 << FixedCS->toString()
5775 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5776 } else {
5777 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5778 << CS.toString() << /*conversion specifier*/1,
5779 getLocationOfByte(CS.getStart()),
5780 /*IsStringLocation*/true,
5781 getSpecifierRange(startSpecifier, specifierLen));
5782 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005783}
5784
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005785void CheckFormatHandler::HandlePosition(const char *startPos,
5786 unsigned posLen) {
5787 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5788 getLocationOfByte(startPos),
5789 /*IsStringLocation*/true,
5790 getSpecifierRange(startPos, posLen));
5791}
5792
Ted Kremenekd1668192010-02-27 01:41:03 +00005793void
Ted Kremenek02087932010-07-16 02:11:22 +00005794CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5795 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005796 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5797 << (unsigned) p,
5798 getLocationOfByte(startPos), /*IsStringLocation*/true,
5799 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005800}
5801
Ted Kremenek02087932010-07-16 02:11:22 +00005802void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005803 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005804 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5805 getLocationOfByte(startPos),
5806 /*IsStringLocation*/true,
5807 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005808}
5809
Ted Kremenek02087932010-07-16 02:11:22 +00005810void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005811 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005812 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005813 EmitFormatDiagnostic(
5814 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5815 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5816 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005817 }
Ted Kremenek02087932010-07-16 02:11:22 +00005818}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005819
Jordan Rose58bbe422012-07-19 18:10:08 +00005820// Note that this may return NULL if there was an error parsing or building
5821// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005822const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005823 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005824}
5825
5826void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005827 // Does the number of data arguments exceed the number of
5828 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005829 if (!HasVAListArg) {
5830 // Find any arguments that weren't covered.
5831 CoveredArgs.flip();
5832 signed notCoveredArg = CoveredArgs.find_first();
5833 if (notCoveredArg >= 0) {
5834 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005835 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5836 } else {
5837 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005838 }
5839 }
5840}
5841
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005842void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5843 const Expr *ArgExpr) {
5844 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5845 "Invalid state");
5846
5847 if (!ArgExpr)
5848 return;
5849
5850 SourceLocation Loc = ArgExpr->getLocStart();
5851
5852 if (S.getSourceManager().isInSystemMacro(Loc))
5853 return;
5854
5855 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5856 for (auto E : DiagnosticExprs)
5857 PDiag << E->getSourceRange();
5858
5859 CheckFormatHandler::EmitFormatDiagnostic(
5860 S, IsFunctionCall, DiagnosticExprs[0],
5861 PDiag, Loc, /*IsStringLocation*/false,
5862 DiagnosticExprs[0]->getSourceRange());
5863}
5864
Ted Kremenekce815422010-07-19 21:25:57 +00005865bool
5866CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5867 SourceLocation Loc,
5868 const char *startSpec,
5869 unsigned specifierLen,
5870 const char *csStart,
5871 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005872 bool keepGoing = true;
5873 if (argIndex < NumDataArgs) {
5874 // Consider the argument coverered, even though the specifier doesn't
5875 // make sense.
5876 CoveredArgs.set(argIndex);
5877 }
5878 else {
5879 // If argIndex exceeds the number of data arguments we
5880 // don't issue a warning because that is just a cascade of warnings (and
5881 // they may have intended '%%' anyway). We don't want to continue processing
5882 // the format string after this point, however, as we will like just get
5883 // gibberish when trying to match arguments.
5884 keepGoing = false;
5885 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005886
5887 StringRef Specifier(csStart, csLen);
5888
5889 // If the specifier in non-printable, it could be the first byte of a UTF-8
5890 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5891 // hex value.
5892 std::string CodePointStr;
5893 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005894 llvm::UTF32 CodePoint;
5895 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5896 const llvm::UTF8 *E =
5897 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5898 llvm::ConversionResult Result =
5899 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005900
Justin Lebar90910552016-09-30 00:38:45 +00005901 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005902 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005903 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005904 }
5905
5906 llvm::raw_string_ostream OS(CodePointStr);
5907 if (CodePoint < 256)
5908 OS << "\\x" << llvm::format("%02x", CodePoint);
5909 else if (CodePoint <= 0xFFFF)
5910 OS << "\\u" << llvm::format("%04x", CodePoint);
5911 else
5912 OS << "\\U" << llvm::format("%08x", CodePoint);
5913 OS.flush();
5914 Specifier = CodePointStr;
5915 }
5916
5917 EmitFormatDiagnostic(
5918 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5919 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5920
Ted Kremenekce815422010-07-19 21:25:57 +00005921 return keepGoing;
5922}
5923
Richard Trieu03cf7b72011-10-28 00:41:25 +00005924void
5925CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5926 const char *startSpec,
5927 unsigned specifierLen) {
5928 EmitFormatDiagnostic(
5929 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5930 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5931}
5932
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005933bool
5934CheckFormatHandler::CheckNumArgs(
5935 const analyze_format_string::FormatSpecifier &FS,
5936 const analyze_format_string::ConversionSpecifier &CS,
5937 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5938
5939 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005940 PartialDiagnostic PDiag = FS.usesPositionalArg()
5941 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5942 << (argIndex+1) << NumDataArgs)
5943 : S.PDiag(diag::warn_printf_insufficient_data_args);
5944 EmitFormatDiagnostic(
5945 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5946 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005947
5948 // Since more arguments than conversion tokens are given, by extension
5949 // all arguments are covered, so mark this as so.
5950 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005951 return false;
5952 }
5953 return true;
5954}
5955
Richard Trieu03cf7b72011-10-28 00:41:25 +00005956template<typename Range>
5957void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5958 SourceLocation Loc,
5959 bool IsStringLocation,
5960 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005961 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005962 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005963 Loc, IsStringLocation, StringRange, FixIt);
5964}
5965
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005966/// If the format string is not within the function call, emit a note
Richard Trieu03cf7b72011-10-28 00:41:25 +00005967/// so that the function call and string are in diagnostic messages.
5968///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005969/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005970/// call and only one diagnostic message will be produced. Otherwise, an
5971/// extra note will be emitted pointing to location of the format string.
5972///
5973/// \param ArgumentExpr the expression that is passed as the format string
5974/// argument in the function call. Used for getting locations when two
5975/// diagnostics are emitted.
5976///
5977/// \param PDiag the callee should already have provided any strings for the
5978/// diagnostic message. This function only adds locations and fixits
5979/// to diagnostics.
5980///
5981/// \param Loc primary location for diagnostic. If two diagnostics are
5982/// required, one will be at Loc and a new SourceLocation will be created for
5983/// the other one.
5984///
5985/// \param IsStringLocation if true, Loc points to the format string should be
5986/// used for the note. Otherwise, Loc points to the argument list and will
5987/// be used with PDiag.
5988///
5989/// \param StringRange some or all of the string to highlight. This is
5990/// templated so it can accept either a CharSourceRange or a SourceRange.
5991///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005992/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005993template <typename Range>
5994void CheckFormatHandler::EmitFormatDiagnostic(
5995 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5996 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5997 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005998 if (InFunctionCall) {
5999 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
6000 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00006001 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00006002 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006003 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
6004 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00006005
6006 const Sema::SemaDiagnosticBuilder &Note =
6007 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
6008 diag::note_format_string_defined);
6009
6010 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00006011 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00006012 }
6013}
6014
Ted Kremenek02087932010-07-16 02:11:22 +00006015//===--- CHECK: Printf format string checking ------------------------------===//
6016
6017namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006018
Ted Kremenek02087932010-07-16 02:11:22 +00006019class CheckPrintfHandler : public CheckFormatHandler {
6020public:
Stephen Hines648c3692016-09-16 01:07:04 +00006021 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006022 const Expr *origFormatExpr,
6023 const Sema::FormatStringType type, unsigned firstDataArg,
6024 unsigned numDataArgs, bool isObjC, const char *beg,
6025 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006026 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00006027 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006028 llvm::SmallBitVector &CheckedVarArgs,
6029 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006030 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6031 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6032 inFunctionCall, CallType, CheckedVarArgs,
6033 UncoveredArg) {}
6034
6035 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
6036
6037 /// Returns true if '%@' specifiers are allowed in the format string.
6038 bool allowsObjCArg() const {
6039 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
6040 FSType == Sema::FST_OSTrace;
6041 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00006042
Ted Kremenek02087932010-07-16 02:11:22 +00006043 bool HandleInvalidPrintfConversionSpecifier(
6044 const analyze_printf::PrintfSpecifier &FS,
6045 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006046 unsigned specifierLen) override;
6047
Ted Kremenek02087932010-07-16 02:11:22 +00006048 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
6049 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006050 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00006051 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6052 const char *StartSpecifier,
6053 unsigned SpecifierLen,
6054 const Expr *E);
6055
Ted Kremenek02087932010-07-16 02:11:22 +00006056 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
6057 const char *startSpecifier, unsigned specifierLen);
6058 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
6059 const analyze_printf::OptionalAmount &Amt,
6060 unsigned type,
6061 const char *startSpecifier, unsigned specifierLen);
6062 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
6063 const analyze_printf::OptionalFlag &flag,
6064 const char *startSpecifier, unsigned specifierLen);
6065 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
6066 const analyze_printf::OptionalFlag &ignoredFlag,
6067 const analyze_printf::OptionalFlag &flag,
6068 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006069 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00006070 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00006071
6072 void HandleEmptyObjCModifierFlag(const char *startFlag,
6073 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00006074
Ted Kremenek2b417712015-07-02 05:39:16 +00006075 void HandleInvalidObjCModifierFlag(const char *startFlag,
6076 unsigned flagLen) override;
6077
6078 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
6079 const char *flagsEnd,
6080 const char *conversionPosition)
6081 override;
6082};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006083
6084} // namespace
Ted Kremenek02087932010-07-16 02:11:22 +00006085
6086bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
6087 const analyze_printf::PrintfSpecifier &FS,
6088 const char *startSpecifier,
6089 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006090 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006091 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006092
Ted Kremenekce815422010-07-19 21:25:57 +00006093 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6094 getLocationOfByte(CS.getStart()),
6095 startSpecifier, specifierLen,
6096 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00006097}
6098
Ted Kremenek02087932010-07-16 02:11:22 +00006099bool CheckPrintfHandler::HandleAmount(
6100 const analyze_format_string::OptionalAmount &Amt,
6101 unsigned k, const char *startSpecifier,
6102 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006103 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006104 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00006105 unsigned argIndex = Amt.getArgIndex();
6106 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006107 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
6108 << k,
6109 getLocationOfByte(Amt.getStart()),
6110 /*IsStringLocation*/true,
6111 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00006112 // Don't do any more checking. We will just emit
6113 // spurious errors.
6114 return false;
6115 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006116
Ted Kremenek5739de72010-01-29 01:06:55 +00006117 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00006118 // Although not in conformance with C99, we also allow the argument to be
6119 // an 'unsigned int' as that is a reasonably safe case. GCC also
6120 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00006121 CoveredArgs.set(argIndex);
6122 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006123 if (!Arg)
6124 return false;
6125
Ted Kremenek5739de72010-01-29 01:06:55 +00006126 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006127
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006128 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
6129 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006130
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006131 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006132 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006133 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00006134 << T << Arg->getSourceRange(),
6135 getLocationOfByte(Amt.getStart()),
6136 /*IsStringLocation*/true,
6137 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00006138 // Don't do any more checking. We will just emit
6139 // spurious errors.
6140 return false;
6141 }
6142 }
6143 }
6144 return true;
6145}
Ted Kremenek5739de72010-01-29 01:06:55 +00006146
Tom Careb49ec692010-06-17 19:00:27 +00006147void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00006148 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006149 const analyze_printf::OptionalAmount &Amt,
6150 unsigned type,
6151 const char *startSpecifier,
6152 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006153 const analyze_printf::PrintfConversionSpecifier &CS =
6154 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00006155
Richard Trieu03cf7b72011-10-28 00:41:25 +00006156 FixItHint fixit =
6157 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
6158 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
6159 Amt.getConstantLength()))
6160 : FixItHint();
6161
6162 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
6163 << type << CS.toString(),
6164 getLocationOfByte(Amt.getStart()),
6165 /*IsStringLocation*/true,
6166 getSpecifierRange(startSpecifier, specifierLen),
6167 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00006168}
6169
Ted Kremenek02087932010-07-16 02:11:22 +00006170void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006171 const analyze_printf::OptionalFlag &flag,
6172 const char *startSpecifier,
6173 unsigned specifierLen) {
6174 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006175 const analyze_printf::PrintfConversionSpecifier &CS =
6176 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00006177 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
6178 << flag.toString() << CS.toString(),
6179 getLocationOfByte(flag.getPosition()),
6180 /*IsStringLocation*/true,
6181 getSpecifierRange(startSpecifier, specifierLen),
6182 FixItHint::CreateRemoval(
6183 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00006184}
6185
6186void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00006187 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006188 const analyze_printf::OptionalFlag &ignoredFlag,
6189 const analyze_printf::OptionalFlag &flag,
6190 const char *startSpecifier,
6191 unsigned specifierLen) {
6192 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00006193 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
6194 << ignoredFlag.toString() << flag.toString(),
6195 getLocationOfByte(ignoredFlag.getPosition()),
6196 /*IsStringLocation*/true,
6197 getSpecifierRange(startSpecifier, specifierLen),
6198 FixItHint::CreateRemoval(
6199 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00006200}
6201
Ted Kremenek2b417712015-07-02 05:39:16 +00006202void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
6203 unsigned flagLen) {
6204 // Warn about an empty flag.
6205 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
6206 getLocationOfByte(startFlag),
6207 /*IsStringLocation*/true,
6208 getSpecifierRange(startFlag, flagLen));
6209}
6210
6211void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
6212 unsigned flagLen) {
6213 // Warn about an invalid flag.
6214 auto Range = getSpecifierRange(startFlag, flagLen);
6215 StringRef flag(startFlag, flagLen);
6216 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
6217 getLocationOfByte(startFlag),
6218 /*IsStringLocation*/true,
6219 Range, FixItHint::CreateRemoval(Range));
6220}
6221
6222void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
6223 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
6224 // Warn about using '[...]' without a '@' conversion.
6225 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
6226 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
6227 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
6228 getLocationOfByte(conversionPosition),
6229 /*IsStringLocation*/true,
6230 Range, FixItHint::CreateRemoval(Range));
6231}
6232
Richard Smith55ce3522012-06-25 20:30:08 +00006233// Determines if the specified is a C++ class or struct containing
6234// a member with the specified name and kind (e.g. a CXXMethodDecl named
6235// "c_str()").
6236template<typename MemberKind>
6237static llvm::SmallPtrSet<MemberKind*, 1>
6238CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
6239 const RecordType *RT = Ty->getAs<RecordType>();
6240 llvm::SmallPtrSet<MemberKind*, 1> Results;
6241
6242 if (!RT)
6243 return Results;
6244 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00006245 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00006246 return Results;
6247
Alp Tokerb6cc5922014-05-03 03:45:55 +00006248 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00006249 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00006250 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00006251
6252 // We just need to include all members of the right kind turned up by the
6253 // filter, at this point.
6254 if (S.LookupQualifiedName(R, RT->getDecl()))
6255 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6256 NamedDecl *decl = (*I)->getUnderlyingDecl();
6257 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
6258 Results.insert(FK);
6259 }
6260 return Results;
6261}
6262
Richard Smith2868a732014-02-28 01:36:39 +00006263/// Check if we could call '.c_str()' on an object.
6264///
6265/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
6266/// allow the call, or if it would be ambiguous).
6267bool Sema::hasCStrMethod(const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006268 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
6269
Richard Smith2868a732014-02-28 01:36:39 +00006270 MethodSet Results =
6271 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
6272 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6273 MI != ME; ++MI)
6274 if ((*MI)->getMinRequiredArguments() == 0)
6275 return true;
6276 return false;
6277}
6278
Richard Smith55ce3522012-06-25 20:30:08 +00006279// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006280// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00006281// Returns true when a c_str() conversion method is found.
6282bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00006283 const analyze_printf::ArgType &AT, const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006284 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
Richard Smith55ce3522012-06-25 20:30:08 +00006285
6286 MethodSet Results =
6287 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
6288
6289 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6290 MI != ME; ++MI) {
6291 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00006292 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00006293 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00006294 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00006295 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00006296 S.Diag(E->getLocStart(), diag::note_printf_c_str)
6297 << "c_str()"
6298 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
6299 return true;
6300 }
6301 }
6302
6303 return false;
6304}
6305
Ted Kremenekab278de2010-01-28 23:39:18 +00006306bool
Ted Kremenek02087932010-07-16 02:11:22 +00006307CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00006308 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00006309 const char *startSpecifier,
6310 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006311 using namespace analyze_format_string;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006312 using namespace analyze_printf;
6313
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006314 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00006315
Ted Kremenek6cd69422010-07-19 22:01:06 +00006316 if (FS.consumesDataArgument()) {
6317 if (atFirstArg) {
6318 atFirstArg = false;
6319 usesPositionalArgs = FS.usesPositionalArg();
6320 }
6321 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006322 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6323 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006324 return false;
6325 }
Ted Kremenek5739de72010-01-29 01:06:55 +00006326 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006327
Ted Kremenekd1668192010-02-27 01:41:03 +00006328 // First check if the field width, precision, and conversion specifier
6329 // have matching data arguments.
6330 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
6331 startSpecifier, specifierLen)) {
6332 return false;
6333 }
6334
6335 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
6336 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006337 return false;
6338 }
6339
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006340 if (!CS.consumesDataArgument()) {
6341 // FIXME: Technically specifying a precision or field width here
6342 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00006343 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006344 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006345
Ted Kremenek4a49d982010-02-26 19:18:41 +00006346 // Consume the argument.
6347 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00006348 if (argIndex < NumDataArgs) {
6349 // The check to see if the argIndex is valid will come later.
6350 // We set the bit here because we may exit early from this
6351 // function if we encounter some other error.
6352 CoveredArgs.set(argIndex);
6353 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00006354
Dimitry Andric6b5ed342015-02-19 22:32:33 +00006355 // FreeBSD kernel extensions.
6356 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6357 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6358 // We need at least two arguments.
6359 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6360 return false;
6361
6362 // Claim the second argument.
6363 CoveredArgs.set(argIndex + 1);
6364
6365 // Type check the first argument (int for %b, pointer for %D)
6366 const Expr *Ex = getDataArg(argIndex);
6367 const analyze_printf::ArgType &AT =
6368 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6369 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6370 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6371 EmitFormatDiagnostic(
6372 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6373 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6374 << false << Ex->getSourceRange(),
6375 Ex->getLocStart(), /*IsStringLocation*/false,
6376 getSpecifierRange(startSpecifier, specifierLen));
6377
6378 // Type check the second argument (char * for both %b and %D)
6379 Ex = getDataArg(argIndex + 1);
6380 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6381 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6382 EmitFormatDiagnostic(
6383 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6384 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6385 << false << Ex->getSourceRange(),
6386 Ex->getLocStart(), /*IsStringLocation*/false,
6387 getSpecifierRange(startSpecifier, specifierLen));
6388
6389 return true;
6390 }
6391
Ted Kremenek4a49d982010-02-26 19:18:41 +00006392 // Check for using an Objective-C specific conversion specifier
6393 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006394 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00006395 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6396 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00006397 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006398
Mehdi Amini06d367c2016-10-24 20:39:34 +00006399 // %P can only be used with os_log.
6400 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6401 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6402 specifierLen);
6403 }
6404
6405 // %n is not allowed with os_log.
6406 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6407 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6408 getLocationOfByte(CS.getStart()),
6409 /*IsStringLocation*/ false,
6410 getSpecifierRange(startSpecifier, specifierLen));
6411
6412 return true;
6413 }
6414
6415 // Only scalars are allowed for os_trace.
6416 if (FSType == Sema::FST_OSTrace &&
6417 (CS.getKind() == ConversionSpecifier::PArg ||
6418 CS.getKind() == ConversionSpecifier::sArg ||
6419 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6420 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6421 specifierLen);
6422 }
6423
6424 // Check for use of public/private annotation outside of os_log().
6425 if (FSType != Sema::FST_OSLog) {
6426 if (FS.isPublic().isSet()) {
6427 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6428 << "public",
6429 getLocationOfByte(FS.isPublic().getPosition()),
6430 /*IsStringLocation*/ false,
6431 getSpecifierRange(startSpecifier, specifierLen));
6432 }
6433 if (FS.isPrivate().isSet()) {
6434 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6435 << "private",
6436 getLocationOfByte(FS.isPrivate().getPosition()),
6437 /*IsStringLocation*/ false,
6438 getSpecifierRange(startSpecifier, specifierLen));
6439 }
6440 }
6441
Tom Careb49ec692010-06-17 19:00:27 +00006442 // Check for invalid use of field width
6443 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00006444 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00006445 startSpecifier, specifierLen);
6446 }
6447
6448 // Check for invalid use of precision
6449 if (!FS.hasValidPrecision()) {
6450 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6451 startSpecifier, specifierLen);
6452 }
6453
Mehdi Amini06d367c2016-10-24 20:39:34 +00006454 // Precision is mandatory for %P specifier.
6455 if (CS.getKind() == ConversionSpecifier::PArg &&
6456 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6457 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6458 getLocationOfByte(startSpecifier),
6459 /*IsStringLocation*/ false,
6460 getSpecifierRange(startSpecifier, specifierLen));
6461 }
6462
Tom Careb49ec692010-06-17 19:00:27 +00006463 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00006464 if (!FS.hasValidThousandsGroupingPrefix())
6465 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006466 if (!FS.hasValidLeadingZeros())
6467 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6468 if (!FS.hasValidPlusPrefix())
6469 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00006470 if (!FS.hasValidSpacePrefix())
6471 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006472 if (!FS.hasValidAlternativeForm())
6473 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6474 if (!FS.hasValidLeftJustified())
6475 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6476
6477 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00006478 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6479 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6480 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006481 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6482 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6483 startSpecifier, specifierLen);
6484
6485 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006486 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006487 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6488 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006489 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006490 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006491 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006492 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6493 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00006494
Jordan Rose92303592012-09-08 04:00:03 +00006495 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6496 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6497
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006498 // The remaining checks depend on the data arguments.
6499 if (HasVAListArg)
6500 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006501
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006502 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006503 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006504
Jordan Rose58bbe422012-07-19 18:10:08 +00006505 const Expr *Arg = getDataArg(argIndex);
6506 if (!Arg)
6507 return true;
6508
6509 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00006510}
6511
Jordan Roseaee34382012-09-05 22:56:26 +00006512static bool requiresParensToAddCast(const Expr *E) {
6513 // FIXME: We should have a general way to reason about operator
6514 // precedence and whether parens are actually needed here.
6515 // Take care of a few common cases where they aren't.
6516 const Expr *Inside = E->IgnoreImpCasts();
6517 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6518 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6519
6520 switch (Inside->getStmtClass()) {
6521 case Stmt::ArraySubscriptExprClass:
6522 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006523 case Stmt::CharacterLiteralClass:
6524 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006525 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006526 case Stmt::FloatingLiteralClass:
6527 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006528 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006529 case Stmt::ObjCArrayLiteralClass:
6530 case Stmt::ObjCBoolLiteralExprClass:
6531 case Stmt::ObjCBoxedExprClass:
6532 case Stmt::ObjCDictionaryLiteralClass:
6533 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006534 case Stmt::ObjCIvarRefExprClass:
6535 case Stmt::ObjCMessageExprClass:
6536 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006537 case Stmt::ObjCStringLiteralClass:
6538 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006539 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006540 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006541 case Stmt::UnaryOperatorClass:
6542 return false;
6543 default:
6544 return true;
6545 }
6546}
6547
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006548static std::pair<QualType, StringRef>
6549shouldNotPrintDirectly(const ASTContext &Context,
6550 QualType IntendedTy,
6551 const Expr *E) {
6552 // Use a 'while' to peel off layers of typedefs.
6553 QualType TyTy = IntendedTy;
6554 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6555 StringRef Name = UserTy->getDecl()->getName();
6556 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Saleem Abdulrasoola01ed932017-10-17 17:39:32 +00006557 .Case("CFIndex", Context.getNSIntegerType())
6558 .Case("NSInteger", Context.getNSIntegerType())
6559 .Case("NSUInteger", Context.getNSUIntegerType())
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006560 .Case("SInt32", Context.IntTy)
6561 .Case("UInt32", Context.UnsignedIntTy)
6562 .Default(QualType());
6563
6564 if (!CastTy.isNull())
6565 return std::make_pair(CastTy, Name);
6566
6567 TyTy = UserTy->desugar();
6568 }
6569
6570 // Strip parens if necessary.
6571 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6572 return shouldNotPrintDirectly(Context,
6573 PE->getSubExpr()->getType(),
6574 PE->getSubExpr());
6575
6576 // If this is a conditional expression, then its result type is constructed
6577 // via usual arithmetic conversions and thus there might be no necessary
6578 // typedef sugar there. Recurse to operands to check for NSInteger &
6579 // Co. usage condition.
6580 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6581 QualType TrueTy, FalseTy;
6582 StringRef TrueName, FalseName;
6583
6584 std::tie(TrueTy, TrueName) =
6585 shouldNotPrintDirectly(Context,
6586 CO->getTrueExpr()->getType(),
6587 CO->getTrueExpr());
6588 std::tie(FalseTy, FalseName) =
6589 shouldNotPrintDirectly(Context,
6590 CO->getFalseExpr()->getType(),
6591 CO->getFalseExpr());
6592
6593 if (TrueTy == FalseTy)
6594 return std::make_pair(TrueTy, TrueName);
6595 else if (TrueTy.isNull())
6596 return std::make_pair(FalseTy, FalseName);
6597 else if (FalseTy.isNull())
6598 return std::make_pair(TrueTy, TrueName);
6599 }
6600
6601 return std::make_pair(QualType(), StringRef());
6602}
6603
Richard Smith55ce3522012-06-25 20:30:08 +00006604bool
6605CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6606 const char *StartSpecifier,
6607 unsigned SpecifierLen,
6608 const Expr *E) {
6609 using namespace analyze_format_string;
6610 using namespace analyze_printf;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006611
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006612 // Now type check the data expression that matches the
6613 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006614 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00006615 if (!AT.isValid())
6616 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00006617
Jordan Rose598ec092012-12-05 18:44:40 +00006618 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00006619 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6620 ExprTy = TET->getUnderlyingExpr()->getType();
6621 }
6622
Seth Cantrellb4802962015-03-04 03:12:10 +00006623 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6624
6625 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00006626 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006627 }
Jordan Rose98709982012-06-04 22:48:57 +00006628
Jordan Rose22b74712012-09-05 22:56:19 +00006629 // Look through argument promotions for our error message's reported type.
6630 // This includes the integral and floating promotions, but excludes array
6631 // and function pointer decay; seeing that an argument intended to be a
6632 // string has type 'char [6]' is probably more confusing than 'char *'.
6633 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6634 if (ICE->getCastKind() == CK_IntegralCast ||
6635 ICE->getCastKind() == CK_FloatingCast) {
6636 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006637 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006638
6639 // Check if we didn't match because of an implicit cast from a 'char'
6640 // or 'short' to an 'int'. This is done because printf is a varargs
6641 // function.
6642 if (ICE->getType() == S.Context.IntTy ||
6643 ICE->getType() == S.Context.UnsignedIntTy) {
6644 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006645 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006646 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006647 }
Jordan Rose98709982012-06-04 22:48:57 +00006648 }
Jordan Rose598ec092012-12-05 18:44:40 +00006649 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6650 // Special case for 'a', which has type 'int' in C.
6651 // Note, however, that we do /not/ want to treat multibyte constants like
6652 // 'MooV' as characters! This form is deprecated but still exists.
6653 if (ExprTy == S.Context.IntTy)
6654 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6655 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006656 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006657
Jordan Rosebc53ed12014-05-31 04:12:14 +00006658 // Look through enums to their underlying type.
6659 bool IsEnum = false;
6660 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6661 ExprTy = EnumTy->getDecl()->getIntegerType();
6662 IsEnum = true;
6663 }
6664
Jordan Rose0e5badd2012-12-05 18:44:49 +00006665 // %C in an Objective-C context prints a unichar, not a wchar_t.
6666 // If the argument is an integer of some kind, believe the %C and suggest
6667 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006668 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006669 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006670 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6671 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6672 !ExprTy->isCharType()) {
6673 // 'unichar' is defined as a typedef of unsigned short, but we should
6674 // prefer using the typedef if it is visible.
6675 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006676
6677 // While we are here, check if the value is an IntegerLiteral that happens
6678 // to be within the valid range.
6679 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6680 const llvm::APInt &V = IL->getValue();
6681 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6682 return true;
6683 }
6684
Jordan Rose0e5badd2012-12-05 18:44:49 +00006685 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6686 Sema::LookupOrdinaryName);
6687 if (S.LookupName(Result, S.getCurScope())) {
6688 NamedDecl *ND = Result.getFoundDecl();
6689 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6690 if (TD->getUnderlyingType() == IntendedTy)
6691 IntendedTy = S.Context.getTypedefType(TD);
6692 }
6693 }
6694 }
6695
6696 // Special-case some of Darwin's platform-independence types by suggesting
6697 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006698 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006699 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006700 QualType CastTy;
6701 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6702 if (!CastTy.isNull()) {
6703 IntendedTy = CastTy;
6704 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006705 }
6706 }
6707
Jordan Rose22b74712012-09-05 22:56:19 +00006708 // We may be able to offer a FixItHint if it is a supported type.
6709 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006710 bool success =
6711 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006712
Jordan Rose22b74712012-09-05 22:56:19 +00006713 if (success) {
6714 // Get the fix string from the fixed format specifier
6715 SmallString<16> buf;
6716 llvm::raw_svector_ostream os(buf);
6717 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006718
Jordan Roseaee34382012-09-05 22:56:26 +00006719 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6720
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006721 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00006722 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6723 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6724 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6725 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00006726 // In this case, the specifier is wrong and should be changed to match
6727 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006728 EmitFormatDiagnostic(S.PDiag(diag)
6729 << AT.getRepresentativeTypeName(S.Context)
6730 << IntendedTy << IsEnum << E->getSourceRange(),
6731 E->getLocStart(),
6732 /*IsStringLocation*/ false, SpecRange,
6733 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006734 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006735 // The canonical type for formatting this value is different from the
6736 // actual type of the expression. (This occurs, for example, with Darwin's
6737 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6738 // should be printed as 'long' for 64-bit compatibility.)
6739 // Rather than emitting a normal format/argument mismatch, we want to
6740 // add a cast to the recommended type (and correct the format string
6741 // if necessary).
6742 SmallString<16> CastBuf;
6743 llvm::raw_svector_ostream CastFix(CastBuf);
6744 CastFix << "(";
6745 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6746 CastFix << ")";
6747
6748 SmallVector<FixItHint,4> Hints;
Alexander Shaposhnikov1788a9b2017-09-22 18:36:06 +00006749 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
Jordan Roseaee34382012-09-05 22:56:26 +00006750 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6751
6752 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6753 // If there's already a cast present, just replace it.
6754 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6755 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6756
6757 } else if (!requiresParensToAddCast(E)) {
6758 // If the expression has high enough precedence,
6759 // just write the C-style cast.
6760 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6761 CastFix.str()));
6762 } else {
6763 // Otherwise, add parens around the expression as well as the cast.
6764 CastFix << "(";
6765 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6766 CastFix.str()));
6767
Alp Tokerb6cc5922014-05-03 03:45:55 +00006768 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006769 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6770 }
6771
Jordan Rose0e5badd2012-12-05 18:44:49 +00006772 if (ShouldNotPrintDirectly) {
6773 // The expression has a type that should not be printed directly.
6774 // We extract the name from the typedef because we don't want to show
6775 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006776 StringRef Name;
6777 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6778 Name = TypedefTy->getDecl()->getName();
6779 else
6780 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006781 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006782 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006783 << E->getSourceRange(),
6784 E->getLocStart(), /*IsStringLocation=*/false,
6785 SpecRange, Hints);
6786 } else {
6787 // In this case, the expression could be printed using a different
6788 // specifier, but we've decided that the specifier is probably correct
6789 // and we should cast instead. Just use the normal warning message.
6790 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006791 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6792 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006793 << E->getSourceRange(),
6794 E->getLocStart(), /*IsStringLocation*/false,
6795 SpecRange, Hints);
6796 }
Jordan Roseaee34382012-09-05 22:56:26 +00006797 }
Jordan Rose22b74712012-09-05 22:56:19 +00006798 } else {
6799 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6800 SpecifierLen);
6801 // Since the warning for passing non-POD types to variadic functions
6802 // was deferred until now, we emit a warning for non-POD
6803 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006804 switch (S.isValidVarArgType(ExprTy)) {
6805 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006806 case Sema::VAK_ValidInCXX11: {
6807 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6808 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6809 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6810 }
Richard Smithd7293d72013-08-05 18:49:43 +00006811
Seth Cantrellb4802962015-03-04 03:12:10 +00006812 EmitFormatDiagnostic(
6813 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6814 << IsEnum << CSR << E->getSourceRange(),
6815 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6816 break;
6817 }
Richard Smithd7293d72013-08-05 18:49:43 +00006818 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006819 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006820 EmitFormatDiagnostic(
6821 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006822 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006823 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006824 << CallType
6825 << AT.getRepresentativeTypeName(S.Context)
6826 << CSR
6827 << E->getSourceRange(),
6828 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006829 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006830 break;
6831
6832 case Sema::VAK_Invalid:
6833 if (ExprTy->isObjCObjectType())
6834 EmitFormatDiagnostic(
6835 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6836 << S.getLangOpts().CPlusPlus11
6837 << ExprTy
6838 << CallType
6839 << AT.getRepresentativeTypeName(S.Context)
6840 << CSR
6841 << E->getSourceRange(),
6842 E->getLocStart(), /*IsStringLocation*/false, CSR);
6843 else
6844 // FIXME: If this is an initializer list, suggest removing the braces
6845 // or inserting a cast to the target type.
6846 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6847 << isa<InitListExpr>(E) << ExprTy << CallType
6848 << AT.getRepresentativeTypeName(S.Context)
6849 << E->getSourceRange();
6850 break;
6851 }
6852
6853 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6854 "format string specifier index out of range");
6855 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006856 }
6857
Ted Kremenekab278de2010-01-28 23:39:18 +00006858 return true;
6859}
6860
Ted Kremenek02087932010-07-16 02:11:22 +00006861//===--- CHECK: Scanf format string checking ------------------------------===//
6862
6863namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006864
Ted Kremenek02087932010-07-16 02:11:22 +00006865class CheckScanfHandler : public CheckFormatHandler {
6866public:
Stephen Hines648c3692016-09-16 01:07:04 +00006867 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006868 const Expr *origFormatExpr, Sema::FormatStringType type,
6869 unsigned firstDataArg, unsigned numDataArgs,
6870 const char *beg, bool hasVAListArg,
6871 ArrayRef<const Expr *> Args, unsigned formatIdx,
6872 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006873 llvm::SmallBitVector &CheckedVarArgs,
6874 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006875 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6876 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6877 inFunctionCall, CallType, CheckedVarArgs,
6878 UncoveredArg) {}
6879
Ted Kremenek02087932010-07-16 02:11:22 +00006880 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6881 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006882 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006883
6884 bool HandleInvalidScanfConversionSpecifier(
6885 const analyze_scanf::ScanfSpecifier &FS,
6886 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006887 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006888
Craig Toppere14c0f82014-03-12 04:55:44 +00006889 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006890};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006891
6892} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006893
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006894void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6895 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006896 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6897 getLocationOfByte(end), /*IsStringLocation*/true,
6898 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006899}
6900
Ted Kremenekce815422010-07-19 21:25:57 +00006901bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6902 const analyze_scanf::ScanfSpecifier &FS,
6903 const char *startSpecifier,
6904 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006905 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006906 FS.getConversionSpecifier();
6907
6908 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6909 getLocationOfByte(CS.getStart()),
6910 startSpecifier, specifierLen,
6911 CS.getStart(), CS.getLength());
6912}
6913
Ted Kremenek02087932010-07-16 02:11:22 +00006914bool CheckScanfHandler::HandleScanfSpecifier(
6915 const analyze_scanf::ScanfSpecifier &FS,
6916 const char *startSpecifier,
6917 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006918 using namespace analyze_scanf;
6919 using namespace analyze_format_string;
6920
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006921 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006922
Ted Kremenek6cd69422010-07-19 22:01:06 +00006923 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6924 // be used to decide if we are using positional arguments consistently.
6925 if (FS.consumesDataArgument()) {
6926 if (atFirstArg) {
6927 atFirstArg = false;
6928 usesPositionalArgs = FS.usesPositionalArg();
6929 }
6930 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006931 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6932 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006933 return false;
6934 }
Ted Kremenek02087932010-07-16 02:11:22 +00006935 }
6936
6937 // Check if the field with is non-zero.
6938 const OptionalAmount &Amt = FS.getFieldWidth();
6939 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6940 if (Amt.getConstantAmount() == 0) {
6941 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6942 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006943 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6944 getLocationOfByte(Amt.getStart()),
6945 /*IsStringLocation*/true, R,
6946 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006947 }
6948 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006949
Ted Kremenek02087932010-07-16 02:11:22 +00006950 if (!FS.consumesDataArgument()) {
6951 // FIXME: Technically specifying a precision or field width here
6952 // makes no sense. Worth issuing a warning at some point.
6953 return true;
6954 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006955
Ted Kremenek02087932010-07-16 02:11:22 +00006956 // Consume the argument.
6957 unsigned argIndex = FS.getArgIndex();
6958 if (argIndex < NumDataArgs) {
6959 // The check to see if the argIndex is valid will come later.
6960 // We set the bit here because we may exit early from this
6961 // function if we encounter some other error.
6962 CoveredArgs.set(argIndex);
6963 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006964
Ted Kremenek4407ea42010-07-20 20:04:47 +00006965 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006966 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006967 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6968 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006969 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006970 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006971 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006972 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6973 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006974
Jordan Rose92303592012-09-08 04:00:03 +00006975 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6976 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6977
Ted Kremenek02087932010-07-16 02:11:22 +00006978 // The remaining checks depend on the data arguments.
6979 if (HasVAListArg)
6980 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006981
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006982 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006983 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006984
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006985 // Check that the argument type matches the format specifier.
6986 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006987 if (!Ex)
6988 return true;
6989
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006990 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006991
6992 if (!AT.isValid()) {
6993 return true;
6994 }
6995
Seth Cantrellb4802962015-03-04 03:12:10 +00006996 analyze_format_string::ArgType::MatchKind match =
6997 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006998 if (match == analyze_format_string::ArgType::Match) {
6999 return true;
7000 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007001
Seth Cantrell79340072015-03-04 05:58:08 +00007002 ScanfSpecifier fixedFS = FS;
7003 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
7004 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007005
Seth Cantrell79340072015-03-04 05:58:08 +00007006 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
7007 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
7008 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
7009 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007010
Seth Cantrell79340072015-03-04 05:58:08 +00007011 if (success) {
7012 // Get the fix string from the fixed format specifier.
7013 SmallString<128> buf;
7014 llvm::raw_svector_ostream os(buf);
7015 fixedFS.toString(os);
7016
7017 EmitFormatDiagnostic(
7018 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
7019 << Ex->getType() << false << Ex->getSourceRange(),
7020 Ex->getLocStart(),
7021 /*IsStringLocation*/ false,
7022 getSpecifierRange(startSpecifier, specifierLen),
7023 FixItHint::CreateReplacement(
7024 getSpecifierRange(startSpecifier, specifierLen), os.str()));
7025 } else {
7026 EmitFormatDiagnostic(S.PDiag(diag)
7027 << AT.getRepresentativeTypeName(S.Context)
7028 << Ex->getType() << false << Ex->getSourceRange(),
7029 Ex->getLocStart(),
7030 /*IsStringLocation*/ false,
7031 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007032 }
7033
Ted Kremenek02087932010-07-16 02:11:22 +00007034 return true;
7035}
7036
Stephen Hines648c3692016-09-16 01:07:04 +00007037static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007038 const Expr *OrigFormatExpr,
7039 ArrayRef<const Expr *> Args,
7040 bool HasVAListArg, unsigned format_idx,
7041 unsigned firstDataArg,
7042 Sema::FormatStringType Type,
7043 bool inFunctionCall,
7044 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007045 llvm::SmallBitVector &CheckedVarArgs,
7046 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00007047 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00007048 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007049 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007050 S, inFunctionCall, Args[format_idx],
7051 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00007052 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00007053 return;
7054 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007055
Ted Kremenekab278de2010-01-28 23:39:18 +00007056 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007057 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00007058 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007059 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007060 const ConstantArrayType *T =
7061 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007062 assert(T && "String literal not of constant array type!");
7063 size_t TypeSize = T->getSize().getZExtValue();
7064 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00007065 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007066
7067 // Emit a warning if the string literal is truncated and does not contain an
7068 // embedded null character.
7069 if (TypeSize <= StrRef.size() &&
7070 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
7071 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007072 S, inFunctionCall, Args[format_idx],
7073 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007074 FExpr->getLocStart(),
7075 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
7076 return;
7077 }
7078
Ted Kremenekab278de2010-01-28 23:39:18 +00007079 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00007080 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007081 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007082 S, inFunctionCall, Args[format_idx],
7083 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00007084 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00007085 return;
7086 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007087
7088 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00007089 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
7090 Type == Sema::FST_OSTrace) {
7091 CheckPrintfHandler H(
7092 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
7093 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
7094 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
7095 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007096
Hans Wennborg23926bd2011-12-15 10:25:47 +00007097 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007098 S.getLangOpts(),
7099 S.Context.getTargetInfo(),
7100 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00007101 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007102 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00007103 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
7104 numDataArgs, Str, HasVAListArg, Args, format_idx,
7105 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007106
Hans Wennborg23926bd2011-12-15 10:25:47 +00007107 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007108 S.getLangOpts(),
7109 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00007110 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00007111 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00007112}
7113
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00007114bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
7115 // Str - The format string. NOTE: this is NOT null-terminated!
7116 StringRef StrRef = FExpr->getString();
7117 const char *Str = StrRef.data();
7118 // Account for cases where the string literal is truncated in a declaration.
7119 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
7120 assert(T && "String literal not of constant array type!");
7121 size_t TypeSize = T->getSize().getZExtValue();
7122 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
7123 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
7124 getLangOpts(),
7125 Context.getTargetInfo());
7126}
7127
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007128//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
7129
7130// Returns the related absolute value function that is larger, of 0 if one
7131// does not exist.
7132static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
7133 switch (AbsFunction) {
7134 default:
7135 return 0;
7136
7137 case Builtin::BI__builtin_abs:
7138 return Builtin::BI__builtin_labs;
7139 case Builtin::BI__builtin_labs:
7140 return Builtin::BI__builtin_llabs;
7141 case Builtin::BI__builtin_llabs:
7142 return 0;
7143
7144 case Builtin::BI__builtin_fabsf:
7145 return Builtin::BI__builtin_fabs;
7146 case Builtin::BI__builtin_fabs:
7147 return Builtin::BI__builtin_fabsl;
7148 case Builtin::BI__builtin_fabsl:
7149 return 0;
7150
7151 case Builtin::BI__builtin_cabsf:
7152 return Builtin::BI__builtin_cabs;
7153 case Builtin::BI__builtin_cabs:
7154 return Builtin::BI__builtin_cabsl;
7155 case Builtin::BI__builtin_cabsl:
7156 return 0;
7157
7158 case Builtin::BIabs:
7159 return Builtin::BIlabs;
7160 case Builtin::BIlabs:
7161 return Builtin::BIllabs;
7162 case Builtin::BIllabs:
7163 return 0;
7164
7165 case Builtin::BIfabsf:
7166 return Builtin::BIfabs;
7167 case Builtin::BIfabs:
7168 return Builtin::BIfabsl;
7169 case Builtin::BIfabsl:
7170 return 0;
7171
7172 case Builtin::BIcabsf:
7173 return Builtin::BIcabs;
7174 case Builtin::BIcabs:
7175 return Builtin::BIcabsl;
7176 case Builtin::BIcabsl:
7177 return 0;
7178 }
7179}
7180
7181// Returns the argument type of the absolute value function.
7182static QualType getAbsoluteValueArgumentType(ASTContext &Context,
7183 unsigned AbsType) {
7184 if (AbsType == 0)
7185 return QualType();
7186
7187 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
7188 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
7189 if (Error != ASTContext::GE_None)
7190 return QualType();
7191
7192 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
7193 if (!FT)
7194 return QualType();
7195
7196 if (FT->getNumParams() != 1)
7197 return QualType();
7198
7199 return FT->getParamType(0);
7200}
7201
7202// Returns the best absolute value function, or zero, based on type and
7203// current absolute value function.
7204static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
7205 unsigned AbsFunctionKind) {
7206 unsigned BestKind = 0;
7207 uint64_t ArgSize = Context.getTypeSize(ArgType);
7208 for (unsigned Kind = AbsFunctionKind; Kind != 0;
7209 Kind = getLargerAbsoluteValueFunction(Kind)) {
7210 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
7211 if (Context.getTypeSize(ParamType) >= ArgSize) {
7212 if (BestKind == 0)
7213 BestKind = Kind;
7214 else if (Context.hasSameType(ParamType, ArgType)) {
7215 BestKind = Kind;
7216 break;
7217 }
7218 }
7219 }
7220 return BestKind;
7221}
7222
7223enum AbsoluteValueKind {
7224 AVK_Integer,
7225 AVK_Floating,
7226 AVK_Complex
7227};
7228
7229static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
7230 if (T->isIntegralOrEnumerationType())
7231 return AVK_Integer;
7232 if (T->isRealFloatingType())
7233 return AVK_Floating;
7234 if (T->isAnyComplexType())
7235 return AVK_Complex;
7236
7237 llvm_unreachable("Type not integer, floating, or complex");
7238}
7239
7240// Changes the absolute value function to a different type. Preserves whether
7241// the function is a builtin.
7242static unsigned changeAbsFunction(unsigned AbsKind,
7243 AbsoluteValueKind ValueKind) {
7244 switch (ValueKind) {
7245 case AVK_Integer:
7246 switch (AbsKind) {
7247 default:
7248 return 0;
7249 case Builtin::BI__builtin_fabsf:
7250 case Builtin::BI__builtin_fabs:
7251 case Builtin::BI__builtin_fabsl:
7252 case Builtin::BI__builtin_cabsf:
7253 case Builtin::BI__builtin_cabs:
7254 case Builtin::BI__builtin_cabsl:
7255 return Builtin::BI__builtin_abs;
7256 case Builtin::BIfabsf:
7257 case Builtin::BIfabs:
7258 case Builtin::BIfabsl:
7259 case Builtin::BIcabsf:
7260 case Builtin::BIcabs:
7261 case Builtin::BIcabsl:
7262 return Builtin::BIabs;
7263 }
7264 case AVK_Floating:
7265 switch (AbsKind) {
7266 default:
7267 return 0;
7268 case Builtin::BI__builtin_abs:
7269 case Builtin::BI__builtin_labs:
7270 case Builtin::BI__builtin_llabs:
7271 case Builtin::BI__builtin_cabsf:
7272 case Builtin::BI__builtin_cabs:
7273 case Builtin::BI__builtin_cabsl:
7274 return Builtin::BI__builtin_fabsf;
7275 case Builtin::BIabs:
7276 case Builtin::BIlabs:
7277 case Builtin::BIllabs:
7278 case Builtin::BIcabsf:
7279 case Builtin::BIcabs:
7280 case Builtin::BIcabsl:
7281 return Builtin::BIfabsf;
7282 }
7283 case AVK_Complex:
7284 switch (AbsKind) {
7285 default:
7286 return 0;
7287 case Builtin::BI__builtin_abs:
7288 case Builtin::BI__builtin_labs:
7289 case Builtin::BI__builtin_llabs:
7290 case Builtin::BI__builtin_fabsf:
7291 case Builtin::BI__builtin_fabs:
7292 case Builtin::BI__builtin_fabsl:
7293 return Builtin::BI__builtin_cabsf;
7294 case Builtin::BIabs:
7295 case Builtin::BIlabs:
7296 case Builtin::BIllabs:
7297 case Builtin::BIfabsf:
7298 case Builtin::BIfabs:
7299 case Builtin::BIfabsl:
7300 return Builtin::BIcabsf;
7301 }
7302 }
7303 llvm_unreachable("Unable to convert function");
7304}
7305
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00007306static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007307 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
7308 if (!FnInfo)
7309 return 0;
7310
7311 switch (FDecl->getBuiltinID()) {
7312 default:
7313 return 0;
7314 case Builtin::BI__builtin_abs:
7315 case Builtin::BI__builtin_fabs:
7316 case Builtin::BI__builtin_fabsf:
7317 case Builtin::BI__builtin_fabsl:
7318 case Builtin::BI__builtin_labs:
7319 case Builtin::BI__builtin_llabs:
7320 case Builtin::BI__builtin_cabs:
7321 case Builtin::BI__builtin_cabsf:
7322 case Builtin::BI__builtin_cabsl:
7323 case Builtin::BIabs:
7324 case Builtin::BIlabs:
7325 case Builtin::BIllabs:
7326 case Builtin::BIfabs:
7327 case Builtin::BIfabsf:
7328 case Builtin::BIfabsl:
7329 case Builtin::BIcabs:
7330 case Builtin::BIcabsf:
7331 case Builtin::BIcabsl:
7332 return FDecl->getBuiltinID();
7333 }
7334 llvm_unreachable("Unknown Builtin type");
7335}
7336
7337// If the replacement is valid, emit a note with replacement function.
7338// Additionally, suggest including the proper header if not already included.
7339static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00007340 unsigned AbsKind, QualType ArgType) {
7341 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007342 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00007343 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007344 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
7345 FunctionName = "std::abs";
7346 if (ArgType->isIntegralOrEnumerationType()) {
7347 HeaderName = "cstdlib";
7348 } else if (ArgType->isRealFloatingType()) {
7349 HeaderName = "cmath";
7350 } else {
7351 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007352 }
Richard Trieubeffb832014-04-15 23:47:53 +00007353
7354 // Lookup all std::abs
7355 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00007356 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00007357 R.suppressDiagnostics();
7358 S.LookupQualifiedName(R, Std);
7359
7360 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007361 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007362 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
7363 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
7364 } else {
7365 FDecl = dyn_cast<FunctionDecl>(I);
7366 }
7367 if (!FDecl)
7368 continue;
7369
7370 // Found std::abs(), check that they are the right ones.
7371 if (FDecl->getNumParams() != 1)
7372 continue;
7373
7374 // Check that the parameter type can handle the argument.
7375 QualType ParamType = FDecl->getParamDecl(0)->getType();
7376 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
7377 S.Context.getTypeSize(ArgType) <=
7378 S.Context.getTypeSize(ParamType)) {
7379 // Found a function, don't need the header hint.
7380 EmitHeaderHint = false;
7381 break;
7382 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007383 }
Richard Trieubeffb832014-04-15 23:47:53 +00007384 }
7385 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00007386 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00007387 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7388
7389 if (HeaderName) {
7390 DeclarationName DN(&S.Context.Idents.get(FunctionName));
7391 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7392 R.suppressDiagnostics();
7393 S.LookupName(R, S.getCurScope());
7394
7395 if (R.isSingleResult()) {
7396 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7397 if (FD && FD->getBuiltinID() == AbsKind) {
7398 EmitHeaderHint = false;
7399 } else {
7400 return;
7401 }
7402 } else if (!R.empty()) {
7403 return;
7404 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007405 }
7406 }
7407
7408 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00007409 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007410
Richard Trieubeffb832014-04-15 23:47:53 +00007411 if (!HeaderName)
7412 return;
7413
7414 if (!EmitHeaderHint)
7415 return;
7416
Alp Toker5d96e0a2014-07-11 20:53:51 +00007417 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7418 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00007419}
7420
Richard Trieua7f30b12016-12-06 01:42:28 +00007421template <std::size_t StrLen>
7422static bool IsStdFunction(const FunctionDecl *FDecl,
7423 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00007424 if (!FDecl)
7425 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007426 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00007427 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007428 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00007429 return false;
7430
7431 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007432}
7433
7434// Warn when using the wrong abs() function.
7435void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00007436 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007437 if (Call->getNumArgs() != 1)
7438 return;
7439
7440 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00007441 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00007442 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007443 return;
7444
7445 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7446 QualType ParamType = Call->getArg(0)->getType();
7447
Alp Toker5d96e0a2014-07-11 20:53:51 +00007448 // Unsigned types cannot be negative. Suggest removing the absolute value
7449 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007450 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00007451 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00007452 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007453 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7454 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00007455 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007456 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7457 return;
7458 }
7459
David Majnemer7f77eb92015-11-15 03:04:34 +00007460 // Taking the absolute value of a pointer is very suspicious, they probably
7461 // wanted to index into an array, dereference a pointer, call a function, etc.
7462 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7463 unsigned DiagType = 0;
7464 if (ArgType->isFunctionType())
7465 DiagType = 1;
7466 else if (ArgType->isArrayType())
7467 DiagType = 2;
7468
7469 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7470 return;
7471 }
7472
Richard Trieubeffb832014-04-15 23:47:53 +00007473 // std::abs has overloads which prevent most of the absolute value problems
7474 // from occurring.
7475 if (IsStdAbs)
7476 return;
7477
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007478 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7479 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7480
7481 // The argument and parameter are the same kind. Check if they are the right
7482 // size.
7483 if (ArgValueKind == ParamValueKind) {
7484 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7485 return;
7486
7487 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7488 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7489 << FDecl << ArgType << ParamType;
7490
7491 if (NewAbsKind == 0)
7492 return;
7493
7494 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007495 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007496 return;
7497 }
7498
7499 // ArgValueKind != ParamValueKind
7500 // The wrong type of absolute value function was used. Attempt to find the
7501 // proper one.
7502 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7503 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7504 if (NewAbsKind == 0)
7505 return;
7506
7507 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7508 << FDecl << ParamValueKind << ArgValueKind;
7509
7510 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007511 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007512}
7513
Richard Trieu67c00712016-12-05 23:41:46 +00007514//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00007515void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7516 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00007517 if (!Call || !FDecl) return;
7518
7519 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00007520 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007521 if (Call->getExprLoc().isMacroID()) return;
7522
7523 // Only care about the one template argument, two function parameter std::max
7524 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00007525 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007526 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7527 if (!ArgList) return;
7528 if (ArgList->size() != 1) return;
7529
7530 // Check that template type argument is unsigned integer.
7531 const auto& TA = ArgList->get(0);
7532 if (TA.getKind() != TemplateArgument::Type) return;
7533 QualType ArgType = TA.getAsType();
7534 if (!ArgType->isUnsignedIntegerType()) return;
7535
7536 // See if either argument is a literal zero.
7537 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7538 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7539 if (!MTE) return false;
7540 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7541 if (!Num) return false;
7542 if (Num->getValue() != 0) return false;
7543 return true;
7544 };
7545
7546 const Expr *FirstArg = Call->getArg(0);
7547 const Expr *SecondArg = Call->getArg(1);
7548 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7549 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7550
7551 // Only warn when exactly one argument is zero.
7552 if (IsFirstArgZero == IsSecondArgZero) return;
7553
7554 SourceRange FirstRange = FirstArg->getSourceRange();
7555 SourceRange SecondRange = SecondArg->getSourceRange();
7556
7557 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7558
7559 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7560 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7561
7562 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7563 SourceRange RemovalRange;
7564 if (IsFirstArgZero) {
7565 RemovalRange = SourceRange(FirstRange.getBegin(),
7566 SecondRange.getBegin().getLocWithOffset(-1));
7567 } else {
7568 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7569 SecondRange.getEnd());
7570 }
7571
7572 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7573 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7574 << FixItHint::CreateRemoval(RemovalRange);
7575}
7576
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007577//===--- CHECK: Standard memory functions ---------------------------------===//
7578
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007579/// Takes the expression passed to the size_t parameter of functions
Nico Weber0e6daef2013-12-26 23:38:39 +00007580/// such as memcmp, strncat, etc and warns if it's a comparison.
7581///
7582/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7583static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7584 IdentifierInfo *FnName,
7585 SourceLocation FnLoc,
7586 SourceLocation RParenLoc) {
7587 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7588 if (!Size)
7589 return false;
7590
Richard Smithc70f1d62017-12-14 15:16:18 +00007591 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
7592 if (!Size->isComparisonOp() && !Size->isLogicalOp())
Nico Weber0e6daef2013-12-26 23:38:39 +00007593 return false;
7594
Nico Weber0e6daef2013-12-26 23:38:39 +00007595 SourceRange SizeRange = Size->getSourceRange();
7596 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7597 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00007598 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007599 << FnName << FixItHint::CreateInsertion(
7600 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00007601 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00007602 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00007603 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00007604 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7605 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00007606
7607 return true;
7608}
7609
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007610/// Determine whether the given type is or contains a dynamic class type
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007611/// (e.g., whether it has a vtable).
7612static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7613 bool &IsContained) {
7614 // Look through array types while ignoring qualifiers.
7615 const Type *Ty = T->getBaseElementTypeUnsafe();
7616 IsContained = false;
7617
7618 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7619 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00007620 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007621 return nullptr;
7622
7623 if (RD->isDynamicClass())
7624 return RD;
7625
7626 // Check all the fields. If any bases were dynamic, the class is dynamic.
7627 // It's impossible for a class to transitively contain itself by value, so
7628 // infinite recursion is impossible.
7629 for (auto *FD : RD->fields()) {
7630 bool SubContained;
7631 if (const CXXRecordDecl *ContainedRD =
7632 getContainedDynamicClass(FD->getType(), SubContained)) {
7633 IsContained = true;
7634 return ContainedRD;
7635 }
7636 }
7637
7638 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007639}
7640
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007641/// If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007642/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007643static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007644 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007645 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007646 if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007647 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007648
Craig Topperc3ec1492014-05-26 06:22:03 +00007649 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007650}
7651
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007652/// If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007653static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007654 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7655 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007656 if (SizeOf->getKind() == UETT_SizeOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007657 return SizeOf->getTypeOfArgument();
7658
7659 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007660}
7661
Akira Hatanaka2be04412018-04-17 19:13:41 +00007662namespace {
7663
7664struct SearchNonTrivialToInitializeField
7665 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
7666 using Super =
7667 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
7668
7669 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
7670
7671 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
7672 SourceLocation SL) {
7673 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7674 asDerived().visitArray(PDIK, AT, SL);
7675 return;
7676 }
7677
7678 Super::visitWithKind(PDIK, FT, SL);
7679 }
7680
7681 void visitARCStrong(QualType FT, SourceLocation SL) {
7682 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7683 }
7684 void visitARCWeak(QualType FT, SourceLocation SL) {
7685 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7686 }
7687 void visitStruct(QualType FT, SourceLocation SL) {
7688 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7689 visit(FD->getType(), FD->getLocation());
7690 }
7691 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
7692 const ArrayType *AT, SourceLocation SL) {
7693 visit(getContext().getBaseElementType(AT), SL);
7694 }
7695 void visitTrivial(QualType FT, SourceLocation SL) {}
7696
7697 static void diag(QualType RT, const Expr *E, Sema &S) {
7698 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
7699 }
7700
7701 ASTContext &getContext() { return S.getASTContext(); }
7702
7703 const Expr *E;
7704 Sema &S;
7705};
7706
7707struct SearchNonTrivialToCopyField
7708 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
7709 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
7710
7711 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
7712
7713 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
7714 SourceLocation SL) {
7715 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7716 asDerived().visitArray(PCK, AT, SL);
7717 return;
7718 }
7719
7720 Super::visitWithKind(PCK, FT, SL);
7721 }
7722
7723 void visitARCStrong(QualType FT, SourceLocation SL) {
7724 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7725 }
7726 void visitARCWeak(QualType FT, SourceLocation SL) {
7727 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7728 }
7729 void visitStruct(QualType FT, SourceLocation SL) {
7730 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7731 visit(FD->getType(), FD->getLocation());
7732 }
7733 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
7734 SourceLocation SL) {
7735 visit(getContext().getBaseElementType(AT), SL);
7736 }
7737 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
7738 SourceLocation SL) {}
7739 void visitTrivial(QualType FT, SourceLocation SL) {}
7740 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
7741
7742 static void diag(QualType RT, const Expr *E, Sema &S) {
7743 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
7744 }
7745
7746 ASTContext &getContext() { return S.getASTContext(); }
7747
7748 const Expr *E;
7749 Sema &S;
7750};
7751
7752}
7753
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007754/// Check for dangerous or invalid arguments to memset().
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007755///
Chandler Carruthac687262011-06-03 06:23:57 +00007756/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007757/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7758/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007759///
7760/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007761void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007762 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007763 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007764 assert(BId != 0);
7765
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007766 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007767 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007768 unsigned ExpectedNumArgs =
7769 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007770 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007771 return;
7772
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007773 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007774 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007775 unsigned LenArg =
7776 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007777 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007778
Nico Weber0e6daef2013-12-26 23:38:39 +00007779 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7780 Call->getLocStart(), Call->getRParenLoc()))
7781 return;
7782
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007783 // We have special checking when the length is a sizeof expression.
7784 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7785 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7786 llvm::FoldingSetNodeID SizeOfArgID;
7787
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007788 // Although widely used, 'bzero' is not a standard function. Be more strict
7789 // with the argument types before allowing diagnostics and only allow the
7790 // form bzero(ptr, sizeof(...)).
7791 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7792 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7793 return;
7794
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007795 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7796 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007797 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007798
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007799 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007800 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007801 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007802 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007803
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007804 // Never warn about void type pointers. This can be used to suppress
7805 // false positives.
7806 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007807 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007808
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007809 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7810 // actually comparing the expressions for equality. Because computing the
7811 // expression IDs can be expensive, we only do this if the diagnostic is
7812 // enabled.
7813 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007814 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7815 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007816 // We only compute IDs for expressions if the warning is enabled, and
7817 // cache the sizeof arg's ID.
7818 if (SizeOfArgID == llvm::FoldingSetNodeID())
7819 SizeOfArg->Profile(SizeOfArgID, Context, true);
7820 llvm::FoldingSetNodeID DestID;
7821 Dest->Profile(DestID, Context, true);
7822 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007823 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7824 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007825 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007826 StringRef ReadableName = FnName->getName();
7827
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007828 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007829 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007830 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007831 if (!PointeeTy->isIncompleteType() &&
7832 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007833 ActionIdx = 2; // If the pointee's size is sizeof(char),
7834 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007835
7836 // If the function is defined as a builtin macro, do not show macro
7837 // expansion.
7838 SourceLocation SL = SizeOfArg->getExprLoc();
7839 SourceRange DSR = Dest->getSourceRange();
7840 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007841 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007842
7843 if (SM.isMacroArgExpansion(SL)) {
7844 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7845 SL = SM.getSpellingLoc(SL);
7846 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7847 SM.getSpellingLoc(DSR.getEnd()));
7848 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7849 SM.getSpellingLoc(SSR.getEnd()));
7850 }
7851
Anna Zaksd08d9152012-05-30 23:14:52 +00007852 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007853 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007854 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007855 << PointeeTy
7856 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007857 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007858 << SSR);
7859 DiagRuntimeBehavior(SL, SizeOfArg,
7860 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7861 << ActionIdx
7862 << SSR);
7863
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007864 break;
7865 }
7866 }
7867
7868 // Also check for cases where the sizeof argument is the exact same
7869 // type as the memory argument, and where it points to a user-defined
7870 // record type.
7871 if (SizeOfArgTy != QualType()) {
7872 if (PointeeTy->isRecordType() &&
7873 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7874 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7875 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7876 << FnName << SizeOfArgTy << ArgIdx
7877 << PointeeTy << Dest->getSourceRange()
7878 << LenExpr->getSourceRange());
7879 break;
7880 }
Nico Weberc5e73862011-06-14 16:14:58 +00007881 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00007882 } else if (DestTy->isArrayType()) {
7883 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00007884 }
Nico Weberc5e73862011-06-14 16:14:58 +00007885
Nico Weberc44b35e2015-03-21 17:37:46 +00007886 if (PointeeTy == QualType())
7887 continue;
Anna Zaks22122702012-01-17 00:37:07 +00007888
Nico Weberc44b35e2015-03-21 17:37:46 +00007889 // Always complain about dynamic classes.
7890 bool IsContained;
7891 if (const CXXRecordDecl *ContainedRD =
7892 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00007893
Nico Weberc44b35e2015-03-21 17:37:46 +00007894 unsigned OperationType = 0;
7895 // "overwritten" if we're warning about the destination for any call
7896 // but memcmp; otherwise a verb appropriate to the call.
7897 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7898 if (BId == Builtin::BImemcpy)
7899 OperationType = 1;
7900 else if(BId == Builtin::BImemmove)
7901 OperationType = 2;
7902 else if (BId == Builtin::BImemcmp)
7903 OperationType = 3;
7904 }
7905
John McCall31168b02011-06-15 23:02:42 +00007906 DiagRuntimeBehavior(
7907 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007908 PDiag(diag::warn_dyn_class_memaccess)
7909 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7910 << FnName << IsContained << ContainedRD << OperationType
7911 << Call->getCallee()->getSourceRange());
7912 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7913 BId != Builtin::BImemset)
7914 DiagRuntimeBehavior(
7915 Dest->getExprLoc(), Dest,
7916 PDiag(diag::warn_arc_object_memaccess)
7917 << ArgIdx << FnName << PointeeTy
7918 << Call->getCallee()->getSourceRange());
Akira Hatanaka2be04412018-04-17 19:13:41 +00007919 else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
7920 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
7921 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
7922 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
7923 PDiag(diag::warn_cstruct_memaccess)
7924 << ArgIdx << FnName << PointeeTy << 0);
7925 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
7926 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
7927 RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
7928 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
7929 PDiag(diag::warn_cstruct_memaccess)
7930 << ArgIdx << FnName << PointeeTy << 1);
7931 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
7932 } else {
7933 continue;
7934 }
7935 } else
Nico Weberc44b35e2015-03-21 17:37:46 +00007936 continue;
7937
7938 DiagRuntimeBehavior(
7939 Dest->getExprLoc(), Dest,
7940 PDiag(diag::note_bad_memaccess_silence)
7941 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7942 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007943 }
7944}
7945
Ted Kremenek6865f772011-08-18 20:55:45 +00007946// A little helper routine: ignore addition and subtraction of integer literals.
7947// This intentionally does not ignore all integer constant expressions because
7948// we don't want to remove sizeof().
7949static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7950 Ex = Ex->IgnoreParenCasts();
7951
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007952 while (true) {
Ted Kremenek6865f772011-08-18 20:55:45 +00007953 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7954 if (!BO || !BO->isAdditiveOp())
7955 break;
7956
7957 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7958 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7959
7960 if (isa<IntegerLiteral>(RHS))
7961 Ex = LHS;
7962 else if (isa<IntegerLiteral>(LHS))
7963 Ex = RHS;
7964 else
7965 break;
7966 }
7967
7968 return Ex;
7969}
7970
Anna Zaks13b08572012-08-08 21:42:23 +00007971static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7972 ASTContext &Context) {
7973 // Only handle constant-sized or VLAs, but not flexible members.
7974 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7975 // Only issue the FIXIT for arrays of size > 1.
7976 if (CAT->getSize().getSExtValue() <= 1)
7977 return false;
7978 } else if (!Ty->isVariableArrayType()) {
7979 return false;
7980 }
7981 return true;
7982}
7983
Ted Kremenek6865f772011-08-18 20:55:45 +00007984// Warn if the user has made the 'size' argument to strlcpy or strlcat
7985// be the size of the source, instead of the destination.
7986void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7987 IdentifierInfo *FnName) {
7988
7989 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007990 unsigned NumArgs = Call->getNumArgs();
7991 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007992 return;
7993
7994 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7995 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007996 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007997
7998 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7999 Call->getLocStart(), Call->getRParenLoc()))
8000 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00008001
8002 // Look for 'strlcpy(dst, x, sizeof(x))'
8003 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
8004 CompareWithSrc = Ex;
8005 else {
8006 // Look for 'strlcpy(dst, x, strlen(x))'
8007 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00008008 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
8009 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00008010 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
8011 }
8012 }
8013
8014 if (!CompareWithSrc)
8015 return;
8016
8017 // Determine if the argument to sizeof/strlen is equal to the source
8018 // argument. In principle there's all kinds of things you could do
8019 // here, for instance creating an == expression and evaluating it with
8020 // EvaluateAsBooleanCondition, but this uses a more direct technique:
8021 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
8022 if (!SrcArgDRE)
8023 return;
8024
8025 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
8026 if (!CompareWithSrcDRE ||
8027 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
8028 return;
8029
8030 const Expr *OriginalSizeArg = Call->getArg(2);
8031 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
8032 << OriginalSizeArg->getSourceRange() << FnName;
8033
8034 // Output a FIXIT hint if the destination is an array (rather than a
8035 // pointer to an array). This could be enhanced to handle some
8036 // pointers if we know the actual size, like if DstArg is 'array+2'
8037 // we could say 'sizeof(array)-2'.
8038 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00008039 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00008040 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00008041
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008042 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00008043 llvm::raw_svector_ostream OS(sizeString);
8044 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008045 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00008046 OS << ")";
8047
8048 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
8049 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
8050 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00008051}
8052
Anna Zaks314cd092012-02-01 19:08:57 +00008053/// Check if two expressions refer to the same declaration.
8054static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
8055 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
8056 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
8057 return D1->getDecl() == D2->getDecl();
8058 return false;
8059}
8060
8061static const Expr *getStrlenExprArg(const Expr *E) {
8062 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8063 const FunctionDecl *FD = CE->getDirectCallee();
8064 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00008065 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00008066 return CE->getArg(0)->IgnoreParenCasts();
8067 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008068 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00008069}
8070
8071// Warn on anti-patterns as the 'size' argument to strncat.
8072// The correct size argument should look like following:
8073// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
8074void Sema::CheckStrncatArguments(const CallExpr *CE,
8075 IdentifierInfo *FnName) {
8076 // Don't crash if the user has the wrong number of arguments.
8077 if (CE->getNumArgs() < 3)
8078 return;
8079 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
8080 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
8081 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
8082
Nico Weber0e6daef2013-12-26 23:38:39 +00008083 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
8084 CE->getRParenLoc()))
8085 return;
8086
Anna Zaks314cd092012-02-01 19:08:57 +00008087 // Identify common expressions, which are wrongly used as the size argument
8088 // to strncat and may lead to buffer overflows.
8089 unsigned PatternType = 0;
8090 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
8091 // - sizeof(dst)
8092 if (referToTheSameDecl(SizeOfArg, DstArg))
8093 PatternType = 1;
8094 // - sizeof(src)
8095 else if (referToTheSameDecl(SizeOfArg, SrcArg))
8096 PatternType = 2;
8097 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
8098 if (BE->getOpcode() == BO_Sub) {
8099 const Expr *L = BE->getLHS()->IgnoreParenCasts();
8100 const Expr *R = BE->getRHS()->IgnoreParenCasts();
8101 // - sizeof(dst) - strlen(dst)
8102 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
8103 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
8104 PatternType = 1;
8105 // - sizeof(src) - (anything)
8106 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
8107 PatternType = 2;
8108 }
8109 }
8110
8111 if (PatternType == 0)
8112 return;
8113
Anna Zaks5069aa32012-02-03 01:27:37 +00008114 // Generate the diagnostic.
8115 SourceLocation SL = LenArg->getLocStart();
8116 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00008117 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00008118
8119 // If the function is defined as a builtin macro, do not show macro expansion.
8120 if (SM.isMacroArgExpansion(SL)) {
8121 SL = SM.getSpellingLoc(SL);
8122 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
8123 SM.getSpellingLoc(SR.getEnd()));
8124 }
8125
Anna Zaks13b08572012-08-08 21:42:23 +00008126 // Check if the destination is an array (rather than a pointer to an array).
8127 QualType DstTy = DstArg->getType();
8128 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
8129 Context);
8130 if (!isKnownSizeArray) {
8131 if (PatternType == 1)
8132 Diag(SL, diag::warn_strncat_wrong_size) << SR;
8133 else
8134 Diag(SL, diag::warn_strncat_src_size) << SR;
8135 return;
8136 }
8137
Anna Zaks314cd092012-02-01 19:08:57 +00008138 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00008139 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00008140 else
Anna Zaks5069aa32012-02-03 01:27:37 +00008141 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00008142
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008143 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00008144 llvm::raw_svector_ostream OS(sizeString);
8145 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008146 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00008147 OS << ") - ";
8148 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008149 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00008150 OS << ") - 1";
8151
Anna Zaks5069aa32012-02-03 01:27:37 +00008152 Diag(SL, diag::note_strncat_wrong_size)
8153 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00008154}
8155
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008156//===--- CHECK: Return Address of Stack Variable --------------------------===//
8157
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008158static const Expr *EvalVal(const Expr *E,
8159 SmallVectorImpl<const DeclRefExpr *> &refVars,
8160 const Decl *ParentDecl);
8161static const Expr *EvalAddr(const Expr *E,
8162 SmallVectorImpl<const DeclRefExpr *> &refVars,
8163 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008164
8165/// CheckReturnStackAddr - Check if a return statement returns the address
8166/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008167static void
8168CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
8169 SourceLocation ReturnLoc) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008170 const Expr *stackE = nullptr;
8171 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008172
8173 // Perform checking for returned stack addresses, local blocks,
8174 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00008175 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008176 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008177 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00008178 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008179 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008180 }
8181
Craig Topperc3ec1492014-05-26 06:22:03 +00008182 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008183 return; // Nothing suspicious was found.
8184
Simon Pilgrim750bde62017-03-31 11:00:53 +00008185 // Parameters are initialized in the calling scope, so taking the address
Richard Trieu81b6c562016-08-05 23:24:47 +00008186 // of a parameter reference doesn't need a warning.
8187 for (auto *DRE : refVars)
8188 if (isa<ParmVarDecl>(DRE->getDecl()))
8189 return;
8190
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008191 SourceLocation diagLoc;
8192 SourceRange diagRange;
8193 if (refVars.empty()) {
8194 diagLoc = stackE->getLocStart();
8195 diagRange = stackE->getSourceRange();
8196 } else {
8197 // We followed through a reference variable. 'stackE' contains the
8198 // problematic expression but we will warn at the return statement pointing
8199 // at the reference variable. We will later display the "trail" of
8200 // reference variables using notes.
8201 diagLoc = refVars[0]->getLocStart();
8202 diagRange = refVars[0]->getSourceRange();
8203 }
8204
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008205 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
8206 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00008207 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008208 << DR->getDecl()->getDeclName() << diagRange;
8209 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008210 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008211 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008212 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008213 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00008214 // If there is an LValue->RValue conversion, then the value of the
8215 // reference type is used, not the reference.
8216 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
8217 if (ICE->getCastKind() == CK_LValueToRValue) {
8218 return;
8219 }
8220 }
Craig Topperda7b27f2015-11-17 05:40:09 +00008221 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
8222 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008223 }
8224
8225 // Display the "trail" of reference variables that we followed until we
8226 // found the problematic expression using notes.
8227 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008228 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008229 // If this var binds to another reference var, show the range of the next
8230 // var, otherwise the var binds to the problematic expression, in which case
8231 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008232 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
8233 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008234 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
8235 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008236 }
8237}
8238
8239/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
8240/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008241/// to a location on the stack, a local block, an address of a label, or a
8242/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008243/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008244/// encounter a subexpression that (1) clearly does not lead to one of the
8245/// above problematic expressions (2) is something we cannot determine leads to
8246/// a problematic expression based on such local checking.
8247///
8248/// Both EvalAddr and EvalVal follow through reference variables to evaluate
8249/// the expression that they point to. Such variables are added to the
8250/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008251///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00008252/// EvalAddr processes expressions that are pointers that are used as
8253/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008254/// At the base case of the recursion is a check for the above problematic
8255/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008256///
8257/// This implementation handles:
8258///
8259/// * pointer-to-pointer casts
8260/// * implicit conversions from array references to pointers
8261/// * taking the address of fields
8262/// * arbitrary interplay between "&" and "*" operators
8263/// * pointer arithmetic from an address of a stack variable
8264/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008265static const Expr *EvalAddr(const Expr *E,
8266 SmallVectorImpl<const DeclRefExpr *> &refVars,
8267 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008268 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00008269 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008270
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008271 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00008272 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00008273 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00008274 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00008275 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00008276
Peter Collingbourne91147592011-04-15 00:35:48 +00008277 E = E->IgnoreParens();
8278
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008279 // Our "symbolic interpreter" is just a dispatch off the currently
8280 // viewed AST node. We then recursively traverse the AST by calling
8281 // EvalAddr and EvalVal appropriately.
8282 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008283 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008284 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008285
Richard Smith40f08eb2014-01-30 22:05:38 +00008286 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00008287 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00008288 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00008289
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008290 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008291 // If this is a reference variable, follow through to the expression that
8292 // it points to.
8293 if (V->hasLocalStorage() &&
8294 V->getType()->isReferenceType() && V->hasInit()) {
8295 // Add the reference variable to the "trail".
8296 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008297 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008298 }
8299
Craig Topperc3ec1492014-05-26 06:22:03 +00008300 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008301 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008302
Chris Lattner934edb22007-12-28 05:31:15 +00008303 case Stmt::UnaryOperatorClass: {
8304 // The only unary operator that make sense to handle here
8305 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008306 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008307
John McCalle3027922010-08-25 11:45:40 +00008308 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008309 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008310 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008311 }
Mike Stump11289f42009-09-09 15:08:12 +00008312
Chris Lattner934edb22007-12-28 05:31:15 +00008313 case Stmt::BinaryOperatorClass: {
8314 // Handle pointer arithmetic. All other binary operators are not valid
8315 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008316 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00008317 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00008318
John McCalle3027922010-08-25 11:45:40 +00008319 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00008320 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008321
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008322 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00008323
8324 // Determine which argument is the real pointer base. It could be
8325 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008326 if (!Base->getType()->isPointerType())
8327 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00008328
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008329 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008330 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00008331 }
Steve Naroff2752a172008-09-10 19:17:48 +00008332
Chris Lattner934edb22007-12-28 05:31:15 +00008333 // For conditional operators we need to see if either the LHS or RHS are
8334 // valid DeclRefExpr*s. If one of them is valid, we return it.
8335 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008336 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008337
Chris Lattner934edb22007-12-28 05:31:15 +00008338 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008339 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008340 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008341 // In C++, we can have a throw-expression, which has 'void' type.
8342 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008343 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008344 return LHS;
8345 }
Chris Lattner934edb22007-12-28 05:31:15 +00008346
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008347 // In C++, we can have a throw-expression, which has 'void' type.
8348 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00008349 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008350
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008351 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00008352 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008353
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008354 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00008355 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008356 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00008357 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008358
8359 case Stmt::AddrLabelExprClass:
8360 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00008361
John McCall28fc7092011-11-10 05:35:25 +00008362 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008363 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8364 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00008365
Ted Kremenekc3b4c522008-08-07 00:49:01 +00008366 // For casts, we need to handle conversions from arrays to
8367 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00008368 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00008369 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00008370 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00008371 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00008372 case Stmt::CXXStaticCastExprClass:
8373 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00008374 case Stmt::CXXConstCastExprClass:
8375 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008376 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00008377 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00008378 case CK_LValueToRValue:
8379 case CK_NoOp:
8380 case CK_BaseToDerived:
8381 case CK_DerivedToBase:
8382 case CK_UncheckedDerivedToBase:
8383 case CK_Dynamic:
8384 case CK_CPointerToObjCPointerCast:
8385 case CK_BlockPointerToObjCPointerCast:
8386 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008387 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00008388
8389 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008390 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00008391
Richard Trieudadefde2014-07-02 04:39:38 +00008392 case CK_BitCast:
8393 if (SubExpr->getType()->isAnyPointerType() ||
8394 SubExpr->getType()->isBlockPointerType() ||
8395 SubExpr->getType()->isObjCQualifiedIdType())
8396 return EvalAddr(SubExpr, refVars, ParentDecl);
8397 else
8398 return nullptr;
8399
Eli Friedman8195ad72012-02-23 23:04:32 +00008400 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00008401 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00008402 }
Chris Lattner934edb22007-12-28 05:31:15 +00008403 }
Mike Stump11289f42009-09-09 15:08:12 +00008404
Douglas Gregorfe314812011-06-21 17:03:29 +00008405 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008406 if (const Expr *Result =
8407 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8408 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00008409 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00008410 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008411
Chris Lattner934edb22007-12-28 05:31:15 +00008412 // Everything else: we simply don't reason about them.
8413 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00008414 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00008415 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008416}
Mike Stump11289f42009-09-09 15:08:12 +00008417
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008418/// EvalVal - This function is complements EvalAddr in the mutual recursion.
8419/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008420static const Expr *EvalVal(const Expr *E,
8421 SmallVectorImpl<const DeclRefExpr *> &refVars,
8422 const Decl *ParentDecl) {
8423 do {
8424 // We should only be called for evaluating non-pointer expressions, or
8425 // expressions with a pointer type that are not used as references but
8426 // instead
8427 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00008428
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008429 // Our "symbolic interpreter" is just a dispatch off the currently
8430 // viewed AST node. We then recursively traverse the AST by calling
8431 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00008432
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008433 E = E->IgnoreParens();
8434 switch (E->getStmtClass()) {
8435 case Stmt::ImplicitCastExprClass: {
8436 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
8437 if (IE->getValueKind() == VK_LValue) {
8438 E = IE->getSubExpr();
8439 continue;
8440 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008441 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008442 }
Richard Smith40f08eb2014-01-30 22:05:38 +00008443
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008444 case Stmt::ExprWithCleanupsClass:
8445 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8446 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008447
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008448 case Stmt::DeclRefExprClass: {
8449 // When we hit a DeclRefExpr we are looking at code that refers to a
8450 // variable's name. If it's not a reference variable we check if it has
8451 // local storage within the function, and if so, return the expression.
8452 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8453
8454 // If we leave the immediate function, the lifetime isn't about to end.
8455 if (DR->refersToEnclosingVariableOrCapture())
8456 return nullptr;
8457
8458 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
8459 // Check if it refers to itself, e.g. "int& i = i;".
8460 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008461 return DR;
8462
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008463 if (V->hasLocalStorage()) {
8464 if (!V->getType()->isReferenceType())
8465 return DR;
8466
8467 // Reference variable, follow through to the expression that
8468 // it points to.
8469 if (V->hasInit()) {
8470 // Add the reference variable to the "trail".
8471 refVars.push_back(DR);
8472 return EvalVal(V->getInit(), refVars, V);
8473 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008474 }
8475 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008476
8477 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008478 }
Mike Stump11289f42009-09-09 15:08:12 +00008479
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008480 case Stmt::UnaryOperatorClass: {
8481 // The only unary operator that make sense to handle here
8482 // is Deref. All others don't resolve to a "name." This includes
8483 // handling all sorts of rvalues passed to a unary operator.
8484 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008485
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008486 if (U->getOpcode() == UO_Deref)
8487 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00008488
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008489 return nullptr;
8490 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008491
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008492 case Stmt::ArraySubscriptExprClass: {
8493 // Array subscripts are potential references to data on the stack. We
8494 // retrieve the DeclRefExpr* for the array variable if it indeed
8495 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00008496 const auto *ASE = cast<ArraySubscriptExpr>(E);
8497 if (ASE->isTypeDependent())
8498 return nullptr;
8499 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008500 }
Mike Stump11289f42009-09-09 15:08:12 +00008501
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008502 case Stmt::OMPArraySectionExprClass: {
8503 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8504 ParentDecl);
8505 }
Mike Stump11289f42009-09-09 15:08:12 +00008506
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008507 case Stmt::ConditionalOperatorClass: {
8508 // For conditional operators we need to see if either the LHS or RHS are
8509 // non-NULL Expr's. If one is non-NULL, we return it.
8510 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008511
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008512 // Handle the GNU extension for missing LHS.
8513 if (const Expr *LHSExpr = C->getLHS()) {
8514 // In C++, we can have a throw-expression, which has 'void' type.
8515 if (!LHSExpr->getType()->isVoidType())
8516 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8517 return LHS;
8518 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008519
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008520 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008521 if (C->getRHS()->getType()->isVoidType())
8522 return nullptr;
8523
8524 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008525 }
8526
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008527 // Accesses to members are potential references to data on the stack.
8528 case Stmt::MemberExprClass: {
8529 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00008530
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008531 // Check for indirect access. We only want direct field accesses.
8532 if (M->isArrow())
8533 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008534
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008535 // Check whether the member type is itself a reference, in which case
8536 // we're not going to refer to the member, but to what the member refers
8537 // to.
8538 if (M->getMemberDecl()->getType()->isReferenceType())
8539 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008540
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008541 return EvalVal(M->getBase(), refVars, ParentDecl);
8542 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00008543
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008544 case Stmt::MaterializeTemporaryExprClass:
8545 if (const Expr *Result =
8546 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8547 refVars, ParentDecl))
8548 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008549 return E;
8550
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008551 default:
8552 // Check that we don't return or take the address of a reference to a
8553 // temporary. This is only useful in C++.
8554 if (!E->isTypeDependent() && E->isRValue())
8555 return E;
8556
8557 // Everything else: we simply don't reason about them.
8558 return nullptr;
8559 }
8560 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008561}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008562
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008563void
8564Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8565 SourceLocation ReturnLoc,
8566 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00008567 const AttrVec *Attrs,
8568 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008569 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8570
8571 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00008572 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8573 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00008574 CheckNonNullExpr(*this, RetValExp))
8575 Diag(ReturnLoc, diag::warn_null_ret)
8576 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00008577
8578 // C++11 [basic.stc.dynamic.allocation]p4:
8579 // If an allocation function declared with a non-throwing
8580 // exception-specification fails to allocate storage, it shall return
8581 // a null pointer. Any other allocation function that fails to allocate
8582 // storage shall indicate failure only by throwing an exception [...]
8583 if (FD) {
8584 OverloadedOperatorKind Op = FD->getOverloadedOperator();
8585 if (Op == OO_New || Op == OO_Array_New) {
8586 const FunctionProtoType *Proto
8587 = FD->getType()->castAs<FunctionProtoType>();
Richard Smitheaf11ad2018-05-03 03:58:32 +00008588 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
Artyom Skrobov9f213442014-01-24 11:10:39 +00008589 CheckNonNullExpr(*this, RetValExp))
8590 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8591 << FD << getLangOpts().CPlusPlus11;
8592 }
8593 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008594}
8595
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008596//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8597
8598/// Check for comparisons of floating point operands using != and ==.
8599/// Issue a warning if these are no self-comparisons, as they are not likely
8600/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00008601void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00008602 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8603 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008604
8605 // Special case: check for x == x (which is OK).
8606 // Do not emit warnings for such cases.
8607 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8608 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8609 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00008610 return;
Mike Stump11289f42009-09-09 15:08:12 +00008611
Ted Kremenekeda40e22007-11-29 00:59:04 +00008612 // Special case: check for comparisons against literals that can be exactly
8613 // represented by APFloat. In such cases, do not emit a warning. This
8614 // is a heuristic: often comparison against such literals are used to
8615 // detect if a value in a variable has not changed. This clearly can
8616 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00008617 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8618 if (FLL->isExact())
8619 return;
8620 } else
8621 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8622 if (FLR->isExact())
8623 return;
Mike Stump11289f42009-09-09 15:08:12 +00008624
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008625 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00008626 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008627 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008628 return;
Mike Stump11289f42009-09-09 15:08:12 +00008629
David Blaikie1f4ff152012-07-16 20:47:22 +00008630 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008631 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008632 return;
Mike Stump11289f42009-09-09 15:08:12 +00008633
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008634 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00008635 Diag(Loc, diag::warn_floatingpoint_eq)
8636 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008637}
John McCallca01b222010-01-04 23:21:16 +00008638
John McCall70aa5392010-01-06 05:24:50 +00008639//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8640//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00008641
John McCall70aa5392010-01-06 05:24:50 +00008642namespace {
John McCallca01b222010-01-04 23:21:16 +00008643
John McCall70aa5392010-01-06 05:24:50 +00008644/// Structure recording the 'active' range of an integer-valued
8645/// expression.
8646struct IntRange {
8647 /// The number of bits active in the int.
8648 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00008649
John McCall70aa5392010-01-06 05:24:50 +00008650 /// True if the int is known not to have negative values.
8651 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00008652
John McCall70aa5392010-01-06 05:24:50 +00008653 IntRange(unsigned Width, bool NonNegative)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008654 : Width(Width), NonNegative(NonNegative) {}
John McCallca01b222010-01-04 23:21:16 +00008655
John McCall817d4af2010-11-10 23:38:19 +00008656 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00008657 static IntRange forBoolType() {
8658 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00008659 }
8660
John McCall817d4af2010-11-10 23:38:19 +00008661 /// Returns the range of an opaque value of the given integral type.
8662 static IntRange forValueOfType(ASTContext &C, QualType T) {
8663 return forValueOfCanonicalType(C,
8664 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00008665 }
8666
John McCall817d4af2010-11-10 23:38:19 +00008667 /// Returns the range of an opaque value of a canonical integral type.
8668 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00008669 assert(T->isCanonicalUnqualified());
8670
8671 if (const VectorType *VT = dyn_cast<VectorType>(T))
8672 T = VT->getElementType().getTypePtr();
8673 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8674 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008675 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8676 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00008677
Roman Lebedevca1aaac2017-10-21 16:44:03 +00008678 if (!C.getLangOpts().CPlusPlus) {
8679 // For enum types in C code, use the underlying datatype.
8680 if (const EnumType *ET = dyn_cast<EnumType>(T))
8681 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8682 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8683 // For enum types in C++, use the known bit width of the enumerators.
David Majnemer6a426652013-06-07 22:07:20 +00008684 EnumDecl *Enum = ET->getDecl();
Richard Smith371e9e8a2017-12-06 03:00:51 +00008685 // In C++11, enums can have a fixed underlying type. Use this type to
8686 // compute the range.
8687 if (Enum->isFixed()) {
Erich Keane69dbbb02017-09-21 19:58:55 +00008688 return IntRange(C.getIntWidth(QualType(T, 0)),
8689 !ET->isSignedIntegerOrEnumerationType());
Richard Smith371e9e8a2017-12-06 03:00:51 +00008690 }
John McCall18a2c2c2010-11-09 22:22:12 +00008691
David Majnemer6a426652013-06-07 22:07:20 +00008692 unsigned NumPositive = Enum->getNumPositiveBits();
8693 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00008694
David Majnemer6a426652013-06-07 22:07:20 +00008695 if (NumNegative == 0)
8696 return IntRange(NumPositive, true/*NonNegative*/);
8697 else
8698 return IntRange(std::max(NumPositive + 1, NumNegative),
8699 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00008700 }
John McCall70aa5392010-01-06 05:24:50 +00008701
8702 const BuiltinType *BT = cast<BuiltinType>(T);
8703 assert(BT->isInteger());
8704
8705 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8706 }
8707
John McCall817d4af2010-11-10 23:38:19 +00008708 /// Returns the "target" range of a canonical integral type, i.e.
8709 /// the range of values expressible in the type.
8710 ///
8711 /// This matches forValueOfCanonicalType except that enums have the
8712 /// full range of their type, not the range of their enumerators.
8713 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8714 assert(T->isCanonicalUnqualified());
8715
8716 if (const VectorType *VT = dyn_cast<VectorType>(T))
8717 T = VT->getElementType().getTypePtr();
8718 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8719 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008720 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8721 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008722 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00008723 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008724
8725 const BuiltinType *BT = cast<BuiltinType>(T);
8726 assert(BT->isInteger());
8727
8728 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8729 }
8730
8731 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00008732 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00008733 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00008734 L.NonNegative && R.NonNegative);
8735 }
8736
John McCall817d4af2010-11-10 23:38:19 +00008737 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008738 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008739 return IntRange(std::min(L.Width, R.Width),
8740 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008741 }
8742};
8743
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008744} // namespace
8745
8746static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
8747 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008748 if (value.isSigned() && value.isNegative())
8749 return IntRange(value.getMinSignedBits(), false);
8750
8751 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008752 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008753
8754 // isNonNegative() just checks the sign bit without considering
8755 // signedness.
8756 return IntRange(value.getActiveBits(), true);
8757}
8758
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008759static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8760 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008761 if (result.isInt())
8762 return GetValueRange(C, result.getInt(), MaxWidth);
8763
8764 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008765 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8766 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8767 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8768 R = IntRange::join(R, El);
8769 }
John McCall70aa5392010-01-06 05:24:50 +00008770 return R;
8771 }
8772
8773 if (result.isComplexInt()) {
8774 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8775 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8776 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008777 }
8778
8779 // This can happen with lossless casts to intptr_t of "based" lvalues.
8780 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008781 // FIXME: The only reason we need to pass the type in here is to get
8782 // the sign right on this one case. It would be nice if APValue
8783 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008784 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008785 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008786}
John McCall70aa5392010-01-06 05:24:50 +00008787
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008788static QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008789 QualType Ty = E->getType();
8790 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8791 Ty = AtomicRHS->getValueType();
8792 return Ty;
8793}
8794
John McCall70aa5392010-01-06 05:24:50 +00008795/// Pseudo-evaluate the given integer expression, estimating the
8796/// range of values it might take.
8797///
8798/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008799static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008800 E = E->IgnoreParens();
8801
8802 // Try a full evaluation first.
8803 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008804 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008805 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008806
8807 // I think we only want to look through implicit casts here; if the
8808 // user has an explicit widening cast, we should treat the value as
8809 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008810 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00008811 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00008812 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8813
Eli Friedmane6d33952013-07-08 20:20:06 +00008814 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00008815
George Burgess IVdf1ed002016-01-13 01:52:39 +00008816 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8817 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00008818
John McCall70aa5392010-01-06 05:24:50 +00008819 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00008820 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00008821 return OutputTypeRange;
8822
8823 IntRange SubRange
8824 = GetExprRange(C, CE->getSubExpr(),
8825 std::min(MaxWidth, OutputTypeRange.Width));
8826
8827 // Bail out if the subexpr's range is as wide as the cast type.
8828 if (SubRange.Width >= OutputTypeRange.Width)
8829 return OutputTypeRange;
8830
8831 // Otherwise, we take the smaller width, and we're non-negative if
8832 // either the output type or the subexpr is.
8833 return IntRange(SubRange.Width,
8834 SubRange.NonNegative || OutputTypeRange.NonNegative);
8835 }
8836
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008837 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008838 // If we can fold the condition, just take that operand.
8839 bool CondResult;
8840 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8841 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8842 : CO->getFalseExpr(),
8843 MaxWidth);
8844
8845 // Otherwise, conservatively merge.
8846 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8847 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8848 return IntRange::join(L, R);
8849 }
8850
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008851 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008852 switch (BO->getOpcode()) {
Richard Smithc70f1d62017-12-14 15:16:18 +00008853 case BO_Cmp:
8854 llvm_unreachable("builtin <=> should have class type");
John McCall70aa5392010-01-06 05:24:50 +00008855
8856 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00008857 case BO_LAnd:
8858 case BO_LOr:
8859 case BO_LT:
8860 case BO_GT:
8861 case BO_LE:
8862 case BO_GE:
8863 case BO_EQ:
8864 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00008865 return IntRange::forBoolType();
8866
John McCallc3688382011-07-13 06:35:24 +00008867 // The type of the assignments is the type of the LHS, so the RHS
8868 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00008869 case BO_MulAssign:
8870 case BO_DivAssign:
8871 case BO_RemAssign:
8872 case BO_AddAssign:
8873 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00008874 case BO_XorAssign:
8875 case BO_OrAssign:
8876 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00008877 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00008878
John McCallc3688382011-07-13 06:35:24 +00008879 // Simple assignments just pass through the RHS, which will have
8880 // been coerced to the LHS type.
8881 case BO_Assign:
8882 // TODO: bitfields?
8883 return GetExprRange(C, BO->getRHS(), MaxWidth);
8884
John McCall70aa5392010-01-06 05:24:50 +00008885 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008886 case BO_PtrMemD:
8887 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00008888 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008889
John McCall2ce81ad2010-01-06 22:07:33 +00008890 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00008891 case BO_And:
8892 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00008893 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8894 GetExprRange(C, BO->getRHS(), MaxWidth));
8895
John McCall70aa5392010-01-06 05:24:50 +00008896 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00008897 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00008898 // ...except that we want to treat '1 << (blah)' as logically
8899 // positive. It's an important idiom.
8900 if (IntegerLiteral *I
8901 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8902 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008903 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00008904 return IntRange(R.Width, /*NonNegative*/ true);
8905 }
8906 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008907 LLVM_FALLTHROUGH;
John McCall1bff9932010-04-07 01:14:35 +00008908
John McCalle3027922010-08-25 11:45:40 +00008909 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00008910 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008911
John McCall2ce81ad2010-01-06 22:07:33 +00008912 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00008913 case BO_Shr:
8914 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00008915 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8916
8917 // If the shift amount is a positive constant, drop the width by
8918 // that much.
8919 llvm::APSInt shift;
8920 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8921 shift.isNonNegative()) {
8922 unsigned zext = shift.getZExtValue();
8923 if (zext >= L.Width)
8924 L.Width = (L.NonNegative ? 0 : 1);
8925 else
8926 L.Width -= zext;
8927 }
8928
8929 return L;
8930 }
8931
8932 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008933 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008934 return GetExprRange(C, BO->getRHS(), MaxWidth);
8935
John McCall2ce81ad2010-01-06 22:07:33 +00008936 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008937 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008938 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008939 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008940 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008941
John McCall51431812011-07-14 22:39:48 +00008942 // The width of a division result is mostly determined by the size
8943 // of the LHS.
8944 case BO_Div: {
8945 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008946 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008947 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8948
8949 // If the divisor is constant, use that.
8950 llvm::APSInt divisor;
8951 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8952 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8953 if (log2 >= L.Width)
8954 L.Width = (L.NonNegative ? 0 : 1);
8955 else
8956 L.Width = std::min(L.Width - log2, MaxWidth);
8957 return L;
8958 }
8959
8960 // Otherwise, just use the LHS's width.
8961 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8962 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8963 }
8964
8965 // The result of a remainder can't be larger than the result of
8966 // either side.
8967 case BO_Rem: {
8968 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008969 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008970 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8971 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8972
8973 IntRange meet = IntRange::meet(L, R);
8974 meet.Width = std::min(meet.Width, MaxWidth);
8975 return meet;
8976 }
8977
8978 // The default behavior is okay for these.
8979 case BO_Mul:
8980 case BO_Add:
8981 case BO_Xor:
8982 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008983 break;
8984 }
8985
John McCall51431812011-07-14 22:39:48 +00008986 // The default case is to treat the operation as if it were closed
8987 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008988 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8989 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8990 return IntRange::join(L, R);
8991 }
8992
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008993 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008994 switch (UO->getOpcode()) {
8995 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008996 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008997 return IntRange::forBoolType();
8998
8999 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00009000 case UO_Deref:
9001 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00009002 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009003
9004 default:
9005 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
9006 }
9007 }
9008
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009009 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00009010 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
9011
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009012 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00009013 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00009014 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00009015
Eli Friedmane6d33952013-07-08 20:20:06 +00009016 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009017}
John McCall263a48b2010-01-04 23:31:57 +00009018
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009019static IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00009020 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00009021}
9022
John McCall263a48b2010-01-04 23:31:57 +00009023/// Checks whether the given value, which currently has the given
9024/// source semantics, has the same value when coerced through the
9025/// target semantics.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009026static bool IsSameFloatAfterCast(const llvm::APFloat &value,
9027 const llvm::fltSemantics &Src,
9028 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00009029 llvm::APFloat truncated = value;
9030
9031 bool ignored;
9032 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
9033 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
9034
9035 return truncated.bitwiseIsEqual(value);
9036}
9037
9038/// Checks whether the given value, which currently has the given
9039/// source semantics, has the same value when coerced through the
9040/// target semantics.
9041///
9042/// The value might be a vector of floats (or a complex number).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009043static bool IsSameFloatAfterCast(const APValue &value,
9044 const llvm::fltSemantics &Src,
9045 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00009046 if (value.isFloat())
9047 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
9048
9049 if (value.isVector()) {
9050 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
9051 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
9052 return false;
9053 return true;
9054 }
9055
9056 assert(value.isComplexFloat());
9057 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
9058 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
9059}
9060
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009061static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009062
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009063static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00009064 // Suppress cases where we are comparing against an enum constant.
9065 if (const DeclRefExpr *DR =
9066 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
9067 if (isa<EnumConstantDecl>(DR->getDecl()))
Roman Lebedev6de129e2017-10-15 20:13:17 +00009068 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00009069
9070 // Suppress cases where the '0' value is expanded from a macro.
9071 if (E->getLocStart().isMacroID())
Roman Lebedev6de129e2017-10-15 20:13:17 +00009072 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00009073
Roman Lebedev6de129e2017-10-15 20:13:17 +00009074 return false;
9075}
9076
Richard Smith692f66ab2017-12-06 19:23:19 +00009077static bool isKnownToHaveUnsignedValue(Expr *E) {
9078 return E->getType()->isIntegerType() &&
Roman Lebedev6de129e2017-10-15 20:13:17 +00009079 (!E->getType()->isSignedIntegerType() ||
9080 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
9081}
9082
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009083namespace {
Richard Smitha5370fb2017-12-08 22:57:11 +00009084/// The promoted range of values of a type. In general this has the
9085/// following structure:
9086///
9087/// |-----------| . . . |-----------|
9088/// ^ ^ ^ ^
9089/// Min HoleMin HoleMax Max
9090///
9091/// ... where there is only a hole if a signed type is promoted to unsigned
9092/// (in which case Min and Max are the smallest and largest representable
9093/// values).
9094struct PromotedRange {
9095 // Min, or HoleMax if there is a hole.
9096 llvm::APSInt PromotedMin;
9097 // Max, or HoleMin if there is a hole.
9098 llvm::APSInt PromotedMax;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009099
Richard Smitha5370fb2017-12-08 22:57:11 +00009100 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
9101 if (R.Width == 0)
9102 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
9103 else if (R.Width >= BitWidth && !Unsigned) {
9104 // Promotion made the type *narrower*. This happens when promoting
9105 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
9106 // Treat all values of 'signed int' as being in range for now.
9107 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
9108 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
9109 } else {
9110 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
9111 .extOrTrunc(BitWidth);
9112 PromotedMin.setIsUnsigned(Unsigned);
9113
9114 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
9115 .extOrTrunc(BitWidth);
9116 PromotedMax.setIsUnsigned(Unsigned);
9117 }
9118 }
9119
9120 // Determine whether this range is contiguous (has no hole).
9121 bool isContiguous() const { return PromotedMin <= PromotedMax; }
9122
9123 // Where a constant value is within the range.
9124 enum ComparisonResult {
9125 LT = 0x1,
9126 LE = 0x2,
9127 GT = 0x4,
9128 GE = 0x8,
9129 EQ = 0x10,
9130 NE = 0x20,
9131 InRangeFlag = 0x40,
9132
9133 Less = LE | LT | NE,
9134 Min = LE | InRangeFlag,
9135 InRange = InRangeFlag,
9136 Max = GE | InRangeFlag,
9137 Greater = GE | GT | NE,
9138
9139 OnlyValue = LE | GE | EQ | InRangeFlag,
9140 InHole = NE
9141 };
9142
9143 ComparisonResult compare(const llvm::APSInt &Value) const {
9144 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
9145 Value.isUnsigned() == PromotedMin.isUnsigned());
9146 if (!isContiguous()) {
9147 assert(Value.isUnsigned() && "discontiguous range for signed compare");
9148 if (Value.isMinValue()) return Min;
9149 if (Value.isMaxValue()) return Max;
9150 if (Value >= PromotedMin) return InRange;
9151 if (Value <= PromotedMax) return InRange;
9152 return InHole;
9153 }
9154
9155 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
9156 case -1: return Less;
9157 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
9158 case 1:
9159 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
9160 case -1: return InRange;
9161 case 0: return Max;
9162 case 1: return Greater;
9163 }
9164 }
9165
9166 llvm_unreachable("impossible compare result");
9167 }
9168
Richard Smithc70f1d62017-12-14 15:16:18 +00009169 static llvm::Optional<StringRef>
9170 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
9171 if (Op == BO_Cmp) {
9172 ComparisonResult LTFlag = LT, GTFlag = GT;
9173 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
9174
9175 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
9176 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
9177 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
9178 return llvm::None;
9179 }
9180
Richard Smitha5370fb2017-12-08 22:57:11 +00009181 ComparisonResult TrueFlag, FalseFlag;
9182 if (Op == BO_EQ) {
9183 TrueFlag = EQ;
9184 FalseFlag = NE;
9185 } else if (Op == BO_NE) {
9186 TrueFlag = NE;
9187 FalseFlag = EQ;
9188 } else {
9189 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
9190 TrueFlag = LT;
9191 FalseFlag = GE;
9192 } else {
9193 TrueFlag = GT;
9194 FalseFlag = LE;
9195 }
9196 if (Op == BO_GE || Op == BO_LE)
9197 std::swap(TrueFlag, FalseFlag);
9198 }
9199 if (R & TrueFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00009200 return StringRef("true");
Richard Smitha5370fb2017-12-08 22:57:11 +00009201 if (R & FalseFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00009202 return StringRef("false");
Richard Smitha5370fb2017-12-08 22:57:11 +00009203 return llvm::None;
9204 }
Roman Lebedev6de129e2017-10-15 20:13:17 +00009205};
John McCallcc7e5bf2010-05-06 08:58:33 +00009206}
9207
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009208static bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00009209 // Strip off implicit integral promotions.
9210 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00009211 if (ICE->getCastKind() != CK_IntegralCast &&
9212 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00009213 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00009214 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00009215 }
9216
9217 return E->getType()->isEnumeralType();
9218}
9219
Richard Smith692f66ab2017-12-06 19:23:19 +00009220static int classifyConstantValue(Expr *Constant) {
9221 // The values of this enumeration are used in the diagnostics
9222 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
9223 enum ConstantValueKind {
9224 Miscellaneous = 0,
9225 LiteralTrue,
9226 LiteralFalse
9227 };
9228 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
9229 return BL->getValue() ? ConstantValueKind::LiteralTrue
9230 : ConstantValueKind::LiteralFalse;
9231 return ConstantValueKind::Miscellaneous;
9232}
9233
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009234static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
9235 Expr *Constant, Expr *Other,
9236 const llvm::APSInt &Value,
9237 bool RhsConstant) {
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009238 if (S.inTemplateInstantiation())
9239 return false;
9240
Richard Smitha5370fb2017-12-08 22:57:11 +00009241 Expr *OriginalOther = Other;
9242
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009243 Constant = Constant->IgnoreParenImpCasts();
9244 Other = Other->IgnoreParenImpCasts();
9245
Richard Smitha5370fb2017-12-08 22:57:11 +00009246 // Suppress warnings on tautological comparisons between values of the same
9247 // enumeration type. There are only two ways we could warn on this:
9248 // - If the constant is outside the range of representable values of
9249 // the enumeration. In such a case, we should warn about the cast
9250 // to enumeration type, not about the comparison.
9251 // - If the constant is the maximum / minimum in-range value. For an
9252 // enumeratin type, such comparisons can be meaningful and useful.
9253 if (Constant->getType()->isEnumeralType() &&
9254 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
9255 return false;
9256
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009257 // TODO: Investigate using GetExprRange() to get tighter bounds
9258 // on the bit ranges.
9259 QualType OtherT = Other->getType();
9260 if (const auto *AT = OtherT->getAs<AtomicType>())
9261 OtherT = AT->getValueType();
9262 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
9263
9264 // Whether we're treating Other as being a bool because of the form of
9265 // expression despite it having another type (typically 'int' in C).
9266 bool OtherIsBooleanDespiteType =
9267 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
9268 if (OtherIsBooleanDespiteType)
9269 OtherRange = IntRange::forBoolType();
9270
Richard Smitha5370fb2017-12-08 22:57:11 +00009271 // Determine the promoted range of the other type and see if a comparison of
9272 // the constant against that range is tautological.
9273 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
9274 Value.isUnsigned());
9275 auto Cmp = OtherPromotedRange.compare(Value);
9276 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
9277 if (!Result)
9278 return false;
Hans Wennborg5791ce72017-12-08 16:54:08 +00009279
Richard Smitha5370fb2017-12-08 22:57:11 +00009280 // Suppress the diagnostic for an in-range comparison if the constant comes
9281 // from a macro or enumerator. We don't want to diagnose
9282 //
9283 // some_long_value <= INT_MAX
9284 //
9285 // when sizeof(int) == sizeof(long).
9286 bool InRange = Cmp & PromotedRange::InRangeFlag;
9287 if (InRange && IsEnumConstOrFromMacro(S, Constant))
9288 return false;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009289
9290 // If this is a comparison to an enum constant, include that
9291 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00009292 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009293 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
9294 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
9295
Richard Smitha5370fb2017-12-08 22:57:11 +00009296 // Should be enough for uint128 (39 decimal digits)
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009297 SmallString<64> PrettySourceValue;
9298 llvm::raw_svector_ostream OS(PrettySourceValue);
9299 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00009300 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009301 else
9302 OS << Value;
9303
Richard Smitha5370fb2017-12-08 22:57:11 +00009304 // FIXME: We use a somewhat different formatting for the in-range cases and
9305 // cases involving boolean values for historical reasons. We should pick a
9306 // consistent way of presenting these diagnostics.
9307 if (!InRange || Other->isKnownToHaveBooleanValue()) {
9308 S.DiagRuntimeBehavior(
9309 E->getOperatorLoc(), E,
9310 S.PDiag(!InRange ? diag::warn_out_of_range_compare
9311 : diag::warn_tautological_bool_compare)
9312 << OS.str() << classifyConstantValue(Constant)
9313 << OtherT << OtherIsBooleanDespiteType << *Result
9314 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
9315 } else {
9316 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
9317 ? (HasEnumType(OriginalOther)
9318 ? diag::warn_unsigned_enum_always_true_comparison
9319 : diag::warn_unsigned_always_true_comparison)
9320 : diag::warn_tautological_constant_compare;
Roman Lebedev6de129e2017-10-15 20:13:17 +00009321
Richard Smitha5370fb2017-12-08 22:57:11 +00009322 S.Diag(E->getOperatorLoc(), Diag)
9323 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
9324 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
9325 }
9326
9327 return true;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009328}
9329
John McCallcc7e5bf2010-05-06 08:58:33 +00009330/// Analyze the operands of the given comparison. Implements the
9331/// fallback case from AnalyzeComparison.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009332static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00009333 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9334 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009335}
John McCall263a48b2010-01-04 23:31:57 +00009336
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009337/// Implements -Wsign-compare.
John McCallca01b222010-01-04 23:21:16 +00009338///
Richard Trieu82402a02011-09-15 21:56:47 +00009339/// \param E the binary operator to check for warnings
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009340static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009341 // The type the comparison is being performed in.
9342 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00009343
9344 // Only analyze comparison operators where both sides have been converted to
9345 // the same type.
9346 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
9347 return AnalyzeImpConvsInComparison(S, E);
9348
9349 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00009350 if (E->isValueDependent())
9351 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00009352
Roman Lebedev6de129e2017-10-15 20:13:17 +00009353 Expr *LHS = E->getLHS();
9354 Expr *RHS = E->getRHS();
9355
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009356 if (T->isIntegralType(S.Context)) {
9357 llvm::APSInt RHSValue;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009358 llvm::APSInt LHSValue;
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009359
Roman Lebedev6de129e2017-10-15 20:13:17 +00009360 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
9361 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
Roman Lebedevbd1fc222017-10-12 20:16:51 +00009362
Roman Lebedev6de129e2017-10-15 20:13:17 +00009363 // We don't care about expressions whose result is a constant.
9364 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
9365 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6f405db2017-10-12 22:03:20 +00009366
Roman Lebedev6de129e2017-10-15 20:13:17 +00009367 // We only care about expressions where just one side is literal
9368 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
9369 // Is the constant on the RHS or LHS?
9370 const bool RhsConstant = IsRHSIntegralLiteral;
9371 Expr *Const = RhsConstant ? RHS : LHS;
9372 Expr *Other = RhsConstant ? LHS : RHS;
9373 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
9374
9375 // Check whether an integer constant comparison results in a value
9376 // of 'true' or 'false'.
Roman Lebedev6de129e2017-10-15 20:13:17 +00009377 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
9378 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00009379 }
9380 }
9381
9382 if (!T->hasUnsignedIntegerRepresentation()) {
9383 // We don't do anything special if this isn't an unsigned integral
9384 // comparison: we're only interested in integral comparisons, and
9385 // signed comparisons only happen in cases we don't care to warn about.
Roman Lebedev6f405db2017-10-12 22:03:20 +00009386 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00009387 }
9388
9389 LHS = LHS->IgnoreParenImpCasts();
9390 RHS = RHS->IgnoreParenImpCasts();
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009391
Alex Lorenzb57409f2018-02-07 20:45:39 +00009392 if (!S.getLangOpts().CPlusPlus) {
9393 // Avoid warning about comparison of integers with different signs when
9394 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
9395 // the type of `E`.
9396 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
9397 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9398 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
9399 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9400 }
9401
John McCallcc7e5bf2010-05-06 08:58:33 +00009402 // Check to see if one of the (unmodified) operands is of different
9403 // signedness.
9404 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00009405 if (LHS->getType()->hasSignedIntegerRepresentation()) {
9406 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00009407 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00009408 signedOperand = LHS;
9409 unsignedOperand = RHS;
9410 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
9411 signedOperand = RHS;
9412 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00009413 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00009414 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00009415 }
9416
John McCallcc7e5bf2010-05-06 08:58:33 +00009417 // Otherwise, calculate the effective range of the signed operand.
9418 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00009419
John McCallcc7e5bf2010-05-06 08:58:33 +00009420 // Go ahead and analyze implicit conversions in the operands. Note
9421 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00009422 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
9423 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00009424
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009425 // If the signed range is non-negative, -Wsign-compare won't fire.
John McCallcc7e5bf2010-05-06 08:58:33 +00009426 if (signedRange.NonNegative)
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009427 return;
John McCallca01b222010-01-04 23:21:16 +00009428
9429 // For (in)equality comparisons, if the unsigned operand is a
9430 // constant which cannot collide with a overflowed signed operand,
9431 // then reinterpreting the signed operand as unsigned will not
9432 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00009433 if (E->isEqualityOp()) {
9434 unsigned comparisonWidth = S.Context.getIntWidth(T);
9435 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00009436
John McCallcc7e5bf2010-05-06 08:58:33 +00009437 // We should never be unable to prove that the unsigned operand is
9438 // non-negative.
9439 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
9440
9441 if (unsignedRange.Width < comparisonWidth)
9442 return;
9443 }
9444
Douglas Gregorbfb4a212012-05-01 01:53:49 +00009445 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9446 S.PDiag(diag::warn_mixed_sign_comparison)
9447 << LHS->getType() << RHS->getType()
9448 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00009449}
9450
John McCall1f425642010-11-11 03:21:53 +00009451/// Analyzes an attempt to assign the given value to a bitfield.
9452///
9453/// Returns true if there was something fishy about the attempt.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009454static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9455 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00009456 assert(Bitfield->isBitField());
9457 if (Bitfield->isInvalidDecl())
9458 return false;
9459
John McCalldeebbcf2010-11-11 05:33:51 +00009460 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00009461 QualType BitfieldType = Bitfield->getType();
9462 if (BitfieldType->isBooleanType())
9463 return false;
9464
9465 if (BitfieldType->isEnumeralType()) {
9466 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9467 // If the underlying enum type was not explicitly specified as an unsigned
9468 // type and the enum contain only positive values, MSVC++ will cause an
9469 // inconsistency by storing this as a signed type.
9470 if (S.getLangOpts().CPlusPlus11 &&
9471 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9472 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9473 BitfieldEnumDecl->getNumNegativeBits() == 0) {
9474 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9475 << BitfieldEnumDecl->getNameAsString();
9476 }
9477 }
9478
John McCalldeebbcf2010-11-11 05:33:51 +00009479 if (Bitfield->getType()->isBooleanType())
9480 return false;
9481
Douglas Gregor789adec2011-02-04 13:09:01 +00009482 // Ignore value- or type-dependent expressions.
9483 if (Bitfield->getBitWidth()->isValueDependent() ||
9484 Bitfield->getBitWidth()->isTypeDependent() ||
9485 Init->isValueDependent() ||
9486 Init->isTypeDependent())
9487 return false;
9488
John McCall1f425642010-11-11 03:21:53 +00009489 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00009490 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00009491
Richard Smith5fab0c92011-12-28 19:48:30 +00009492 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009493 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9494 Expr::SE_AllowSideEffects)) {
9495 // The RHS is not constant. If the RHS has an enum type, make sure the
9496 // bitfield is wide enough to hold all the values of the enum without
9497 // truncation.
9498 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9499 EnumDecl *ED = EnumTy->getDecl();
9500 bool SignedBitfield = BitfieldType->isSignedIntegerType();
9501
9502 // Enum types are implicitly signed on Windows, so check if there are any
9503 // negative enumerators to see if the enum was intended to be signed or
9504 // not.
9505 bool SignedEnum = ED->getNumNegativeBits() > 0;
9506
9507 // Check for surprising sign changes when assigning enum values to a
9508 // bitfield of different signedness. If the bitfield is signed and we
9509 // have exactly the right number of bits to store this unsigned enum,
9510 // suggest changing the enum to an unsigned type. This typically happens
9511 // on Windows where unfixed enums always use an underlying type of 'int'.
9512 unsigned DiagID = 0;
9513 if (SignedEnum && !SignedBitfield) {
9514 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9515 } else if (SignedBitfield && !SignedEnum &&
9516 ED->getNumPositiveBits() == FieldWidth) {
9517 DiagID = diag::warn_signed_bitfield_enum_conversion;
9518 }
9519
9520 if (DiagID) {
9521 S.Diag(InitLoc, DiagID) << Bitfield << ED;
9522 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9523 SourceRange TypeRange =
9524 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9525 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9526 << SignedEnum << TypeRange;
9527 }
9528
9529 // Compute the required bitwidth. If the enum has negative values, we need
9530 // one more bit than the normal number of positive bits to represent the
9531 // sign bit.
9532 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9533 ED->getNumNegativeBits())
9534 : ED->getNumPositiveBits();
9535
9536 // Check the bitwidth.
9537 if (BitsNeeded > FieldWidth) {
9538 Expr *WidthExpr = Bitfield->getBitWidth();
9539 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9540 << Bitfield << ED;
9541 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9542 << BitsNeeded << ED << WidthExpr->getSourceRange();
9543 }
9544 }
9545
John McCall1f425642010-11-11 03:21:53 +00009546 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009547 }
John McCall1f425642010-11-11 03:21:53 +00009548
John McCall1f425642010-11-11 03:21:53 +00009549 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00009550
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009551 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00009552 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009553 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9554 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00009555
John McCall1f425642010-11-11 03:21:53 +00009556 if (OriginalWidth <= FieldWidth)
9557 return false;
9558
Eli Friedmanc267a322012-01-26 23:11:39 +00009559 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00009560 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00009561 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00009562
Eli Friedmanc267a322012-01-26 23:11:39 +00009563 // Check whether the stored value is equal to the original value.
9564 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00009565 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00009566 return false;
9567
Eli Friedmanc267a322012-01-26 23:11:39 +00009568 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00009569 // therefore don't strictly fit into a signed bitfield of width 1.
9570 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00009571 return false;
9572
John McCall1f425642010-11-11 03:21:53 +00009573 std::string PrettyValue = Value.toString(10);
9574 std::string PrettyTrunc = TruncatedValue.toString(10);
9575
9576 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9577 << PrettyValue << PrettyTrunc << OriginalInit->getType()
9578 << Init->getSourceRange();
9579
9580 return true;
9581}
9582
John McCalld2a53122010-11-09 23:24:47 +00009583/// Analyze the given simple or compound assignment for warning-worthy
9584/// operations.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009585static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00009586 // Just recurse on the LHS.
9587 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9588
9589 // We want to recurse on the RHS as normal unless we're assigning to
9590 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00009591 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009592 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00009593 E->getOperatorLoc())) {
9594 // Recurse, ignoring any implicit conversions on the RHS.
9595 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9596 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00009597 }
9598 }
9599
9600 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9601}
9602
John McCall263a48b2010-01-04 23:31:57 +00009603/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009604static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9605 SourceLocation CContext, unsigned diag,
9606 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009607 if (pruneControlFlow) {
9608 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9609 S.PDiag(diag)
9610 << SourceType << T << E->getSourceRange()
9611 << SourceRange(CContext));
9612 return;
9613 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00009614 S.Diag(E->getExprLoc(), diag)
9615 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9616}
9617
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009618/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009619static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
9620 SourceLocation CContext,
9621 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009622 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009623}
9624
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +00009625/// Analyze the given compound assignment for the possible losing of
9626/// floating-point precision.
9627static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
9628 assert(isa<CompoundAssignOperator>(E) &&
9629 "Must be compound assignment operation");
9630 // Recurse on the LHS and RHS in here
9631 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9632 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9633
9634 // Now check the outermost expression
9635 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
9636 const auto *RBT = cast<CompoundAssignOperator>(E)
9637 ->getComputationResultType()
9638 ->getAs<BuiltinType>();
9639
9640 // If both source and target are floating points.
9641 if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint())
9642 // Builtin FP kinds are ordered by increasing FP rank.
9643 if (ResultBT->getKind() < RBT->getKind())
9644 // We don't want to warn for system macro.
9645 if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
9646 // warn about dropping FP rank.
9647 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(),
9648 E->getOperatorLoc(),
9649 diag::warn_impcast_float_result_precision);
9650}
Richard Trieube234c32016-04-21 21:04:55 +00009651
9652/// Diagnose an implicit cast from a floating point value to an integer value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009653static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9654 SourceLocation CContext) {
Richard Trieube234c32016-04-21 21:04:55 +00009655 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00009656 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00009657
9658 Expr *InnerE = E->IgnoreParenImpCasts();
9659 // We also want to warn on, e.g., "int i = -1.234"
9660 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9661 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9662 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9663
9664 const bool IsLiteral =
9665 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9666
9667 llvm::APFloat Value(0.0);
9668 bool IsConstant =
9669 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9670 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00009671 return DiagnoseImpCast(S, E, T, CContext,
9672 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00009673 }
9674
Chandler Carruth016ef402011-04-10 08:36:24 +00009675 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00009676
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00009677 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9678 T->hasUnsignedIntegerRepresentation());
Erich Keanea4c48c62018-05-08 21:26:21 +00009679 llvm::APFloat::opStatus Result = Value.convertToInteger(
9680 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
9681
9682 if (Result == llvm::APFloat::opOK && isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00009683 if (IsLiteral) return;
9684 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9685 PruneWarnings);
9686 }
9687
Erich Keanea4c48c62018-05-08 21:26:21 +00009688 // Conversion of a floating-point value to a non-bool integer where the
9689 // integral part cannot be represented by the integer type is undefined.
9690 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
9691 return DiagnoseImpCast(
9692 S, E, T, CContext,
9693 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
Richard Trieua2b8fe62018-05-14 23:21:48 +00009694 : diag::warn_impcast_float_to_integer_out_of_range,
9695 PruneWarnings);
Erich Keanea4c48c62018-05-08 21:26:21 +00009696
Richard Trieube234c32016-04-21 21:04:55 +00009697 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00009698 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00009699 // Warn on floating point literal to integer.
9700 DiagID = diag::warn_impcast_literal_float_to_integer;
9701 } else if (IntegerValue == 0) {
9702 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
9703 return DiagnoseImpCast(S, E, T, CContext,
9704 diag::warn_impcast_float_integer, PruneWarnings);
9705 }
9706 // Warn on non-zero to zero conversion.
9707 DiagID = diag::warn_impcast_float_to_integer_zero;
9708 } else {
9709 if (IntegerValue.isUnsigned()) {
9710 if (!IntegerValue.isMaxValue()) {
9711 return DiagnoseImpCast(S, E, T, CContext,
9712 diag::warn_impcast_float_integer, PruneWarnings);
9713 }
9714 } else { // IntegerValue.isSigned()
9715 if (!IntegerValue.isMaxSignedValue() &&
9716 !IntegerValue.isMinSignedValue()) {
9717 return DiagnoseImpCast(S, E, T, CContext,
9718 diag::warn_impcast_float_integer, PruneWarnings);
9719 }
9720 }
9721 // Warn on evaluatable floating point expression to integer conversion.
9722 DiagID = diag::warn_impcast_float_to_integer;
9723 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009724
Eli Friedman07185912013-08-29 23:44:43 +00009725 // FIXME: Force the precision of the source value down so we don't print
9726 // digits which are usually useless (we don't really care here if we
9727 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9728 // would automatically print the shortest representation, but it's a bit
9729 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00009730 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00009731 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9732 precision = (precision * 59 + 195) / 196;
9733 Value.toString(PrettySourceValue, precision);
9734
David Blaikie9b88cc02012-05-15 17:18:27 +00009735 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00009736 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00009737 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00009738 else
David Blaikie9b88cc02012-05-15 17:18:27 +00009739 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00009740
Richard Trieube234c32016-04-21 21:04:55 +00009741 if (PruneWarnings) {
9742 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9743 S.PDiag(DiagID)
9744 << E->getType() << T.getUnqualifiedType()
9745 << PrettySourceValue << PrettyTargetValue
9746 << E->getSourceRange() << SourceRange(CContext));
9747 } else {
9748 S.Diag(E->getExprLoc(), DiagID)
9749 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9750 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9751 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009752}
9753
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009754static std::string PrettyPrintInRange(const llvm::APSInt &Value,
9755 IntRange Range) {
John McCall18a2c2c2010-11-09 22:22:12 +00009756 if (!Range.Width) return "0";
9757
9758 llvm::APSInt ValueInRange = Value;
9759 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00009760 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00009761 return ValueInRange.toString(10);
9762}
9763
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009764static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009765 if (!isa<ImplicitCastExpr>(Ex))
9766 return false;
9767
9768 Expr *InnerE = Ex->IgnoreParenImpCasts();
9769 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9770 const Type *Source =
9771 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9772 if (Target->isDependentType())
9773 return false;
9774
9775 const BuiltinType *FloatCandidateBT =
9776 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9777 const Type *BoolCandidateType = ToBool ? Target : Source;
9778
9779 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9780 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9781}
9782
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009783static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9784 SourceLocation CC) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009785 unsigned NumArgs = TheCall->getNumArgs();
9786 for (unsigned i = 0; i < NumArgs; ++i) {
9787 Expr *CurrA = TheCall->getArg(i);
9788 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9789 continue;
9790
9791 bool IsSwapped = ((i > 0) &&
9792 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9793 IsSwapped |= ((i < (NumArgs - 1)) &&
9794 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9795 if (IsSwapped) {
9796 // Warn on this floating-point to bool conversion.
9797 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9798 CurrA->getType(), CC,
9799 diag::warn_impcast_floating_point_to_bool);
9800 }
9801 }
9802}
9803
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009804static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
9805 SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009806 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9807 E->getExprLoc()))
9808 return;
9809
Richard Trieu09d6b802016-01-08 23:35:06 +00009810 // Don't warn on functions which have return type nullptr_t.
9811 if (isa<CallExpr>(E))
9812 return;
9813
Richard Trieu5b993502014-10-15 03:42:06 +00009814 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9815 const Expr::NullPointerConstantKind NullKind =
9816 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9817 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9818 return;
9819
9820 // Return if target type is a safe conversion.
9821 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9822 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9823 return;
9824
9825 SourceLocation Loc = E->getSourceRange().getBegin();
9826
Richard Trieu0a5e1662016-02-13 00:58:53 +00009827 // Venture through the macro stacks to get to the source of macro arguments.
9828 // The new location is a better location than the complete location that was
9829 // passed in.
George Karpenkov441e8fd2018-02-09 23:30:07 +00009830 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
9831 CC = S.SourceMgr.getTopMacroCallerLoc(CC);
Richard Trieu0a5e1662016-02-13 00:58:53 +00009832
Richard Trieu5b993502014-10-15 03:42:06 +00009833 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00009834 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9835 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9836 Loc, S.SourceMgr, S.getLangOpts());
9837 if (MacroName == "NULL")
Richard Smithb5f81712018-04-30 05:25:48 +00009838 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
Richard Trieu5b993502014-10-15 03:42:06 +00009839 }
9840
9841 // Only warn if the null and context location are in the same macro expansion.
9842 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9843 return;
9844
9845 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009846 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
Richard Trieu5b993502014-10-15 03:42:06 +00009847 << FixItHint::CreateReplacement(Loc,
9848 S.getFixItZeroLiteralForType(T, Loc));
9849}
9850
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009851static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9852 ObjCArrayLiteral *ArrayLiteral);
9853
9854static void
9855checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9856 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00009857
9858/// Check a single element within a collection literal against the
9859/// target element type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009860static void checkObjCCollectionLiteralElement(Sema &S,
9861 QualType TargetElementType,
9862 Expr *Element,
9863 unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009864 // Skip a bitcast to 'id' or qualified 'id'.
9865 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9866 if (ICE->getCastKind() == CK_BitCast &&
9867 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9868 Element = ICE->getSubExpr();
9869 }
9870
9871 QualType ElementType = Element->getType();
9872 ExprResult ElementResult(Element);
9873 if (ElementType->getAs<ObjCObjectPointerType>() &&
9874 S.CheckSingleAssignmentConstraints(TargetElementType,
9875 ElementResult,
9876 false, false)
9877 != Sema::Compatible) {
9878 S.Diag(Element->getLocStart(),
9879 diag::warn_objc_collection_literal_element)
9880 << ElementType << ElementKind << TargetElementType
9881 << Element->getSourceRange();
9882 }
9883
9884 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9885 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9886 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9887 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9888}
9889
9890/// Check an Objective-C array literal being converted to the given
9891/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009892static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9893 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009894 if (!S.NSArrayDecl)
9895 return;
9896
9897 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9898 if (!TargetObjCPtr)
9899 return;
9900
9901 if (TargetObjCPtr->isUnspecialized() ||
9902 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9903 != S.NSArrayDecl->getCanonicalDecl())
9904 return;
9905
9906 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9907 if (TypeArgs.size() != 1)
9908 return;
9909
9910 QualType TargetElementType = TypeArgs[0];
9911 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9912 checkObjCCollectionLiteralElement(S, TargetElementType,
9913 ArrayLiteral->getElement(I),
9914 0);
9915 }
9916}
9917
9918/// Check an Objective-C dictionary literal being converted to the given
9919/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009920static void
9921checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9922 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009923 if (!S.NSDictionaryDecl)
9924 return;
9925
9926 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9927 if (!TargetObjCPtr)
9928 return;
9929
9930 if (TargetObjCPtr->isUnspecialized() ||
9931 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9932 != S.NSDictionaryDecl->getCanonicalDecl())
9933 return;
9934
9935 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9936 if (TypeArgs.size() != 2)
9937 return;
9938
9939 QualType TargetKeyType = TypeArgs[0];
9940 QualType TargetObjectType = TypeArgs[1];
9941 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9942 auto Element = DictionaryLiteral->getKeyValueElement(I);
9943 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9944 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9945 }
9946}
9947
Richard Trieufc404c72016-02-05 23:02:38 +00009948// Helper function to filter out cases for constant width constant conversion.
9949// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009950static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9951 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00009952 // If initializing from a constant, and the constant starts with '0',
9953 // then it is a binary, octal, or hexadecimal. Allow these constants
9954 // to fill all the bits, even if there is a sign change.
9955 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9956 const char FirstLiteralCharacter =
9957 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9958 if (FirstLiteralCharacter == '0')
9959 return false;
9960 }
9961
9962 // If the CC location points to a '{', and the type is char, then assume
9963 // assume it is an array initialization.
9964 if (CC.isValid() && T->isCharType()) {
9965 const char FirstContextCharacter =
9966 S.getSourceManager().getCharacterData(CC)[0];
9967 if (FirstContextCharacter == '{')
9968 return false;
9969 }
9970
9971 return true;
9972}
9973
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009974static void
9975CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
9976 bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009977 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00009978
John McCallcc7e5bf2010-05-06 08:58:33 +00009979 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9980 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9981 if (Source == Target) return;
9982 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00009983
Chandler Carruthc22845a2011-07-26 05:40:03 +00009984 // If the conversion context location is invalid don't complain. We also
9985 // don't want to emit a warning if the issue occurs from the expansion of
9986 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9987 // delay this check as long as possible. Once we detect we are in that
9988 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009989 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00009990 return;
9991
Richard Trieu021baa32011-09-23 20:10:00 +00009992 // Diagnose implicit casts to bool.
9993 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9994 if (isa<StringLiteral>(E))
9995 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00009996 // and expressions, for instance, assert(0 && "error here"), are
9997 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00009998 return DiagnoseImpCast(S, E, T, CC,
9999 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +000010000 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
10001 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
10002 // This covers the literal expressions that evaluate to Objective-C
10003 // objects.
10004 return DiagnoseImpCast(S, E, T, CC,
10005 diag::warn_impcast_objective_c_literal_to_bool);
10006 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010007 if (Source->isPointerType() || Source->canDecayToPointerType()) {
10008 // Warn on pointer to bool conversion that is always true.
10009 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
10010 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +000010011 }
Richard Trieu021baa32011-09-23 20:10:00 +000010012 }
John McCall263a48b2010-01-04 23:31:57 +000010013
Douglas Gregor5054cb02015-07-07 03:58:22 +000010014 // Check implicit casts from Objective-C collection literals to specialized
10015 // collection types, e.g., NSArray<NSString *> *.
10016 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
10017 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
10018 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
10019 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
10020
John McCall263a48b2010-01-04 23:31:57 +000010021 // Strip vector types.
10022 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010023 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010024 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010025 return;
John McCallacf0ee52010-10-08 02:01:28 +000010026 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010027 }
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010028
Chris Lattneree7286f2011-06-14 04:51:15 +000010029 // If the vector cast is cast between two vectors of the same size, it is
10030 // a bitcast, not a conversion.
10031 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
10032 return;
John McCall263a48b2010-01-04 23:31:57 +000010033
10034 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
10035 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
10036 }
Stephen Canon3ba640d2014-04-03 10:33:25 +000010037 if (auto VecTy = dyn_cast<VectorType>(Target))
10038 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +000010039
10040 // Strip complex types.
10041 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010042 if (!isa<ComplexType>(Target)) {
Tim Northover02416372017-08-08 23:18:05 +000010043 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010044 return;
10045
Tim Northover02416372017-08-08 23:18:05 +000010046 return DiagnoseImpCast(S, E, T, CC,
10047 S.getLangOpts().CPlusPlus
10048 ? diag::err_impcast_complex_scalar
10049 : diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010050 }
John McCall263a48b2010-01-04 23:31:57 +000010051
10052 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
10053 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
10054 }
10055
10056 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
10057 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
10058
10059 // If the source is floating point...
10060 if (SourceBT && SourceBT->isFloatingPoint()) {
10061 // ...and the target is floating point...
10062 if (TargetBT && TargetBT->isFloatingPoint()) {
10063 // ...then warn if we're dropping FP rank.
10064
10065 // Builtin FP kinds are ordered by increasing FP rank.
10066 if (SourceBT->getKind() > TargetBT->getKind()) {
10067 // Don't warn about float constants that are precisely
10068 // representable in the target type.
10069 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +000010070 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +000010071 // Value might be a float, a float vector, or a float complex.
10072 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +000010073 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
10074 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +000010075 return;
10076 }
10077
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010078 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010079 return;
10080
John McCallacf0ee52010-10-08 02:01:28 +000010081 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +000010082 }
10083 // ... or possibly if we're increasing rank, too
10084 else if (TargetBT->getKind() > SourceBT->getKind()) {
10085 if (S.SourceMgr.isInSystemMacro(CC))
10086 return;
10087
10088 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +000010089 }
10090 return;
10091 }
10092
Richard Trieube234c32016-04-21 21:04:55 +000010093 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +000010094 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010095 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010096 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +000010097
Richard Trieube234c32016-04-21 21:04:55 +000010098 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +000010099 }
John McCall263a48b2010-01-04 23:31:57 +000010100
Richard Smith54894fd2015-12-30 01:06:52 +000010101 // Detect the case where a call result is converted from floating-point to
10102 // to bool, and the final argument to the call is converted from bool, to
10103 // discover this typo:
10104 //
10105 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
10106 //
10107 // FIXME: This is an incredibly special case; is there some more general
10108 // way to detect this class of misplaced-parentheses bug?
10109 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010110 // Check last argument of function call to see if it is an
10111 // implicit cast from a type matching the type the result
10112 // is being cast to.
10113 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +000010114 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010115 Expr *LastA = CEx->getArg(NumArgs - 1);
10116 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +000010117 if (isa<ImplicitCastExpr>(LastA) &&
10118 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010119 // Warn on this floating-point to bool conversion
10120 DiagnoseImpCast(S, E, T, CC,
10121 diag::warn_impcast_floating_point_to_bool);
10122 }
10123 }
10124 }
John McCall263a48b2010-01-04 23:31:57 +000010125 return;
10126 }
10127
Richard Trieu5b993502014-10-15 03:42:06 +000010128 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +000010129
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010130 S.DiscardMisalignedMemberAddress(Target, E);
10131
David Blaikie9366d2b2012-06-19 21:19:06 +000010132 if (!Source->isIntegerType() || !Target->isIntegerType())
10133 return;
10134
David Blaikie7555b6a2012-05-15 16:56:36 +000010135 // TODO: remove this early return once the false positives for constant->bool
10136 // in templates, macros, etc, are reduced or removed.
10137 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
10138 return;
10139
John McCallcc7e5bf2010-05-06 08:58:33 +000010140 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +000010141 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +000010142
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010143 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +000010144 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010145 // TODO: this should happen for bitfield stores, too.
10146 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +000010147 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010148 if (S.SourceMgr.isInSystemMacro(CC))
10149 return;
10150
John McCall18a2c2c2010-11-09 22:22:12 +000010151 std::string PrettySourceValue = Value.toString(10);
10152 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010153
Ted Kremenek33ba9952011-10-22 02:37:33 +000010154 S.DiagRuntimeBehavior(E->getExprLoc(), E,
10155 S.PDiag(diag::warn_impcast_integer_precision_constant)
10156 << PrettySourceValue << PrettyTargetValue
10157 << E->getType() << T << E->getSourceRange()
10158 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +000010159 return;
10160 }
10161
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010162 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
10163 if (S.SourceMgr.isInSystemMacro(CC))
10164 return;
10165
David Blaikie9455da02012-04-12 22:40:54 +000010166 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +000010167 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
10168 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +000010169 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +000010170 }
10171
Richard Trieudcb55572016-01-29 23:51:16 +000010172 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
10173 SourceRange.NonNegative && Source->isSignedIntegerType()) {
10174 // Warn when doing a signed to signed conversion, warn if the positive
10175 // source value is exactly the width of the target type, which will
10176 // cause a negative value to be stored.
10177
10178 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +000010179 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
10180 !S.SourceMgr.isInSystemMacro(CC)) {
10181 if (isSameWidthConstantConversion(S, E, T, CC)) {
10182 std::string PrettySourceValue = Value.toString(10);
10183 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +000010184
Richard Trieufc404c72016-02-05 23:02:38 +000010185 S.DiagRuntimeBehavior(
10186 E->getExprLoc(), E,
10187 S.PDiag(diag::warn_impcast_integer_precision_constant)
10188 << PrettySourceValue << PrettyTargetValue << E->getType() << T
10189 << E->getSourceRange() << clang::SourceRange(CC));
10190 return;
Richard Trieudcb55572016-01-29 23:51:16 +000010191 }
10192 }
Richard Trieufc404c72016-02-05 23:02:38 +000010193
Richard Trieudcb55572016-01-29 23:51:16 +000010194 // Fall through for non-constants to give a sign conversion warning.
10195 }
10196
John McCallcc7e5bf2010-05-06 08:58:33 +000010197 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
10198 (!TargetRange.NonNegative && SourceRange.NonNegative &&
10199 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010200 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010201 return;
10202
John McCallcc7e5bf2010-05-06 08:58:33 +000010203 unsigned DiagID = diag::warn_impcast_integer_sign;
10204
10205 // Traditionally, gcc has warned about this under -Wsign-compare.
10206 // We also want to warn about it in -Wconversion.
10207 // So if -Wconversion is off, use a completely identical diagnostic
10208 // in the sign-compare group.
10209 // The conditional-checking code will
10210 if (ICContext) {
10211 DiagID = diag::warn_impcast_integer_sign_conditional;
10212 *ICContext = true;
10213 }
10214
John McCallacf0ee52010-10-08 02:01:28 +000010215 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +000010216 }
10217
Douglas Gregora78f1932011-02-22 02:45:07 +000010218 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +000010219 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
10220 // type, to give us better diagnostics.
10221 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000010222 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +000010223 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10224 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
10225 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
10226 SourceType = S.Context.getTypeDeclType(Enum);
10227 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
10228 }
10229 }
10230
Douglas Gregora78f1932011-02-22 02:45:07 +000010231 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
10232 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +000010233 if (SourceEnum->getDecl()->hasNameForLinkage() &&
10234 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010235 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010236 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010237 return;
10238
Douglas Gregor364f7db2011-03-12 00:14:31 +000010239 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +000010240 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010241 }
John McCall263a48b2010-01-04 23:31:57 +000010242}
10243
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010244static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10245 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010246
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010247static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
10248 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010249 E = E->IgnoreParenImpCasts();
10250
10251 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +000010252 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010253
John McCallacf0ee52010-10-08 02:01:28 +000010254 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010255 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000010256 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +000010257}
10258
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010259static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10260 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +000010261 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +000010262
10263 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +000010264 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
10265 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000010266
10267 // If -Wconversion would have warned about either of the candidates
10268 // for a signedness conversion to the context type...
10269 if (!Suspicious) return;
10270
10271 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010272 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +000010273 return;
10274
John McCallcc7e5bf2010-05-06 08:58:33 +000010275 // ...then check whether it would have warned about either of the
10276 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +000010277 if (E->getType() == T) return;
10278
10279 Suspicious = false;
10280 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
10281 E->getType(), CC, &Suspicious);
10282 if (!Suspicious)
10283 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +000010284 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000010285}
10286
Richard Trieu65724892014-11-15 06:37:39 +000010287/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10288/// Input argument E is a logical expression.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010289static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +000010290 if (S.getLangOpts().Bool)
10291 return;
10292 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
10293}
10294
John McCallcc7e5bf2010-05-06 08:58:33 +000010295/// AnalyzeImplicitConversions - Find and report any interesting
10296/// implicit conversions in the given expression. There are a couple
10297/// of competing diagnostics here, -Wconversion and -Wsign-compare.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010298static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
10299 SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +000010300 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +000010301 Expr *E = OrigE->IgnoreParenImpCasts();
10302
Douglas Gregor6e8da6a2011-10-10 17:38:18 +000010303 if (E->isTypeDependent() || E->isValueDependent())
10304 return;
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010305
John McCallcc7e5bf2010-05-06 08:58:33 +000010306 // For conditional operators, we analyze the arguments as if they
10307 // were being fed directly into the output.
10308 if (isa<ConditionalOperator>(E)) {
10309 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +000010310 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010311 return;
10312 }
10313
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010314 // Check implicit argument conversions for function calls.
10315 if (CallExpr *Call = dyn_cast<CallExpr>(E))
10316 CheckImplicitArgumentConversions(S, Call, CC);
10317
John McCallcc7e5bf2010-05-06 08:58:33 +000010318 // Go ahead and check any implicit conversions we might have skipped.
10319 // The non-canonical typecheck is just an optimization;
10320 // CheckImplicitConversion will filter out dead implicit conversions.
10321 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000010322 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010323
10324 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +000010325
10326 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
10327 // The bound subexpressions in a PseudoObjectExpr are not reachable
10328 // as transitive children.
10329 // FIXME: Use a more uniform representation for this.
10330 for (auto *SE : POE->semantics())
10331 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
10332 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +000010333 }
Richard Smithd7bed4d2015-11-22 02:57:17 +000010334
John McCallcc7e5bf2010-05-06 08:58:33 +000010335 // Skip past explicit casts.
10336 if (isa<ExplicitCastExpr>(E)) {
10337 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +000010338 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010339 }
10340
John McCalld2a53122010-11-09 23:24:47 +000010341 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10342 // Do a somewhat different check with comparison operators.
10343 if (BO->isComparisonOp())
10344 return AnalyzeComparison(S, BO);
10345
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010346 // And with simple assignments.
10347 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +000010348 return AnalyzeAssignment(S, BO);
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010349 // And with compound assignments.
10350 if (BO->isAssignmentOp())
10351 return AnalyzeCompoundAssignment(S, BO);
John McCalld2a53122010-11-09 23:24:47 +000010352 }
John McCallcc7e5bf2010-05-06 08:58:33 +000010353
10354 // These break the otherwise-useful invariant below. Fortunately,
10355 // we don't really need to recurse into them, because any internal
10356 // expressions should have been analyzed already when they were
10357 // built into statements.
10358 if (isa<StmtExpr>(E)) return;
10359
10360 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +000010361 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +000010362
10363 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +000010364 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +000010365 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +000010366 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +000010367 for (Stmt *SubStmt : E->children()) {
10368 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +000010369 if (!ChildExpr)
10370 continue;
10371
Richard Trieu955231d2014-01-25 01:10:35 +000010372 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +000010373 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +000010374 // Ignore checking string literals that are in logical and operators.
10375 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +000010376 continue;
10377 AnalyzeImplicitConversions(S, ChildExpr, CC);
10378 }
Richard Trieu791b86e2014-11-19 06:08:18 +000010379
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010380 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +000010381 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
10382 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000010383 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +000010384
10385 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
10386 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000010387 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010388 }
Richard Trieu791b86e2014-11-19 06:08:18 +000010389
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010390 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
10391 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +000010392 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010393}
10394
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000010395/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000010396static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
10397 // Taking into account implicit conversions,
10398 // allow any integer.
10399 if (!E->getType()->isIntegerType()) {
10400 S.Diag(E->getLocStart(),
10401 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
10402 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010403 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000010404 // Potentially emit standard warnings for implicit conversions if enabled
10405 // using -Wconversion.
10406 CheckImplicitConversion(S, E, IntT, E->getLocStart());
10407 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010408}
10409
Richard Trieuc1888e02014-06-28 23:25:37 +000010410// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
10411// Returns true when emitting a warning about taking the address of a reference.
10412static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +000010413 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +000010414 E = E->IgnoreParenImpCasts();
10415
10416 const FunctionDecl *FD = nullptr;
10417
10418 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10419 if (!DRE->getDecl()->getType()->isReferenceType())
10420 return false;
10421 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10422 if (!M->getMemberDecl()->getType()->isReferenceType())
10423 return false;
10424 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +000010425 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +000010426 return false;
10427 FD = Call->getDirectCallee();
10428 } else {
10429 return false;
10430 }
10431
10432 SemaRef.Diag(E->getExprLoc(), PD);
10433
10434 // If possible, point to location of function.
10435 if (FD) {
10436 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
10437 }
10438
10439 return true;
10440}
10441
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010442// Returns true if the SourceLocation is expanded from any macro body.
10443// Returns false if the SourceLocation is invalid, is from not in a macro
10444// expansion, or is from expanded from a top-level macro argument.
10445static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
10446 if (Loc.isInvalid())
10447 return false;
10448
10449 while (Loc.isMacroID()) {
10450 if (SM.isMacroBodyExpansion(Loc))
10451 return true;
10452 Loc = SM.getImmediateMacroCallerLoc(Loc);
10453 }
10454
10455 return false;
10456}
10457
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010458/// Diagnose pointers that are always non-null.
Richard Trieu3bb8b562014-02-26 02:36:06 +000010459/// \param E the expression containing the pointer
10460/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
10461/// compared to a null pointer
10462/// \param IsEqual True when the comparison is equal to a null pointer
10463/// \param Range Extra SourceRange to highlight in the diagnostic
10464void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
10465 Expr::NullPointerConstantKind NullKind,
10466 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +000010467 if (!E)
10468 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010469
10470 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010471 if (E->getExprLoc().isMacroID()) {
10472 const SourceManager &SM = getSourceManager();
10473 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
10474 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +000010475 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010476 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010477 E = E->IgnoreImpCasts();
10478
10479 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10480
Richard Trieuf7432752014-06-06 21:39:26 +000010481 if (isa<CXXThisExpr>(E)) {
10482 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10483 : diag::warn_this_bool_conversion;
10484 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10485 return;
10486 }
10487
Richard Trieu3bb8b562014-02-26 02:36:06 +000010488 bool IsAddressOf = false;
10489
10490 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10491 if (UO->getOpcode() != UO_AddrOf)
10492 return;
10493 IsAddressOf = true;
10494 E = UO->getSubExpr();
10495 }
10496
Richard Trieuc1888e02014-06-28 23:25:37 +000010497 if (IsAddressOf) {
10498 unsigned DiagID = IsCompare
10499 ? diag::warn_address_of_reference_null_compare
10500 : diag::warn_address_of_reference_bool_conversion;
10501 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10502 << IsEqual;
10503 if (CheckForReference(*this, E, PD)) {
10504 return;
10505 }
10506 }
10507
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010508 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10509 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +000010510 std::string Str;
10511 llvm::raw_string_ostream S(Str);
10512 E->printPretty(S, nullptr, getPrintingPolicy());
10513 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10514 : diag::warn_cast_nonnull_to_bool;
10515 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10516 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010517 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +000010518 };
10519
10520 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10521 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10522 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010523 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10524 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010525 return;
10526 }
10527 }
10528 }
10529
Richard Trieu3bb8b562014-02-26 02:36:06 +000010530 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +000010531 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010532 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10533 D = R->getDecl();
10534 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10535 D = M->getMemberDecl();
10536 }
10537
10538 // Weak Decls can be null.
10539 if (!D || D->isWeak())
10540 return;
George Burgess IV850269a2015-12-08 22:02:00 +000010541
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010542 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +000010543 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10544 if (getCurFunction() &&
10545 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010546 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10547 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010548 return;
10549 }
10550
10551 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +000010552 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +000010553 assert(ParamIter != FD->param_end());
10554 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10555
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010556 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10557 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010558 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +000010559 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010560 }
George Burgess IV850269a2015-12-08 22:02:00 +000010561
Joel E. Denny81508102018-03-13 14:51:22 +000010562 for (const ParamIdx &ArgNo : NonNull->args()) {
10563 if (ArgNo.getASTIndex() == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010564 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010565 return;
10566 }
George Burgess IV850269a2015-12-08 22:02:00 +000010567 }
10568 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010569 }
10570 }
George Burgess IV850269a2015-12-08 22:02:00 +000010571 }
10572
Richard Trieu3bb8b562014-02-26 02:36:06 +000010573 QualType T = D->getType();
10574 const bool IsArray = T->isArrayType();
10575 const bool IsFunction = T->isFunctionType();
10576
Richard Trieuc1888e02014-06-28 23:25:37 +000010577 // Address of function is used to silence the function warning.
10578 if (IsAddressOf && IsFunction) {
10579 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010580 }
10581
10582 // Found nothing.
10583 if (!IsAddressOf && !IsFunction && !IsArray)
10584 return;
10585
10586 // Pretty print the expression for the diagnostic.
10587 std::string Str;
10588 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +000010589 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +000010590
10591 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10592 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +000010593 enum {
10594 AddressOf,
10595 FunctionPointer,
10596 ArrayPointer
10597 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010598 if (IsAddressOf)
10599 DiagType = AddressOf;
10600 else if (IsFunction)
10601 DiagType = FunctionPointer;
10602 else if (IsArray)
10603 DiagType = ArrayPointer;
10604 else
10605 llvm_unreachable("Could not determine diagnostic.");
10606 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10607 << Range << IsEqual;
10608
10609 if (!IsFunction)
10610 return;
10611
10612 // Suggest '&' to silence the function warning.
10613 Diag(E->getExprLoc(), diag::note_function_warning_silence)
10614 << FixItHint::CreateInsertion(E->getLocStart(), "&");
10615
10616 // Check to see if '()' fixit should be emitted.
10617 QualType ReturnType;
10618 UnresolvedSet<4> NonTemplateOverloads;
10619 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10620 if (ReturnType.isNull())
10621 return;
10622
10623 if (IsCompare) {
10624 // There are two cases here. If there is null constant, the only suggest
10625 // for a pointer return type. If the null is 0, then suggest if the return
10626 // type is a pointer or an integer type.
10627 if (!ReturnType->isPointerType()) {
10628 if (NullKind == Expr::NPCK_ZeroExpression ||
10629 NullKind == Expr::NPCK_ZeroLiteral) {
10630 if (!ReturnType->isIntegerType())
10631 return;
10632 } else {
10633 return;
10634 }
10635 }
10636 } else { // !IsCompare
10637 // For function to bool, only suggest if the function pointer has bool
10638 // return type.
10639 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10640 return;
10641 }
10642 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +000010643 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +000010644}
10645
John McCallcc7e5bf2010-05-06 08:58:33 +000010646/// Diagnoses "dangerous" implicit conversions within the given
10647/// expression (which is a full expression). Implements -Wconversion
10648/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +000010649///
10650/// \param CC the "context" location of the implicit conversion, i.e.
10651/// the most location of the syntactic entity requiring the implicit
10652/// conversion
10653void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010654 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +000010655 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +000010656 return;
10657
10658 // Don't diagnose for value- or type-dependent expressions.
10659 if (E->isTypeDependent() || E->isValueDependent())
10660 return;
10661
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010662 // Check for array bounds violations in cases where the check isn't triggered
10663 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10664 // ArraySubscriptExpr is on the RHS of a variable initialization.
10665 CheckArrayAccess(E);
10666
John McCallacf0ee52010-10-08 02:01:28 +000010667 // This is not the right CC for (e.g.) a variable initialization.
10668 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010669}
10670
Richard Trieu65724892014-11-15 06:37:39 +000010671/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10672/// Input argument E is a logical expression.
10673void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10674 ::CheckBoolLikeConversion(*this, E, CC);
10675}
10676
Richard Smith9f7df0c2017-06-26 23:19:32 +000010677/// Diagnose when expression is an integer constant expression and its evaluation
10678/// results in integer overflow
10679void Sema::CheckForIntOverflow (Expr *E) {
10680 // Use a work list to deal with nested struct initializers.
10681 SmallVector<Expr *, 2> Exprs(1, E);
10682
10683 do {
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010684 Expr *OriginalE = Exprs.pop_back_val();
10685 Expr *E = OriginalE->IgnoreParenCasts();
Richard Smith9f7df0c2017-06-26 23:19:32 +000010686
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010687 if (isa<BinaryOperator>(E)) {
10688 E->EvaluateForOverflow(Context);
Richard Smith9f7df0c2017-06-26 23:19:32 +000010689 continue;
10690 }
10691
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010692 if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
Richard Smith9f7df0c2017-06-26 23:19:32 +000010693 Exprs.append(InitList->inits().begin(), InitList->inits().end());
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010694 else if (isa<ObjCBoxedExpr>(OriginalE))
10695 E->EvaluateForOverflow(Context);
10696 else if (auto Call = dyn_cast<CallExpr>(E))
10697 Exprs.append(Call->arg_begin(), Call->arg_end());
10698 else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
10699 Exprs.append(Message->arg_begin(), Message->arg_end());
Richard Smith9f7df0c2017-06-26 23:19:32 +000010700 } while (!Exprs.empty());
10701}
10702
Richard Smithc406cb72013-01-17 01:17:56 +000010703namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010704
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010705/// Visitor for expressions which looks for unsequenced operations on the
Richard Smithc406cb72013-01-17 01:17:56 +000010706/// same object.
10707class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010708 using Base = EvaluatedExprVisitor<SequenceChecker>;
Richard Smithe3dbfe02013-06-30 10:40:20 +000010709
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010710 /// A tree of sequenced regions within an expression. Two regions are
Richard Smithc406cb72013-01-17 01:17:56 +000010711 /// unsequenced if one is an ancestor or a descendent of the other. When we
10712 /// finish processing an expression with sequencing, such as a comma
10713 /// expression, we fold its tree nodes into its parent, since they are
10714 /// unsequenced with respect to nodes we will visit later.
10715 class SequenceTree {
10716 struct Value {
10717 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10718 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +000010719 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +000010720 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010721 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +000010722
10723 public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010724 /// A region within an expression which may be sequenced with respect
Richard Smithc406cb72013-01-17 01:17:56 +000010725 /// to some other region.
10726 class Seq {
Richard Smithc406cb72013-01-17 01:17:56 +000010727 friend class SequenceTree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010728
10729 unsigned Index = 0;
10730
10731 explicit Seq(unsigned N) : Index(N) {}
10732
Richard Smithc406cb72013-01-17 01:17:56 +000010733 public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010734 Seq() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010735 };
10736
10737 SequenceTree() { Values.push_back(Value(0)); }
10738 Seq root() const { return Seq(0); }
10739
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010740 /// Create a new sequence of operations, which is an unsequenced
Richard Smithc406cb72013-01-17 01:17:56 +000010741 /// subset of \p Parent. This sequence of operations is sequenced with
10742 /// respect to other children of \p Parent.
10743 Seq allocate(Seq Parent) {
10744 Values.push_back(Value(Parent.Index));
10745 return Seq(Values.size() - 1);
10746 }
10747
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010748 /// Merge a sequence of operations into its parent.
Richard Smithc406cb72013-01-17 01:17:56 +000010749 void merge(Seq S) {
10750 Values[S.Index].Merged = true;
10751 }
10752
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010753 /// Determine whether two operations are unsequenced. This operation
Richard Smithc406cb72013-01-17 01:17:56 +000010754 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10755 /// should have been merged into its parent as appropriate.
10756 bool isUnsequenced(Seq Cur, Seq Old) {
10757 unsigned C = representative(Cur.Index);
10758 unsigned Target = representative(Old.Index);
10759 while (C >= Target) {
10760 if (C == Target)
10761 return true;
10762 C = Values[C].Parent;
10763 }
10764 return false;
10765 }
10766
10767 private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010768 /// Pick a representative for a sequence.
Richard Smithc406cb72013-01-17 01:17:56 +000010769 unsigned representative(unsigned K) {
10770 if (Values[K].Merged)
10771 // Perform path compression as we go.
10772 return Values[K].Parent = representative(Values[K].Parent);
10773 return K;
10774 }
10775 };
10776
10777 /// An object for which we can track unsequenced uses.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010778 using Object = NamedDecl *;
Richard Smithc406cb72013-01-17 01:17:56 +000010779
10780 /// Different flavors of object usage which we track. We only track the
10781 /// least-sequenced usage of each kind.
10782 enum UsageKind {
10783 /// A read of an object. Multiple unsequenced reads are OK.
10784 UK_Use,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010785
Richard Smithc406cb72013-01-17 01:17:56 +000010786 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000010787 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000010788 UK_ModAsValue,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010789
Richard Smithc406cb72013-01-17 01:17:56 +000010790 /// A modification of an object which is not sequenced before the value
10791 /// computation of the expression, such as n++.
10792 UK_ModAsSideEffect,
10793
10794 UK_Count = UK_ModAsSideEffect + 1
10795 };
10796
10797 struct Usage {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010798 Expr *Use = nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010799 SequenceTree::Seq Seq;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010800
10801 Usage() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010802 };
10803
10804 struct UsageInfo {
Richard Smithc406cb72013-01-17 01:17:56 +000010805 Usage Uses[UK_Count];
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010806
Richard Smithc406cb72013-01-17 01:17:56 +000010807 /// Have we issued a diagnostic for this variable already?
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010808 bool Diagnosed = false;
10809
10810 UsageInfo() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010811 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010812 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
Richard Smithc406cb72013-01-17 01:17:56 +000010813
10814 Sema &SemaRef;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010815
Richard Smithc406cb72013-01-17 01:17:56 +000010816 /// Sequenced regions within the expression.
10817 SequenceTree Tree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010818
Richard Smithc406cb72013-01-17 01:17:56 +000010819 /// Declaration modifications and references which we have seen.
10820 UsageInfoMap UsageMap;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010821
Richard Smithc406cb72013-01-17 01:17:56 +000010822 /// The region we are currently within.
10823 SequenceTree::Seq Region;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010824
Richard Smithc406cb72013-01-17 01:17:56 +000010825 /// Filled in with declarations which were modified as a side-effect
10826 /// (that is, post-increment operations).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010827 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
10828
Richard Smithd33f5202013-01-17 23:18:09 +000010829 /// Expressions to check later. We defer checking these to reduce
10830 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010831 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000010832
10833 /// RAII object wrapping the visitation of a sequenced subexpression of an
10834 /// expression. At the end of this process, the side-effects of the evaluation
10835 /// become sequenced with respect to the value computation of the result, so
10836 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10837 /// UK_ModAsValue.
10838 struct SequencedSubexpression {
10839 SequencedSubexpression(SequenceChecker &Self)
10840 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10841 Self.ModAsSideEffect = &ModAsSideEffect;
10842 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010843
Richard Smithc406cb72013-01-17 01:17:56 +000010844 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000010845 for (auto &M : llvm::reverse(ModAsSideEffect)) {
10846 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000010847 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000010848 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10849 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000010850 }
10851 Self.ModAsSideEffect = OldModAsSideEffect;
10852 }
10853
10854 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010855 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010856 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000010857 };
10858
Richard Smith40238f02013-06-20 22:21:56 +000010859 /// RAII object wrapping the visitation of a subexpression which we might
10860 /// choose to evaluate as a constant. If any subexpression is evaluated and
10861 /// found to be non-constant, this allows us to suppress the evaluation of
10862 /// the outer expression.
10863 class EvaluationTracker {
10864 public:
10865 EvaluationTracker(SequenceChecker &Self)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010866 : Self(Self), Prev(Self.EvalTracker) {
Richard Smith40238f02013-06-20 22:21:56 +000010867 Self.EvalTracker = this;
10868 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010869
Richard Smith40238f02013-06-20 22:21:56 +000010870 ~EvaluationTracker() {
10871 Self.EvalTracker = Prev;
10872 if (Prev)
10873 Prev->EvalOK &= EvalOK;
10874 }
10875
10876 bool evaluate(const Expr *E, bool &Result) {
10877 if (!EvalOK || E->isValueDependent())
10878 return false;
10879 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10880 return EvalOK;
10881 }
10882
10883 private:
10884 SequenceChecker &Self;
10885 EvaluationTracker *Prev;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010886 bool EvalOK = true;
10887 } *EvalTracker = nullptr;
Richard Smith40238f02013-06-20 22:21:56 +000010888
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010889 /// Find the object which is produced by the specified expression,
Richard Smithc406cb72013-01-17 01:17:56 +000010890 /// if any.
10891 Object getObject(Expr *E, bool Mod) const {
10892 E = E->IgnoreParenCasts();
10893 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10894 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10895 return getObject(UO->getSubExpr(), Mod);
10896 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10897 if (BO->getOpcode() == BO_Comma)
10898 return getObject(BO->getRHS(), Mod);
10899 if (Mod && BO->isAssignmentOp())
10900 return getObject(BO->getLHS(), Mod);
10901 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10902 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10903 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10904 return ME->getMemberDecl();
10905 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10906 // FIXME: If this is a reference, map through to its value.
10907 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000010908 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010909 }
10910
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010911 /// Note that an object was modified or used by an expression.
Richard Smithc406cb72013-01-17 01:17:56 +000010912 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10913 Usage &U = UI.Uses[UK];
10914 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10915 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10916 ModAsSideEffect->push_back(std::make_pair(O, U));
10917 U.Use = Ref;
10918 U.Seq = Region;
10919 }
10920 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010921
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010922 /// Check whether a modification or use conflicts with a prior usage.
Richard Smithc406cb72013-01-17 01:17:56 +000010923 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10924 bool IsModMod) {
10925 if (UI.Diagnosed)
10926 return;
10927
10928 const Usage &U = UI.Uses[OtherKind];
10929 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10930 return;
10931
10932 Expr *Mod = U.Use;
10933 Expr *ModOrUse = Ref;
10934 if (OtherKind == UK_Use)
10935 std::swap(Mod, ModOrUse);
10936
10937 SemaRef.Diag(Mod->getExprLoc(),
10938 IsModMod ? diag::warn_unsequenced_mod_mod
10939 : diag::warn_unsequenced_mod_use)
10940 << O << SourceRange(ModOrUse->getExprLoc());
10941 UI.Diagnosed = true;
10942 }
10943
10944 void notePreUse(Object O, Expr *Use) {
10945 UsageInfo &U = UsageMap[O];
10946 // Uses conflict with other modifications.
10947 checkUsage(O, U, Use, UK_ModAsValue, false);
10948 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010949
Richard Smithc406cb72013-01-17 01:17:56 +000010950 void notePostUse(Object O, Expr *Use) {
10951 UsageInfo &U = UsageMap[O];
10952 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10953 addUsage(U, O, Use, UK_Use);
10954 }
10955
10956 void notePreMod(Object O, Expr *Mod) {
10957 UsageInfo &U = UsageMap[O];
10958 // Modifications conflict with other modifications and with uses.
10959 checkUsage(O, U, Mod, UK_ModAsValue, true);
10960 checkUsage(O, U, Mod, UK_Use, false);
10961 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010962
Richard Smithc406cb72013-01-17 01:17:56 +000010963 void notePostMod(Object O, Expr *Use, UsageKind UK) {
10964 UsageInfo &U = UsageMap[O];
10965 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10966 addUsage(U, O, Use, UK);
10967 }
10968
10969public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010970 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010971 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
Richard Smithc406cb72013-01-17 01:17:56 +000010972 Visit(E);
10973 }
10974
10975 void VisitStmt(Stmt *S) {
10976 // Skip all statements which aren't expressions for now.
10977 }
10978
10979 void VisitExpr(Expr *E) {
10980 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000010981 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000010982 }
10983
10984 void VisitCastExpr(CastExpr *E) {
10985 Object O = Object();
10986 if (E->getCastKind() == CK_LValueToRValue)
10987 O = getObject(E->getSubExpr(), false);
10988
10989 if (O)
10990 notePreUse(O, E);
10991 VisitExpr(E);
10992 if (O)
10993 notePostUse(O, E);
10994 }
10995
10996 void VisitBinComma(BinaryOperator *BO) {
10997 // C++11 [expr.comma]p1:
10998 // Every value computation and side effect associated with the left
10999 // expression is sequenced before every value computation and side
11000 // effect associated with the right expression.
11001 SequenceTree::Seq LHS = Tree.allocate(Region);
11002 SequenceTree::Seq RHS = Tree.allocate(Region);
11003 SequenceTree::Seq OldRegion = Region;
11004
11005 {
11006 SequencedSubexpression SeqLHS(*this);
11007 Region = LHS;
11008 Visit(BO->getLHS());
11009 }
11010
11011 Region = RHS;
11012 Visit(BO->getRHS());
11013
11014 Region = OldRegion;
11015
11016 // Forget that LHS and RHS are sequenced. They are both unsequenced
11017 // with respect to other stuff.
11018 Tree.merge(LHS);
11019 Tree.merge(RHS);
11020 }
11021
11022 void VisitBinAssign(BinaryOperator *BO) {
11023 // The modification is sequenced after the value computation of the LHS
11024 // and RHS, so check it before inspecting the operands and update the
11025 // map afterwards.
11026 Object O = getObject(BO->getLHS(), true);
11027 if (!O)
11028 return VisitExpr(BO);
11029
11030 notePreMod(O, BO);
11031
11032 // C++11 [expr.ass]p7:
11033 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
11034 // only once.
11035 //
11036 // Therefore, for a compound assignment operator, O is considered used
11037 // everywhere except within the evaluation of E1 itself.
11038 if (isa<CompoundAssignOperator>(BO))
11039 notePreUse(O, BO);
11040
11041 Visit(BO->getLHS());
11042
11043 if (isa<CompoundAssignOperator>(BO))
11044 notePostUse(O, BO);
11045
11046 Visit(BO->getRHS());
11047
Richard Smith83e37bee2013-06-26 23:16:51 +000011048 // C++11 [expr.ass]p1:
11049 // the assignment is sequenced [...] before the value computation of the
11050 // assignment expression.
11051 // C11 6.5.16/3 has no such rule.
11052 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11053 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000011054 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011055
Richard Smithc406cb72013-01-17 01:17:56 +000011056 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
11057 VisitBinAssign(CAO);
11058 }
11059
11060 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11061 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11062 void VisitUnaryPreIncDec(UnaryOperator *UO) {
11063 Object O = getObject(UO->getSubExpr(), true);
11064 if (!O)
11065 return VisitExpr(UO);
11066
11067 notePreMod(O, UO);
11068 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000011069 // C++11 [expr.pre.incr]p1:
11070 // the expression ++x is equivalent to x+=1
11071 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11072 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000011073 }
11074
11075 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11076 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11077 void VisitUnaryPostIncDec(UnaryOperator *UO) {
11078 Object O = getObject(UO->getSubExpr(), true);
11079 if (!O)
11080 return VisitExpr(UO);
11081
11082 notePreMod(O, UO);
11083 Visit(UO->getSubExpr());
11084 notePostMod(O, UO, UK_ModAsSideEffect);
11085 }
11086
11087 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
11088 void VisitBinLOr(BinaryOperator *BO) {
11089 // The side-effects of the LHS of an '&&' are sequenced before the
11090 // value computation of the RHS, and hence before the value computation
11091 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
11092 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000011093 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000011094 {
11095 SequencedSubexpression Sequenced(*this);
11096 Visit(BO->getLHS());
11097 }
11098
11099 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011100 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000011101 if (!Result)
11102 Visit(BO->getRHS());
11103 } else {
11104 // Check for unsequenced operations in the RHS, treating it as an
11105 // entirely separate evaluation.
11106 //
11107 // FIXME: If there are operations in the RHS which are unsequenced
11108 // with respect to operations outside the RHS, and those operations
11109 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000011110 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000011111 }
Richard Smithc406cb72013-01-17 01:17:56 +000011112 }
11113 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000011114 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000011115 {
11116 SequencedSubexpression Sequenced(*this);
11117 Visit(BO->getLHS());
11118 }
11119
11120 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011121 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000011122 if (Result)
11123 Visit(BO->getRHS());
11124 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000011125 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000011126 }
Richard Smithc406cb72013-01-17 01:17:56 +000011127 }
11128
11129 // Only visit the condition, unless we can be sure which subexpression will
11130 // be chosen.
11131 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000011132 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000011133 {
11134 SequencedSubexpression Sequenced(*this);
11135 Visit(CO->getCond());
11136 }
Richard Smithc406cb72013-01-17 01:17:56 +000011137
11138 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011139 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000011140 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000011141 else {
Richard Smithd33f5202013-01-17 23:18:09 +000011142 WorkList.push_back(CO->getTrueExpr());
11143 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000011144 }
Richard Smithc406cb72013-01-17 01:17:56 +000011145 }
11146
Richard Smithe3dbfe02013-06-30 10:40:20 +000011147 void VisitCallExpr(CallExpr *CE) {
11148 // C++11 [intro.execution]p15:
11149 // When calling a function [...], every value computation and side effect
11150 // associated with any argument expression, or with the postfix expression
11151 // designating the called function, is sequenced before execution of every
11152 // expression or statement in the body of the function [and thus before
11153 // the value computation of its result].
11154 SequencedSubexpression Sequenced(*this);
11155 Base::VisitCallExpr(CE);
11156
11157 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
11158 }
11159
Richard Smithc406cb72013-01-17 01:17:56 +000011160 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000011161 // This is a call, so all subexpressions are sequenced before the result.
11162 SequencedSubexpression Sequenced(*this);
11163
Richard Smithc406cb72013-01-17 01:17:56 +000011164 if (!CCE->isListInitialization())
11165 return VisitExpr(CCE);
11166
11167 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011168 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000011169 SequenceTree::Seq Parent = Region;
11170 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
11171 E = CCE->arg_end();
11172 I != E; ++I) {
11173 Region = Tree.allocate(Parent);
11174 Elts.push_back(Region);
11175 Visit(*I);
11176 }
11177
11178 // Forget that the initializers are sequenced.
11179 Region = Parent;
11180 for (unsigned I = 0; I < Elts.size(); ++I)
11181 Tree.merge(Elts[I]);
11182 }
11183
11184 void VisitInitListExpr(InitListExpr *ILE) {
11185 if (!SemaRef.getLangOpts().CPlusPlus11)
11186 return VisitExpr(ILE);
11187
11188 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011189 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000011190 SequenceTree::Seq Parent = Region;
11191 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
11192 Expr *E = ILE->getInit(I);
11193 if (!E) continue;
11194 Region = Tree.allocate(Parent);
11195 Elts.push_back(Region);
11196 Visit(E);
11197 }
11198
11199 // Forget that the initializers are sequenced.
11200 Region = Parent;
11201 for (unsigned I = 0; I < Elts.size(); ++I)
11202 Tree.merge(Elts[I]);
11203 }
11204};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011205
11206} // namespace
Richard Smithc406cb72013-01-17 01:17:56 +000011207
11208void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011209 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000011210 WorkList.push_back(E);
11211 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000011212 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000011213 SequenceChecker(*this, Item, WorkList);
11214 }
Richard Smithc406cb72013-01-17 01:17:56 +000011215}
11216
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011217void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
11218 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000011219 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000011220 if (!E->isInstantiationDependent())
11221 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011222 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000011223 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011224 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000011225}
11226
John McCall1f425642010-11-11 03:21:53 +000011227void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
11228 FieldDecl *BitField,
11229 Expr *Init) {
11230 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
11231}
11232
David Majnemer61a5bbf2015-04-07 22:08:51 +000011233static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
11234 SourceLocation Loc) {
11235 if (!PType->isVariablyModifiedType())
11236 return;
11237 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
11238 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
11239 return;
11240 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000011241 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
11242 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
11243 return;
11244 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000011245 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
11246 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
11247 return;
11248 }
11249
11250 const ArrayType *AT = S.Context.getAsArrayType(PType);
11251 if (!AT)
11252 return;
11253
11254 if (AT->getSizeModifier() != ArrayType::Star) {
11255 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
11256 return;
11257 }
11258
11259 S.Diag(Loc, diag::err_array_star_in_function_definition);
11260}
11261
Mike Stump0c2ec772010-01-21 03:59:47 +000011262/// CheckParmsForFunctionDef - Check that the parameters of the given
11263/// function are appropriate for the definition of a function. This
11264/// takes care of any checks that cannot be performed on the
11265/// declaration itself, e.g., that the types of each of the function
11266/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000011267bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000011268 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011269 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000011270 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011271 // C99 6.7.5.3p4: the parameters in a parameter type list in a
11272 // function declarator that is part of a function definition of
11273 // that function shall not have incomplete type.
11274 //
11275 // This is also C++ [dcl.fct]p6.
11276 if (!Param->isInvalidDecl() &&
11277 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011278 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011279 Param->setInvalidDecl();
11280 HasInvalidParm = true;
11281 }
11282
11283 // C99 6.9.1p5: If the declarator includes a parameter type list, the
11284 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000011285 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000011286 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000011287 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000011288 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000011289 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000011290
11291 // C99 6.7.5.3p12:
11292 // If the function declarator is not part of a definition of that
11293 // function, parameters may have incomplete type and may use the [*]
11294 // notation in their sequences of declarator specifiers to specify
11295 // variable length array types.
11296 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000011297 // FIXME: This diagnostic should point the '[*]' if source-location
11298 // information is added for it.
11299 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000011300
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011301 // If the parameter is a c++ class type and it has to be destructed in the
11302 // callee function, declare the destructor so that it can be called by the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000011303 // callee function. Do not perform any direct access check on the dtor here.
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011304 if (!Param->isInvalidDecl()) {
11305 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
11306 if (!ClassDecl->isInvalidDecl() &&
11307 !ClassDecl->hasIrrelevantDestructor() &&
11308 !ClassDecl->isDependentContext() &&
Akira Hatanaka85282972018-05-15 21:00:30 +000011309 ClassDecl->isParamDestroyedInCallee()) {
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011310 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11311 MarkFunctionReferenced(Param->getLocation(), Destructor);
11312 DiagnoseUseOfDecl(Destructor, Param->getLocation());
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000011313 }
11314 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000011315 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011316
11317 // Parameters with the pass_object_size attribute only need to be marked
11318 // constant at function definitions. Because we lack information about
11319 // whether we're on a declaration or definition when we're instantiating the
11320 // attribute, we need to check for constness here.
11321 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
11322 if (!Param->getType().isConstQualified())
11323 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
11324 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000011325 }
11326
11327 return HasInvalidParm;
11328}
John McCall2b5c1b22010-08-12 21:44:57 +000011329
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000011330/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
11331/// or MemberExpr.
11332static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
11333 ASTContext &Context) {
11334 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
11335 return Context.getDeclAlign(DRE->getDecl());
11336
11337 if (const auto *ME = dyn_cast<MemberExpr>(E))
11338 return Context.getDeclAlign(ME->getMemberDecl());
11339
11340 return TypeAlign;
11341}
11342
John McCall2b5c1b22010-08-12 21:44:57 +000011343/// CheckCastAlign - Implements -Wcast-align, which warns when a
11344/// pointer cast increases the alignment requirements.
11345void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
11346 // This is actually a lot of work to potentially be doing on every
11347 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011348 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000011349 return;
11350
11351 // Ignore dependent types.
11352 if (T->isDependentType() || Op->getType()->isDependentType())
11353 return;
11354
11355 // Require that the destination be a pointer type.
11356 const PointerType *DestPtr = T->getAs<PointerType>();
11357 if (!DestPtr) return;
11358
11359 // If the destination has alignment 1, we're done.
11360 QualType DestPointee = DestPtr->getPointeeType();
11361 if (DestPointee->isIncompleteType()) return;
11362 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
11363 if (DestAlign.isOne()) return;
11364
11365 // Require that the source be a pointer type.
11366 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
11367 if (!SrcPtr) return;
11368 QualType SrcPointee = SrcPtr->getPointeeType();
11369
11370 // Whitelist casts from cv void*. We already implicitly
11371 // whitelisted casts to cv void*, since they have alignment 1.
11372 // Also whitelist casts involving incomplete types, which implicitly
11373 // includes 'void'.
11374 if (SrcPointee->isIncompleteType()) return;
11375
11376 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000011377
11378 if (auto *CE = dyn_cast<CastExpr>(Op)) {
11379 if (CE->getCastKind() == CK_ArrayToPointerDecay)
11380 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
11381 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
11382 if (UO->getOpcode() == UO_AddrOf)
11383 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
11384 }
11385
John McCall2b5c1b22010-08-12 21:44:57 +000011386 if (SrcAlign >= DestAlign) return;
11387
11388 Diag(TRange.getBegin(), diag::warn_cast_align)
11389 << Op->getType() << T
11390 << static_cast<unsigned>(SrcAlign.getQuantity())
11391 << static_cast<unsigned>(DestAlign.getQuantity())
11392 << TRange << Op->getSourceRange();
11393}
11394
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011395/// Check whether this array fits the idiom of a size-one tail padded
Chandler Carruth28389f02011-08-05 09:10:50 +000011396/// array member of a struct.
11397///
11398/// We avoid emitting out-of-bounds access warnings for such arrays as they are
11399/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000011400static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000011401 const NamedDecl *ND) {
11402 if (Size != 1 || !ND) return false;
11403
11404 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
11405 if (!FD) return false;
11406
11407 // Don't consider sizes resulting from macro expansions or template argument
11408 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000011409
11410 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011411 while (TInfo) {
11412 TypeLoc TL = TInfo->getTypeLoc();
11413 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000011414 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
11415 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011416 TInfo = TDL->getTypeSourceInfo();
11417 continue;
11418 }
David Blaikie6adc78e2013-02-18 22:06:02 +000011419 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
11420 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000011421 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
11422 return false;
11423 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011424 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000011425 }
Chandler Carruth28389f02011-08-05 09:10:50 +000011426
11427 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000011428 if (!RD) return false;
11429 if (RD->isUnion()) return false;
11430 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11431 if (!CRD->isStandardLayout()) return false;
11432 }
Chandler Carruth28389f02011-08-05 09:10:50 +000011433
Benjamin Kramer8c543672011-08-06 03:04:42 +000011434 // See if this is the last field decl in the record.
11435 const Decl *D = FD;
11436 while ((D = D->getNextDeclInContext()))
11437 if (isa<FieldDecl>(D))
11438 return false;
11439 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000011440}
11441
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011442void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011443 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000011444 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011445 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011446 if (IndexExpr->isValueDependent())
11447 return;
11448
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011449 const Type *EffectiveType =
11450 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011451 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011452 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011453 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011454 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000011455 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000011456
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011457 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000011458 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000011459 return;
Richard Smith13f67182011-12-16 19:31:14 +000011460 if (IndexNegated)
11461 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000011462
Craig Topperc3ec1492014-05-26 06:22:03 +000011463 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000011464 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011465 ND = DRE->getDecl();
Chandler Carruth28389f02011-08-05 09:10:50 +000011466 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011467 ND = ME->getMemberDecl();
Chandler Carruth126b1552011-08-05 08:07:29 +000011468
Ted Kremeneke4b316c2011-02-23 23:06:04 +000011469 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011470 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000011471 if (!size.isStrictlyPositive())
11472 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011473
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011474 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000011475 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011476 // Make sure we're comparing apples to apples when comparing index to size
11477 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
11478 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000011479 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000011480 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011481 if (ptrarith_typesize != array_typesize) {
11482 // There's a cast to a different size type involved
11483 uint64_t ratio = array_typesize / ptrarith_typesize;
11484 // TODO: Be smarter about handling cases where array_typesize is not a
11485 // multiple of ptrarith_typesize
11486 if (ptrarith_typesize * ratio == array_typesize)
11487 size *= llvm::APInt(size.getBitWidth(), ratio);
11488 }
11489 }
11490
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011491 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011492 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011493 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011494 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011495
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011496 // For array subscripting the index must be less than size, but for pointer
11497 // arithmetic also allow the index (offset) to be equal to size since
11498 // computing the next address after the end of the array is legal and
11499 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011500 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000011501 return;
11502
11503 // Also don't warn for arrays of size 1 which are members of some
11504 // structure. These are often used to approximate flexible arrays in C89
11505 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011506 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000011507 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011508
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011509 // Suppress the warning if the subscript expression (as identified by the
11510 // ']' location) and the index expression are both from macro expansions
11511 // within a system header.
11512 if (ASE) {
11513 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11514 ASE->getRBracketLoc());
11515 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11516 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11517 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000011518 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011519 return;
11520 }
11521 }
11522
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011523 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011524 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011525 DiagID = diag::warn_array_index_exceeds_bounds;
11526
11527 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11528 PDiag(DiagID) << index.toString(10, true)
11529 << size.toString(10, true)
11530 << (unsigned)size.getLimitedValue(~0U)
11531 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011532 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011533 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011534 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011535 DiagID = diag::warn_ptr_arith_precedes_bounds;
11536 if (index.isNegative()) index = -index;
11537 }
11538
11539 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11540 PDiag(DiagID) << index.toString(10, true)
11541 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000011542 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000011543
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011544 if (!ND) {
11545 // Try harder to find a NamedDecl to point at in the note.
11546 while (const ArraySubscriptExpr *ASE =
11547 dyn_cast<ArraySubscriptExpr>(BaseExpr))
11548 BaseExpr = ASE->getBase()->IgnoreParenCasts();
11549 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011550 ND = DRE->getDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011551 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011552 ND = ME->getMemberDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011553 }
11554
Chandler Carruth1af88f12011-02-17 21:10:52 +000011555 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011556 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11557 PDiag(diag::note_array_index_out_of_bounds)
11558 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000011559}
11560
Ted Kremenekdf26df72011-03-01 18:41:00 +000011561void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011562 int AllowOnePastEnd = 0;
11563 while (expr) {
11564 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000011565 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011566 case Stmt::ArraySubscriptExprClass: {
11567 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011568 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011569 AllowOnePastEnd > 0);
Aaron Ballman93c6ba12018-04-24 19:21:04 +000011570 expr = ASE->getBase();
11571 break;
11572 }
11573 case Stmt::MemberExprClass: {
11574 expr = cast<MemberExpr>(expr)->getBase();
11575 break;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011576 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000011577 case Stmt::OMPArraySectionExprClass: {
11578 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11579 if (ASE->getLowerBound())
11580 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11581 /*ASE=*/nullptr, AllowOnePastEnd > 0);
11582 return;
11583 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011584 case Stmt::UnaryOperatorClass: {
11585 // Only unwrap the * and & unary operators
11586 const UnaryOperator *UO = cast<UnaryOperator>(expr);
11587 expr = UO->getSubExpr();
11588 switch (UO->getOpcode()) {
11589 case UO_AddrOf:
11590 AllowOnePastEnd++;
11591 break;
11592 case UO_Deref:
11593 AllowOnePastEnd--;
11594 break;
11595 default:
11596 return;
11597 }
11598 break;
11599 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011600 case Stmt::ConditionalOperatorClass: {
11601 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11602 if (const Expr *lhs = cond->getLHS())
11603 CheckArrayAccess(lhs);
11604 if (const Expr *rhs = cond->getRHS())
11605 CheckArrayAccess(rhs);
11606 return;
11607 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000011608 case Stmt::CXXOperatorCallExprClass: {
11609 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11610 for (const auto *Arg : OCE->arguments())
11611 CheckArrayAccess(Arg);
11612 return;
11613 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011614 default:
11615 return;
11616 }
Peter Collingbourne91147592011-04-15 00:35:48 +000011617 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011618}
John McCall31168b02011-06-15 23:02:42 +000011619
11620//===--- CHECK: Objective-C retain cycles ----------------------------------//
11621
11622namespace {
John McCall31168b02011-06-15 23:02:42 +000011623
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011624struct RetainCycleOwner {
11625 VarDecl *Variable = nullptr;
11626 SourceRange Range;
11627 SourceLocation Loc;
11628 bool Indirect = false;
11629
11630 RetainCycleOwner() = default;
11631
11632 void setLocsFrom(Expr *e) {
11633 Loc = e->getExprLoc();
11634 Range = e->getSourceRange();
11635 }
11636};
11637
11638} // namespace
John McCall31168b02011-06-15 23:02:42 +000011639
11640/// Consider whether capturing the given variable can possibly lead to
11641/// a retain cycle.
11642static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000011643 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000011644 // lifetime. In MRR, it's captured strongly if the variable is
11645 // __block and has an appropriate type.
11646 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11647 return false;
11648
11649 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011650 if (ref)
11651 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000011652 return true;
11653}
11654
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011655static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000011656 while (true) {
11657 e = e->IgnoreParens();
11658 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11659 switch (cast->getCastKind()) {
11660 case CK_BitCast:
11661 case CK_LValueBitCast:
11662 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000011663 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000011664 e = cast->getSubExpr();
11665 continue;
11666
John McCall31168b02011-06-15 23:02:42 +000011667 default:
11668 return false;
11669 }
11670 }
11671
11672 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11673 ObjCIvarDecl *ivar = ref->getDecl();
11674 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11675 return false;
11676
11677 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011678 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000011679 return false;
11680
11681 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11682 owner.Indirect = true;
11683 return true;
11684 }
11685
11686 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11687 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11688 if (!var) return false;
11689 return considerVariable(var, ref, owner);
11690 }
11691
John McCall31168b02011-06-15 23:02:42 +000011692 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11693 if (member->isArrow()) return false;
11694
11695 // Don't count this as an indirect ownership.
11696 e = member->getBase();
11697 continue;
11698 }
11699
John McCallfe96e0b2011-11-06 09:01:30 +000011700 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11701 // Only pay attention to pseudo-objects on property references.
11702 ObjCPropertyRefExpr *pre
11703 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11704 ->IgnoreParens());
11705 if (!pre) return false;
11706 if (pre->isImplicitProperty()) return false;
11707 ObjCPropertyDecl *property = pre->getExplicitProperty();
11708 if (!property->isRetaining() &&
11709 !(property->getPropertyIvarDecl() &&
11710 property->getPropertyIvarDecl()->getType()
11711 .getObjCLifetime() == Qualifiers::OCL_Strong))
11712 return false;
11713
11714 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011715 if (pre->isSuperReceiver()) {
11716 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11717 if (!owner.Variable)
11718 return false;
11719 owner.Loc = pre->getLocation();
11720 owner.Range = pre->getSourceRange();
11721 return true;
11722 }
John McCallfe96e0b2011-11-06 09:01:30 +000011723 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11724 ->getSourceExpr());
11725 continue;
11726 }
11727
John McCall31168b02011-06-15 23:02:42 +000011728 // Array ivars?
11729
11730 return false;
11731 }
11732}
11733
11734namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011735
John McCall31168b02011-06-15 23:02:42 +000011736 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011737 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000011738 VarDecl *Variable;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011739 Expr *Capturer = nullptr;
11740 bool VarWillBeReased = false;
11741
11742 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11743 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11744 Context(Context), Variable(variable) {}
John McCall31168b02011-06-15 23:02:42 +000011745
11746 void VisitDeclRefExpr(DeclRefExpr *ref) {
11747 if (ref->getDecl() == Variable && !Capturer)
11748 Capturer = ref;
11749 }
11750
John McCall31168b02011-06-15 23:02:42 +000011751 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11752 if (Capturer) return;
11753 Visit(ref->getBase());
11754 if (Capturer && ref->isFreeIvar())
11755 Capturer = ref;
11756 }
11757
11758 void VisitBlockExpr(BlockExpr *block) {
11759 // Look inside nested blocks
11760 if (block->getBlockDecl()->capturesVariable(Variable))
11761 Visit(block->getBlockDecl()->getBody());
11762 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000011763
11764 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11765 if (Capturer) return;
11766 if (OVE->getSourceExpr())
11767 Visit(OVE->getSourceExpr());
11768 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011769
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011770 void VisitBinaryOperator(BinaryOperator *BinOp) {
11771 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11772 return;
11773 Expr *LHS = BinOp->getLHS();
11774 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11775 if (DRE->getDecl() != Variable)
11776 return;
11777 if (Expr *RHS = BinOp->getRHS()) {
11778 RHS = RHS->IgnoreParenCasts();
11779 llvm::APSInt Value;
11780 VarWillBeReased =
11781 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11782 }
11783 }
11784 }
John McCall31168b02011-06-15 23:02:42 +000011785 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011786
11787} // namespace
John McCall31168b02011-06-15 23:02:42 +000011788
11789/// Check whether the given argument is a block which captures a
11790/// variable.
11791static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11792 assert(owner.Variable && owner.Loc.isValid());
11793
11794 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000011795
11796 // Look through [^{...} copy] and Block_copy(^{...}).
11797 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11798 Selector Cmd = ME->getSelector();
11799 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11800 e = ME->getInstanceReceiver();
11801 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000011802 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000011803 e = e->IgnoreParenCasts();
11804 }
11805 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11806 if (CE->getNumArgs() == 1) {
11807 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000011808 if (Fn) {
11809 const IdentifierInfo *FnI = Fn->getIdentifier();
11810 if (FnI && FnI->isStr("_Block_copy")) {
11811 e = CE->getArg(0)->IgnoreParenCasts();
11812 }
11813 }
Jordan Rose67e887c2012-09-17 17:54:30 +000011814 }
11815 }
11816
John McCall31168b02011-06-15 23:02:42 +000011817 BlockExpr *block = dyn_cast<BlockExpr>(e);
11818 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000011819 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011820
11821 FindCaptureVisitor visitor(S.Context, owner.Variable);
11822 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011823 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000011824}
11825
11826static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11827 RetainCycleOwner &owner) {
11828 assert(capturer);
11829 assert(owner.Variable && owner.Loc.isValid());
11830
11831 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11832 << owner.Variable << capturer->getSourceRange();
11833 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11834 << owner.Indirect << owner.Range;
11835}
11836
11837/// Check for a keyword selector that starts with the word 'add' or
11838/// 'set'.
11839static bool isSetterLikeSelector(Selector sel) {
11840 if (sel.isUnarySelector()) return false;
11841
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011842 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000011843 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011844 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000011845 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011846 else if (str.startswith("add")) {
11847 // Specially whitelist 'addOperationWithBlock:'.
11848 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11849 return false;
11850 str = str.substr(3);
11851 }
John McCall31168b02011-06-15 23:02:42 +000011852 else
11853 return false;
11854
11855 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000011856 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000011857}
11858
Benjamin Kramer3a743452015-03-09 15:03:32 +000011859static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11860 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011861 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11862 Message->getReceiverInterface(),
11863 NSAPI::ClassId_NSMutableArray);
11864 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011865 return None;
11866 }
11867
11868 Selector Sel = Message->getSelector();
11869
11870 Optional<NSAPI::NSArrayMethodKind> MKOpt =
11871 S.NSAPIObj->getNSArrayMethodKind(Sel);
11872 if (!MKOpt) {
11873 return None;
11874 }
11875
11876 NSAPI::NSArrayMethodKind MK = *MKOpt;
11877
11878 switch (MK) {
11879 case NSAPI::NSMutableArr_addObject:
11880 case NSAPI::NSMutableArr_insertObjectAtIndex:
11881 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11882 return 0;
11883 case NSAPI::NSMutableArr_replaceObjectAtIndex:
11884 return 1;
11885
11886 default:
11887 return None;
11888 }
11889
11890 return None;
11891}
11892
11893static
11894Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11895 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011896 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11897 Message->getReceiverInterface(),
11898 NSAPI::ClassId_NSMutableDictionary);
11899 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011900 return None;
11901 }
11902
11903 Selector Sel = Message->getSelector();
11904
11905 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11906 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11907 if (!MKOpt) {
11908 return None;
11909 }
11910
11911 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11912
11913 switch (MK) {
11914 case NSAPI::NSMutableDict_setObjectForKey:
11915 case NSAPI::NSMutableDict_setValueForKey:
11916 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11917 return 0;
11918
11919 default:
11920 return None;
11921 }
11922
11923 return None;
11924}
11925
11926static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011927 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11928 Message->getReceiverInterface(),
11929 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000011930
Alex Denisov5dfac812015-08-06 04:51:14 +000011931 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11932 Message->getReceiverInterface(),
11933 NSAPI::ClassId_NSMutableOrderedSet);
11934 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011935 return None;
11936 }
11937
11938 Selector Sel = Message->getSelector();
11939
11940 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11941 if (!MKOpt) {
11942 return None;
11943 }
11944
11945 NSAPI::NSSetMethodKind MK = *MKOpt;
11946
11947 switch (MK) {
11948 case NSAPI::NSMutableSet_addObject:
11949 case NSAPI::NSOrderedSet_setObjectAtIndex:
11950 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11951 case NSAPI::NSOrderedSet_insertObjectAtIndex:
11952 return 0;
11953 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11954 return 1;
11955 }
11956
11957 return None;
11958}
11959
11960void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11961 if (!Message->isInstanceMessage()) {
11962 return;
11963 }
11964
11965 Optional<int> ArgOpt;
11966
11967 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11968 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11969 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11970 return;
11971 }
11972
11973 int ArgIndex = *ArgOpt;
11974
Alex Denisove1d882c2015-03-04 17:55:52 +000011975 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11976 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11977 Arg = OE->getSourceExpr()->IgnoreImpCasts();
11978 }
11979
Alex Denisov5dfac812015-08-06 04:51:14 +000011980 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011981 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011982 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011983 Diag(Message->getSourceRange().getBegin(),
11984 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000011985 << ArgRE->getDecl() << StringRef("'super'");
Alex Denisove1d882c2015-03-04 17:55:52 +000011986 }
11987 }
Alex Denisov5dfac812015-08-06 04:51:14 +000011988 } else {
11989 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11990
11991 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11992 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11993 }
11994
11995 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11996 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11997 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11998 ValueDecl *Decl = ReceiverRE->getDecl();
11999 Diag(Message->getSourceRange().getBegin(),
12000 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012001 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012002 if (!ArgRE->isObjCSelfExpr()) {
12003 Diag(Decl->getLocation(),
12004 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000012005 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012006 }
12007 }
12008 }
12009 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
12010 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
12011 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
12012 ObjCIvarDecl *Decl = IvarRE->getDecl();
12013 Diag(Message->getSourceRange().getBegin(),
12014 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012015 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012016 Diag(Decl->getLocation(),
12017 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000012018 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012019 }
Alex Denisove1d882c2015-03-04 17:55:52 +000012020 }
12021 }
12022 }
Alex Denisove1d882c2015-03-04 17:55:52 +000012023}
12024
John McCall31168b02011-06-15 23:02:42 +000012025/// Check a message send to see if it's likely to cause a retain cycle.
12026void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
12027 // Only check instance methods whose selector looks like a setter.
12028 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
12029 return;
12030
12031 // Try to find a variable that the receiver is strongly owned by.
12032 RetainCycleOwner owner;
12033 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012034 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000012035 return;
12036 } else {
12037 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
12038 owner.Variable = getCurMethodDecl()->getSelfDecl();
12039 owner.Loc = msg->getSuperLoc();
12040 owner.Range = msg->getSuperLoc();
12041 }
12042
12043 // Check whether the receiver is captured by any of the arguments.
Alex Lorenz42a97a92017-11-17 20:44:25 +000012044 const ObjCMethodDecl *MD = msg->getMethodDecl();
12045 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
12046 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
12047 // noescape blocks should not be retained by the method.
12048 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
12049 continue;
John McCall31168b02011-06-15 23:02:42 +000012050 return diagnoseRetainCycle(*this, capturer, owner);
Alex Lorenz42a97a92017-11-17 20:44:25 +000012051 }
12052 }
John McCall31168b02011-06-15 23:02:42 +000012053}
12054
12055/// Check a property assign to see if it's likely to cause a retain cycle.
12056void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
12057 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012058 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000012059 return;
12060
12061 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
12062 diagnoseRetainCycle(*this, capturer, owner);
12063}
12064
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012065void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
12066 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000012067 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012068 return;
12069
12070 // Because we don't have an expression for the variable, we have to set the
12071 // location explicitly here.
12072 Owner.Loc = Var->getLocation();
12073 Owner.Range = Var->getSourceRange();
12074
12075 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
12076 diagnoseRetainCycle(*this, Capturer, Owner);
12077}
12078
Ted Kremenek9304da92012-12-21 08:04:28 +000012079static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
12080 Expr *RHS, bool isProperty) {
12081 // Check if RHS is an Objective-C object literal, which also can get
12082 // immediately zapped in a weak reference. Note that we explicitly
12083 // allow ObjCStringLiterals, since those are designed to never really die.
12084 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012085
Ted Kremenek64873352012-12-21 22:46:35 +000012086 // This enum needs to match with the 'select' in
12087 // warn_objc_arc_literal_assign (off-by-1).
12088 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
12089 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
12090 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012091
12092 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000012093 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000012094 << (isProperty ? 0 : 1)
12095 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012096
12097 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000012098}
12099
Ted Kremenekc1f014a2012-12-21 19:45:30 +000012100static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
12101 Qualifiers::ObjCLifetime LT,
12102 Expr *RHS, bool isProperty) {
12103 // Strip off any implicit cast added to get to the one ARC-specific.
12104 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
12105 if (cast->getCastKind() == CK_ARCConsumeObject) {
12106 S.Diag(Loc, diag::warn_arc_retained_assign)
12107 << (LT == Qualifiers::OCL_ExplicitNone)
12108 << (isProperty ? 0 : 1)
12109 << RHS->getSourceRange();
12110 return true;
12111 }
12112 RHS = cast->getSubExpr();
12113 }
12114
12115 if (LT == Qualifiers::OCL_Weak &&
12116 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
12117 return true;
12118
12119 return false;
12120}
12121
Ted Kremenekb36234d2012-12-21 08:04:20 +000012122bool Sema::checkUnsafeAssigns(SourceLocation Loc,
12123 QualType LHS, Expr *RHS) {
12124 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
12125
12126 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
12127 return false;
12128
12129 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
12130 return true;
12131
12132 return false;
12133}
12134
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012135void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
12136 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012137 QualType LHSType;
12138 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000012139 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012140 ObjCPropertyRefExpr *PRE
12141 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
12142 if (PRE && !PRE->isImplicitProperty()) {
12143 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12144 if (PD)
12145 LHSType = PD->getType();
12146 }
12147
12148 if (LHSType.isNull())
12149 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000012150
12151 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
12152
12153 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012154 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000012155 getCurFunction()->markSafeWeakUse(LHS);
12156 }
12157
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012158 if (checkUnsafeAssigns(Loc, LHSType, RHS))
12159 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000012160
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012161 // FIXME. Check for other life times.
12162 if (LT != Qualifiers::OCL_None)
12163 return;
12164
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012165 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012166 if (PRE->isImplicitProperty())
12167 return;
12168 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12169 if (!PD)
12170 return;
12171
Bill Wendling44426052012-12-20 19:22:21 +000012172 unsigned Attributes = PD->getPropertyAttributes();
12173 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012174 // when 'assign' attribute was not explicitly specified
12175 // by user, ignore it and rely on property type itself
12176 // for lifetime info.
12177 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
12178 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
12179 LHSType->isObjCRetainableType())
12180 return;
12181
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012182 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000012183 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012184 Diag(Loc, diag::warn_arc_retained_property_assign)
12185 << RHS->getSourceRange();
12186 return;
12187 }
12188 RHS = cast->getSubExpr();
12189 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012190 }
Bill Wendling44426052012-12-20 19:22:21 +000012191 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000012192 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
12193 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000012194 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012195 }
12196}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012197
12198//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
12199
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012200static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
12201 SourceLocation StmtLoc,
12202 const NullStmt *Body) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012203 // Do not warn if the body is a macro that expands to nothing, e.g:
12204 //
12205 // #define CALL(x)
12206 // if (condition)
12207 // CALL(0);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012208 if (Body->hasLeadingEmptyMacro())
12209 return false;
12210
12211 // Get line numbers of statement and body.
12212 bool StmtLineInvalid;
Hans Wennborg95419752017-11-20 17:38:16 +000012213 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012214 &StmtLineInvalid);
12215 if (StmtLineInvalid)
12216 return false;
12217
12218 bool BodyLineInvalid;
12219 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
12220 &BodyLineInvalid);
12221 if (BodyLineInvalid)
12222 return false;
12223
12224 // Warn if null statement and body are on the same line.
12225 if (StmtLine != BodyLine)
12226 return false;
12227
12228 return true;
12229}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012230
12231void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
12232 const Stmt *Body,
12233 unsigned DiagID) {
12234 // Since this is a syntactic check, don't emit diagnostic for template
12235 // instantiations, this just adds noise.
12236 if (CurrentInstantiationScope)
12237 return;
12238
12239 // The body should be a null statement.
12240 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
12241 if (!NBody)
12242 return;
12243
12244 // Do the usual checks.
12245 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12246 return;
12247
12248 Diag(NBody->getSemiLoc(), DiagID);
12249 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12250}
12251
12252void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
12253 const Stmt *PossibleBody) {
12254 assert(!CurrentInstantiationScope); // Ensured by caller
12255
12256 SourceLocation StmtLoc;
12257 const Stmt *Body;
12258 unsigned DiagID;
12259 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
12260 StmtLoc = FS->getRParenLoc();
12261 Body = FS->getBody();
12262 DiagID = diag::warn_empty_for_body;
12263 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
12264 StmtLoc = WS->getCond()->getSourceRange().getEnd();
12265 Body = WS->getBody();
12266 DiagID = diag::warn_empty_while_body;
12267 } else
12268 return; // Neither `for' nor `while'.
12269
12270 // The body should be a null statement.
12271 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
12272 if (!NBody)
12273 return;
12274
12275 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012276 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012277 return;
12278
12279 // Do the usual checks.
12280 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12281 return;
12282
12283 // `for(...);' and `while(...);' are popular idioms, so in order to keep
12284 // noise level low, emit diagnostics only if for/while is followed by a
12285 // CompoundStmt, e.g.:
12286 // for (int i = 0; i < n; i++);
12287 // {
12288 // a(i);
12289 // }
12290 // or if for/while is followed by a statement with more indentation
12291 // than for/while itself:
12292 // for (int i = 0; i < n; i++);
12293 // a(i);
12294 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
12295 if (!ProbableTypo) {
12296 bool BodyColInvalid;
12297 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
12298 PossibleBody->getLocStart(),
12299 &BodyColInvalid);
12300 if (BodyColInvalid)
12301 return;
12302
12303 bool StmtColInvalid;
12304 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
12305 S->getLocStart(),
12306 &StmtColInvalid);
12307 if (StmtColInvalid)
12308 return;
12309
12310 if (BodyCol > StmtCol)
12311 ProbableTypo = true;
12312 }
12313
12314 if (ProbableTypo) {
12315 Diag(NBody->getSemiLoc(), DiagID);
12316 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12317 }
12318}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012319
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012320//===--- CHECK: Warn on self move with std::move. -------------------------===//
12321
12322/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
12323void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
12324 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012325 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
12326 return;
12327
Richard Smith51ec0cf2017-02-21 01:17:38 +000012328 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012329 return;
12330
12331 // Strip parens and casts away.
12332 LHSExpr = LHSExpr->IgnoreParenImpCasts();
12333 RHSExpr = RHSExpr->IgnoreParenImpCasts();
12334
12335 // Check for a call expression
12336 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
12337 if (!CE || CE->getNumArgs() != 1)
12338 return;
12339
12340 // Check for a call to std::move
Nico Weberb688d132017-09-28 16:16:39 +000012341 if (!CE->isCallToStdMove())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012342 return;
12343
12344 // Get argument from std::move
12345 RHSExpr = CE->getArg(0);
12346
12347 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12348 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12349
12350 // Two DeclRefExpr's, check that the decls are the same.
12351 if (LHSDeclRef && RHSDeclRef) {
12352 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12353 return;
12354 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12355 RHSDeclRef->getDecl()->getCanonicalDecl())
12356 return;
12357
12358 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12359 << LHSExpr->getSourceRange()
12360 << RHSExpr->getSourceRange();
12361 return;
12362 }
12363
12364 // Member variables require a different approach to check for self moves.
12365 // MemberExpr's are the same if every nested MemberExpr refers to the same
12366 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
12367 // the base Expr's are CXXThisExpr's.
12368 const Expr *LHSBase = LHSExpr;
12369 const Expr *RHSBase = RHSExpr;
12370 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
12371 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
12372 if (!LHSME || !RHSME)
12373 return;
12374
12375 while (LHSME && RHSME) {
12376 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
12377 RHSME->getMemberDecl()->getCanonicalDecl())
12378 return;
12379
12380 LHSBase = LHSME->getBase();
12381 RHSBase = RHSME->getBase();
12382 LHSME = dyn_cast<MemberExpr>(LHSBase);
12383 RHSME = dyn_cast<MemberExpr>(RHSBase);
12384 }
12385
12386 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
12387 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
12388 if (LHSDeclRef && RHSDeclRef) {
12389 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12390 return;
12391 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12392 RHSDeclRef->getDecl()->getCanonicalDecl())
12393 return;
12394
12395 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12396 << LHSExpr->getSourceRange()
12397 << RHSExpr->getSourceRange();
12398 return;
12399 }
12400
12401 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
12402 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12403 << LHSExpr->getSourceRange()
12404 << RHSExpr->getSourceRange();
12405}
12406
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012407//===--- Layout compatibility ----------------------------------------------//
12408
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012409static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012410
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012411/// Check if two enumeration types are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012412static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012413 // C++11 [dcl.enum] p8:
12414 // Two enumeration types are layout-compatible if they have the same
12415 // underlying type.
12416 return ED1->isComplete() && ED2->isComplete() &&
12417 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
12418}
12419
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012420/// Check if two fields are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012421static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
12422 FieldDecl *Field2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012423 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
12424 return false;
12425
12426 if (Field1->isBitField() != Field2->isBitField())
12427 return false;
12428
12429 if (Field1->isBitField()) {
12430 // Make sure that the bit-fields are the same length.
12431 unsigned Bits1 = Field1->getBitWidthValue(C);
12432 unsigned Bits2 = Field2->getBitWidthValue(C);
12433
12434 if (Bits1 != Bits2)
12435 return false;
12436 }
12437
12438 return true;
12439}
12440
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012441/// Check if two standard-layout structs are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012442/// (C++11 [class.mem] p17)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012443static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
12444 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012445 // If both records are C++ classes, check that base classes match.
12446 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
12447 // If one of records is a CXXRecordDecl we are in C++ mode,
12448 // thus the other one is a CXXRecordDecl, too.
12449 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
12450 // Check number of base classes.
12451 if (D1CXX->getNumBases() != D2CXX->getNumBases())
12452 return false;
12453
12454 // Check the base classes.
12455 for (CXXRecordDecl::base_class_const_iterator
12456 Base1 = D1CXX->bases_begin(),
12457 BaseEnd1 = D1CXX->bases_end(),
12458 Base2 = D2CXX->bases_begin();
12459 Base1 != BaseEnd1;
12460 ++Base1, ++Base2) {
12461 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
12462 return false;
12463 }
12464 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
12465 // If only RD2 is a C++ class, it should have zero base classes.
12466 if (D2CXX->getNumBases() > 0)
12467 return false;
12468 }
12469
12470 // Check the fields.
12471 RecordDecl::field_iterator Field2 = RD2->field_begin(),
12472 Field2End = RD2->field_end(),
12473 Field1 = RD1->field_begin(),
12474 Field1End = RD1->field_end();
12475 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
12476 if (!isLayoutCompatible(C, *Field1, *Field2))
12477 return false;
12478 }
12479 if (Field1 != Field1End || Field2 != Field2End)
12480 return false;
12481
12482 return true;
12483}
12484
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012485/// Check if two standard-layout unions are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012486/// (C++11 [class.mem] p18)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012487static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
12488 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012489 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012490 for (auto *Field2 : RD2->fields())
12491 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012492
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012493 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012494 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12495 I = UnmatchedFields.begin(),
12496 E = UnmatchedFields.end();
12497
12498 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012499 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012500 bool Result = UnmatchedFields.erase(*I);
12501 (void) Result;
12502 assert(Result);
12503 break;
12504 }
12505 }
12506 if (I == E)
12507 return false;
12508 }
12509
12510 return UnmatchedFields.empty();
12511}
12512
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012513static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
12514 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012515 if (RD1->isUnion() != RD2->isUnion())
12516 return false;
12517
12518 if (RD1->isUnion())
12519 return isLayoutCompatibleUnion(C, RD1, RD2);
12520 else
12521 return isLayoutCompatibleStruct(C, RD1, RD2);
12522}
12523
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012524/// Check if two types are layout-compatible in C++11 sense.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012525static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012526 if (T1.isNull() || T2.isNull())
12527 return false;
12528
12529 // C++11 [basic.types] p11:
12530 // If two types T1 and T2 are the same type, then T1 and T2 are
12531 // layout-compatible types.
12532 if (C.hasSameType(T1, T2))
12533 return true;
12534
12535 T1 = T1.getCanonicalType().getUnqualifiedType();
12536 T2 = T2.getCanonicalType().getUnqualifiedType();
12537
12538 const Type::TypeClass TC1 = T1->getTypeClass();
12539 const Type::TypeClass TC2 = T2->getTypeClass();
12540
12541 if (TC1 != TC2)
12542 return false;
12543
12544 if (TC1 == Type::Enum) {
12545 return isLayoutCompatible(C,
12546 cast<EnumType>(T1)->getDecl(),
12547 cast<EnumType>(T2)->getDecl());
12548 } else if (TC1 == Type::Record) {
12549 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12550 return false;
12551
12552 return isLayoutCompatible(C,
12553 cast<RecordType>(T1)->getDecl(),
12554 cast<RecordType>(T2)->getDecl());
12555 }
12556
12557 return false;
12558}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012559
12560//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12561
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012562/// Given a type tag expression find the type tag itself.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012563///
12564/// \param TypeExpr Type tag expression, as it appears in user's code.
12565///
12566/// \param VD Declaration of an identifier that appears in a type tag.
12567///
12568/// \param MagicValue Type tag magic value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012569static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12570 const ValueDecl **VD, uint64_t *MagicValue) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012571 while(true) {
12572 if (!TypeExpr)
12573 return false;
12574
12575 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12576
12577 switch (TypeExpr->getStmtClass()) {
12578 case Stmt::UnaryOperatorClass: {
12579 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12580 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12581 TypeExpr = UO->getSubExpr();
12582 continue;
12583 }
12584 return false;
12585 }
12586
12587 case Stmt::DeclRefExprClass: {
12588 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12589 *VD = DRE->getDecl();
12590 return true;
12591 }
12592
12593 case Stmt::IntegerLiteralClass: {
12594 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12595 llvm::APInt MagicValueAPInt = IL->getValue();
12596 if (MagicValueAPInt.getActiveBits() <= 64) {
12597 *MagicValue = MagicValueAPInt.getZExtValue();
12598 return true;
12599 } else
12600 return false;
12601 }
12602
12603 case Stmt::BinaryConditionalOperatorClass:
12604 case Stmt::ConditionalOperatorClass: {
12605 const AbstractConditionalOperator *ACO =
12606 cast<AbstractConditionalOperator>(TypeExpr);
12607 bool Result;
12608 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12609 if (Result)
12610 TypeExpr = ACO->getTrueExpr();
12611 else
12612 TypeExpr = ACO->getFalseExpr();
12613 continue;
12614 }
12615 return false;
12616 }
12617
12618 case Stmt::BinaryOperatorClass: {
12619 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12620 if (BO->getOpcode() == BO_Comma) {
12621 TypeExpr = BO->getRHS();
12622 continue;
12623 }
12624 return false;
12625 }
12626
12627 default:
12628 return false;
12629 }
12630 }
12631}
12632
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012633/// Retrieve the C type corresponding to type tag TypeExpr.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012634///
12635/// \param TypeExpr Expression that specifies a type tag.
12636///
12637/// \param MagicValues Registered magic values.
12638///
12639/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12640/// kind.
12641///
12642/// \param TypeInfo Information about the corresponding C type.
12643///
12644/// \returns true if the corresponding C type was found.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012645static bool GetMatchingCType(
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012646 const IdentifierInfo *ArgumentKind,
12647 const Expr *TypeExpr, const ASTContext &Ctx,
12648 const llvm::DenseMap<Sema::TypeTagMagicValue,
12649 Sema::TypeTagData> *MagicValues,
12650 bool &FoundWrongKind,
12651 Sema::TypeTagData &TypeInfo) {
12652 FoundWrongKind = false;
12653
12654 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000012655 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012656
12657 uint64_t MagicValue;
12658
12659 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12660 return false;
12661
12662 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000012663 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012664 if (I->getArgumentKind() != ArgumentKind) {
12665 FoundWrongKind = true;
12666 return false;
12667 }
12668 TypeInfo.Type = I->getMatchingCType();
12669 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12670 TypeInfo.MustBeNull = I->getMustBeNull();
12671 return true;
12672 }
12673 return false;
12674 }
12675
12676 if (!MagicValues)
12677 return false;
12678
12679 llvm::DenseMap<Sema::TypeTagMagicValue,
12680 Sema::TypeTagData>::const_iterator I =
12681 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12682 if (I == MagicValues->end())
12683 return false;
12684
12685 TypeInfo = I->second;
12686 return true;
12687}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012688
12689void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12690 uint64_t MagicValue, QualType Type,
12691 bool LayoutCompatible,
12692 bool MustBeNull) {
12693 if (!TypeTagForDatatypeMagicValues)
12694 TypeTagForDatatypeMagicValues.reset(
12695 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12696
12697 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12698 (*TypeTagForDatatypeMagicValues)[Magic] =
12699 TypeTagData(Type, LayoutCompatible, MustBeNull);
12700}
12701
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012702static bool IsSameCharType(QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012703 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12704 if (!BT1)
12705 return false;
12706
12707 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12708 if (!BT2)
12709 return false;
12710
12711 BuiltinType::Kind T1Kind = BT1->getKind();
12712 BuiltinType::Kind T2Kind = BT2->getKind();
12713
12714 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
12715 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
12716 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12717 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12718}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012719
12720void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012721 const ArrayRef<const Expr *> ExprArgs,
12722 SourceLocation CallSiteLoc) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012723 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12724 bool IsPointerAttr = Attr->getIsPointer();
12725
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012726 // Retrieve the argument representing the 'type_tag'.
Joel E. Denny81508102018-03-13 14:51:22 +000012727 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
12728 if (TypeTagIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012729 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000012730 << 0 << Attr->getTypeTagIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012731 return;
12732 }
Joel E. Denny81508102018-03-13 14:51:22 +000012733 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012734 bool FoundWrongKind;
12735 TypeTagData TypeInfo;
12736 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12737 TypeTagForDatatypeMagicValues.get(),
12738 FoundWrongKind, TypeInfo)) {
12739 if (FoundWrongKind)
12740 Diag(TypeTagExpr->getExprLoc(),
12741 diag::warn_type_tag_for_datatype_wrong_kind)
12742 << TypeTagExpr->getSourceRange();
12743 return;
12744 }
12745
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012746 // Retrieve the argument representing the 'arg_idx'.
Joel E. Denny81508102018-03-13 14:51:22 +000012747 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
12748 if (ArgumentIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012749 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000012750 << 1 << Attr->getArgumentIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012751 return;
12752 }
Joel E. Denny81508102018-03-13 14:51:22 +000012753 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012754 if (IsPointerAttr) {
12755 // Skip implicit cast of pointer to `void *' (as a function argument).
12756 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000012757 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000012758 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012759 ArgumentExpr = ICE->getSubExpr();
12760 }
12761 QualType ArgumentType = ArgumentExpr->getType();
12762
12763 // Passing a `void*' pointer shouldn't trigger a warning.
12764 if (IsPointerAttr && ArgumentType->isVoidPointerType())
12765 return;
12766
12767 if (TypeInfo.MustBeNull) {
12768 // Type tag with matching void type requires a null pointer.
12769 if (!ArgumentExpr->isNullPointerConstant(Context,
12770 Expr::NPC_ValueDependentIsNotNull)) {
12771 Diag(ArgumentExpr->getExprLoc(),
12772 diag::warn_type_safety_null_pointer_required)
12773 << ArgumentKind->getName()
12774 << ArgumentExpr->getSourceRange()
12775 << TypeTagExpr->getSourceRange();
12776 }
12777 return;
12778 }
12779
12780 QualType RequiredType = TypeInfo.Type;
12781 if (IsPointerAttr)
12782 RequiredType = Context.getPointerType(RequiredType);
12783
12784 bool mismatch = false;
12785 if (!TypeInfo.LayoutCompatible) {
12786 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12787
12788 // C++11 [basic.fundamental] p1:
12789 // Plain char, signed char, and unsigned char are three distinct types.
12790 //
12791 // But we treat plain `char' as equivalent to `signed char' or `unsigned
12792 // char' depending on the current char signedness mode.
12793 if (mismatch)
12794 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12795 RequiredType->getPointeeType())) ||
12796 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12797 mismatch = false;
12798 } else
12799 if (IsPointerAttr)
12800 mismatch = !isLayoutCompatible(Context,
12801 ArgumentType->getPointeeType(),
12802 RequiredType->getPointeeType());
12803 else
12804 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12805
12806 if (mismatch)
12807 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000012808 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012809 << TypeInfo.LayoutCompatible << RequiredType
12810 << ArgumentExpr->getSourceRange()
12811 << TypeTagExpr->getSourceRange();
12812}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012813
12814void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12815 CharUnits Alignment) {
12816 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12817}
12818
12819void Sema::DiagnoseMisalignedMembers() {
12820 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000012821 const NamedDecl *ND = m.RD;
12822 if (ND->getName().empty()) {
12823 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12824 ND = TD;
12825 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012826 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000012827 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012828 }
12829 MisalignedMembers.clear();
12830}
12831
12832void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012833 E = E->IgnoreParens();
12834 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012835 return;
12836 if (isa<UnaryOperator>(E) &&
12837 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12838 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12839 if (isa<MemberExpr>(Op)) {
12840 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12841 MisalignedMember(Op));
12842 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012843 (T->isIntegerType() ||
Roger Ferrer Ibanezd80d6c52017-12-07 09:23:50 +000012844 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
12845 Context.getTypeAlignInChars(
12846 T->getPointeeType()) <= MA->Alignment))))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012847 MisalignedMembers.erase(MA);
12848 }
12849 }
12850}
12851
12852void Sema::RefersToMemberWithReducedAlignment(
12853 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000012854 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12855 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012856 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012857 if (!ME)
12858 return;
12859
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000012860 // No need to check expressions with an __unaligned-qualified type.
12861 if (E->getType().getQualifiers().hasUnaligned())
12862 return;
12863
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012864 // For a chain of MemberExpr like "a.b.c.d" this list
12865 // will keep FieldDecl's like [d, c, b].
12866 SmallVector<FieldDecl *, 4> ReverseMemberChain;
12867 const MemberExpr *TopME = nullptr;
12868 bool AnyIsPacked = false;
12869 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012870 QualType BaseType = ME->getBase()->getType();
12871 if (ME->isArrow())
12872 BaseType = BaseType->getPointeeType();
12873 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000012874 if (RD->isInvalidDecl())
12875 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012876
12877 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012878 auto *FD = dyn_cast<FieldDecl>(MD);
12879 // We do not care about non-data members.
12880 if (!FD || FD->isInvalidDecl())
12881 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012882
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012883 AnyIsPacked =
12884 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12885 ReverseMemberChain.push_back(FD);
12886
12887 TopME = ME;
12888 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12889 } while (ME);
12890 assert(TopME && "We did not compute a topmost MemberExpr!");
12891
12892 // Not the scope of this diagnostic.
12893 if (!AnyIsPacked)
12894 return;
12895
12896 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12897 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12898 // TODO: The innermost base of the member expression may be too complicated.
12899 // For now, just disregard these cases. This is left for future
12900 // improvement.
12901 if (!DRE && !isa<CXXThisExpr>(TopBase))
12902 return;
12903
12904 // Alignment expected by the whole expression.
12905 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12906
12907 // No need to do anything else with this case.
12908 if (ExpectedAlignment.isOne())
12909 return;
12910
12911 // Synthesize offset of the whole access.
12912 CharUnits Offset;
12913 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12914 I++) {
12915 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12916 }
12917
12918 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12919 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12920 ReverseMemberChain.back()->getParent()->getTypeForDecl());
12921
12922 // The base expression of the innermost MemberExpr may give
12923 // stronger guarantees than the class containing the member.
12924 if (DRE && !TopME->isArrow()) {
12925 const ValueDecl *VD = DRE->getDecl();
12926 if (!VD->getType()->isReferenceType())
12927 CompleteObjectAlignment =
12928 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12929 }
12930
12931 // Check if the synthesized offset fulfills the alignment.
12932 if (Offset % ExpectedAlignment != 0 ||
12933 // It may fulfill the offset it but the effective alignment may still be
12934 // lower than the expected expression alignment.
12935 CompleteObjectAlignment < ExpectedAlignment) {
12936 // If this happens, we want to determine a sensible culprit of this.
12937 // Intuitively, watching the chain of member expressions from right to
12938 // left, we start with the required alignment (as required by the field
12939 // type) but some packed attribute in that chain has reduced the alignment.
12940 // It may happen that another packed structure increases it again. But if
12941 // we are here such increase has not been enough. So pointing the first
12942 // FieldDecl that either is packed or else its RecordDecl is,
12943 // seems reasonable.
12944 FieldDecl *FD = nullptr;
12945 CharUnits Alignment;
12946 for (FieldDecl *FDI : ReverseMemberChain) {
12947 if (FDI->hasAttr<PackedAttr>() ||
12948 FDI->getParent()->hasAttr<PackedAttr>()) {
12949 FD = FDI;
12950 Alignment = std::min(
12951 Context.getTypeAlignInChars(FD->getType()),
12952 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12953 break;
12954 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012955 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012956 assert(FD && "We did not find a packed FieldDecl!");
12957 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012958 }
12959}
12960
12961void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12962 using namespace std::placeholders;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012963
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012964 RefersToMemberWithReducedAlignment(
12965 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12966 _2, _3, _4));
12967}