blob: 419ac47b9b802a9eb70201585b7217a12ce1fe53 [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:
Craig Topper7609f1c2016-10-01 21:03:50 +00002343 ArgNum = 3;
2344 HasRC = true;
2345 break;
2346 case X86::BI__builtin_ia32_addpd512_mask:
2347 case X86::BI__builtin_ia32_addps512_mask:
2348 case X86::BI__builtin_ia32_divpd512_mask:
2349 case X86::BI__builtin_ia32_divps512_mask:
2350 case X86::BI__builtin_ia32_mulpd512_mask:
2351 case X86::BI__builtin_ia32_mulps512_mask:
2352 case X86::BI__builtin_ia32_subpd512_mask:
2353 case X86::BI__builtin_ia32_subps512_mask:
2354 case X86::BI__builtin_ia32_addss_round_mask:
2355 case X86::BI__builtin_ia32_addsd_round_mask:
2356 case X86::BI__builtin_ia32_divss_round_mask:
2357 case X86::BI__builtin_ia32_divsd_round_mask:
2358 case X86::BI__builtin_ia32_mulss_round_mask:
2359 case X86::BI__builtin_ia32_mulsd_round_mask:
2360 case X86::BI__builtin_ia32_subss_round_mask:
2361 case X86::BI__builtin_ia32_subsd_round_mask:
2362 case X86::BI__builtin_ia32_scalefpd512_mask:
2363 case X86::BI__builtin_ia32_scalefps512_mask:
2364 case X86::BI__builtin_ia32_scalefsd_round_mask:
2365 case X86::BI__builtin_ia32_scalefss_round_mask:
2366 case X86::BI__builtin_ia32_getmantpd512_mask:
2367 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002368 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2369 case X86::BI__builtin_ia32_sqrtsd_round_mask:
2370 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002371 case X86::BI__builtin_ia32_vfmaddsd3_mask:
2372 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2373 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2374 case X86::BI__builtin_ia32_vfmaddss3_mask:
2375 case X86::BI__builtin_ia32_vfmaddss3_maskz:
2376 case X86::BI__builtin_ia32_vfmaddss3_mask3:
Craig Topperb92c77d2018-06-07 02:46:02 +00002377 case X86::BI__builtin_ia32_vfmaddpd512_mask:
2378 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2379 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2380 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2381 case X86::BI__builtin_ia32_vfmaddps512_mask:
2382 case X86::BI__builtin_ia32_vfmaddps512_maskz:
2383 case X86::BI__builtin_ia32_vfmaddps512_mask3:
2384 case X86::BI__builtin_ia32_vfmsubps512_mask3:
2385 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2386 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2387 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2388 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2389 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2390 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2391 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2392 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
Craig Topper7609f1c2016-10-01 21:03:50 +00002393 ArgNum = 4;
2394 HasRC = true;
2395 break;
2396 case X86::BI__builtin_ia32_getmantsd_round_mask:
2397 case X86::BI__builtin_ia32_getmantss_round_mask:
2398 ArgNum = 5;
2399 HasRC = true;
2400 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00002401 }
2402
2403 llvm::APSInt Result;
2404
2405 // We can't check the value of a dependent argument.
2406 Expr *Arg = TheCall->getArg(ArgNum);
2407 if (Arg->isTypeDependent() || Arg->isValueDependent())
2408 return false;
2409
2410 // Check constant-ness first.
2411 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2412 return true;
2413
2414 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2415 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2416 // combined with ROUND_NO_EXC.
2417 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2418 Result == 8/*ROUND_NO_EXC*/ ||
2419 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2420 return false;
2421
2422 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2423 << Arg->getSourceRange();
2424}
2425
Craig Topperdf5beb22017-03-13 17:16:50 +00002426// Check if the gather/scatter scale is legal.
2427bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2428 CallExpr *TheCall) {
2429 unsigned ArgNum = 0;
2430 switch (BuiltinID) {
2431 default:
2432 return false;
2433 case X86::BI__builtin_ia32_gatherpfdpd:
2434 case X86::BI__builtin_ia32_gatherpfdps:
2435 case X86::BI__builtin_ia32_gatherpfqpd:
2436 case X86::BI__builtin_ia32_gatherpfqps:
2437 case X86::BI__builtin_ia32_scatterpfdpd:
2438 case X86::BI__builtin_ia32_scatterpfdps:
2439 case X86::BI__builtin_ia32_scatterpfqpd:
2440 case X86::BI__builtin_ia32_scatterpfqps:
2441 ArgNum = 3;
2442 break;
2443 case X86::BI__builtin_ia32_gatherd_pd:
2444 case X86::BI__builtin_ia32_gatherd_pd256:
2445 case X86::BI__builtin_ia32_gatherq_pd:
2446 case X86::BI__builtin_ia32_gatherq_pd256:
2447 case X86::BI__builtin_ia32_gatherd_ps:
2448 case X86::BI__builtin_ia32_gatherd_ps256:
2449 case X86::BI__builtin_ia32_gatherq_ps:
2450 case X86::BI__builtin_ia32_gatherq_ps256:
2451 case X86::BI__builtin_ia32_gatherd_q:
2452 case X86::BI__builtin_ia32_gatherd_q256:
2453 case X86::BI__builtin_ia32_gatherq_q:
2454 case X86::BI__builtin_ia32_gatherq_q256:
2455 case X86::BI__builtin_ia32_gatherd_d:
2456 case X86::BI__builtin_ia32_gatherd_d256:
2457 case X86::BI__builtin_ia32_gatherq_d:
2458 case X86::BI__builtin_ia32_gatherq_d256:
2459 case X86::BI__builtin_ia32_gather3div2df:
2460 case X86::BI__builtin_ia32_gather3div2di:
2461 case X86::BI__builtin_ia32_gather3div4df:
2462 case X86::BI__builtin_ia32_gather3div4di:
2463 case X86::BI__builtin_ia32_gather3div4sf:
2464 case X86::BI__builtin_ia32_gather3div4si:
2465 case X86::BI__builtin_ia32_gather3div8sf:
2466 case X86::BI__builtin_ia32_gather3div8si:
2467 case X86::BI__builtin_ia32_gather3siv2df:
2468 case X86::BI__builtin_ia32_gather3siv2di:
2469 case X86::BI__builtin_ia32_gather3siv4df:
2470 case X86::BI__builtin_ia32_gather3siv4di:
2471 case X86::BI__builtin_ia32_gather3siv4sf:
2472 case X86::BI__builtin_ia32_gather3siv4si:
2473 case X86::BI__builtin_ia32_gather3siv8sf:
2474 case X86::BI__builtin_ia32_gather3siv8si:
2475 case X86::BI__builtin_ia32_gathersiv8df:
2476 case X86::BI__builtin_ia32_gathersiv16sf:
2477 case X86::BI__builtin_ia32_gatherdiv8df:
2478 case X86::BI__builtin_ia32_gatherdiv16sf:
2479 case X86::BI__builtin_ia32_gathersiv8di:
2480 case X86::BI__builtin_ia32_gathersiv16si:
2481 case X86::BI__builtin_ia32_gatherdiv8di:
2482 case X86::BI__builtin_ia32_gatherdiv16si:
2483 case X86::BI__builtin_ia32_scatterdiv2df:
2484 case X86::BI__builtin_ia32_scatterdiv2di:
2485 case X86::BI__builtin_ia32_scatterdiv4df:
2486 case X86::BI__builtin_ia32_scatterdiv4di:
2487 case X86::BI__builtin_ia32_scatterdiv4sf:
2488 case X86::BI__builtin_ia32_scatterdiv4si:
2489 case X86::BI__builtin_ia32_scatterdiv8sf:
2490 case X86::BI__builtin_ia32_scatterdiv8si:
2491 case X86::BI__builtin_ia32_scattersiv2df:
2492 case X86::BI__builtin_ia32_scattersiv2di:
2493 case X86::BI__builtin_ia32_scattersiv4df:
2494 case X86::BI__builtin_ia32_scattersiv4di:
2495 case X86::BI__builtin_ia32_scattersiv4sf:
2496 case X86::BI__builtin_ia32_scattersiv4si:
2497 case X86::BI__builtin_ia32_scattersiv8sf:
2498 case X86::BI__builtin_ia32_scattersiv8si:
2499 case X86::BI__builtin_ia32_scattersiv8df:
2500 case X86::BI__builtin_ia32_scattersiv16sf:
2501 case X86::BI__builtin_ia32_scatterdiv8df:
2502 case X86::BI__builtin_ia32_scatterdiv16sf:
2503 case X86::BI__builtin_ia32_scattersiv8di:
2504 case X86::BI__builtin_ia32_scattersiv16si:
2505 case X86::BI__builtin_ia32_scatterdiv8di:
2506 case X86::BI__builtin_ia32_scatterdiv16si:
2507 ArgNum = 4;
2508 break;
2509 }
2510
2511 llvm::APSInt Result;
2512
2513 // We can't check the value of a dependent argument.
2514 Expr *Arg = TheCall->getArg(ArgNum);
2515 if (Arg->isTypeDependent() || Arg->isValueDependent())
2516 return false;
2517
2518 // Check constant-ness first.
2519 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2520 return true;
2521
2522 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2523 return false;
2524
2525 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2526 << Arg->getSourceRange();
2527}
2528
Craig Topper51738f82018-04-26 20:14:46 +00002529static bool isX86_32Builtin(unsigned BuiltinID) {
2530 // These builtins only work on x86-32 targets.
2531 switch (BuiltinID) {
2532 case X86::BI__builtin_ia32_readeflags_u32:
2533 case X86::BI__builtin_ia32_writeeflags_u32:
2534 return true;
2535 }
2536
2537 return false;
2538}
2539
Craig Topperf0ddc892016-09-23 04:48:27 +00002540bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2541 if (BuiltinID == X86::BI__builtin_cpu_supports)
2542 return SemaBuiltinCpuSupports(*this, TheCall);
2543
Craig Topper699ae0c2017-08-10 20:28:30 +00002544 if (BuiltinID == X86::BI__builtin_cpu_is)
2545 return SemaBuiltinCpuIs(*this, TheCall);
2546
Craig Topper51738f82018-04-26 20:14:46 +00002547 // Check for 32-bit only builtins on a 64-bit target.
2548 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2549 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
2550 return Diag(TheCall->getCallee()->getLocStart(),
2551 diag::err_32_bit_builtin_64_bit_tgt);
2552
Craig Toppera7e253e2016-09-23 04:48:31 +00002553 // If the intrinsic has rounding or SAE make sure its valid.
2554 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2555 return true;
2556
Craig Topperdf5beb22017-03-13 17:16:50 +00002557 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2558 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2559 return true;
2560
Craig Topperf0ddc892016-09-23 04:48:27 +00002561 // For intrinsics which take an immediate value as part of the instruction,
2562 // range check them here.
2563 int i = 0, l = 0, u = 0;
2564 switch (BuiltinID) {
2565 default:
2566 return false;
Craig Topper11899b02018-06-05 21:54:35 +00002567 case X86::BI__builtin_ia32_vec_ext_v2si:
Craig Topperf3914b72018-06-06 00:24:55 +00002568 case X86::BI__builtin_ia32_vec_ext_v2di:
Craig Topper11899b02018-06-05 21:54:35 +00002569 i = 1; l = 0; u = 1;
2570 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002571 case X86::BI__builtin_ia32_vec_set_v2di:
2572 i = 2; l = 0; u = 1;
2573 break;
Craig Topper11899b02018-06-05 21:54:35 +00002574 case X86::BI__builtin_ia32_vec_ext_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00002575 case X86::BI__builtin_ia32_vec_ext_v4si:
2576 case X86::BI__builtin_ia32_vec_ext_v4sf:
2577 case X86::BI__builtin_ia32_vec_ext_v4di:
Craig Topper11899b02018-06-05 21:54:35 +00002578 i = 1; l = 0; u = 3;
2579 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002580 case X86::BI_mm_prefetch:
2581 case X86::BI__builtin_ia32_vec_ext_v8hi:
2582 case X86::BI__builtin_ia32_vec_ext_v8si:
2583 i = 1; l = 0; u = 7;
2584 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002585 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper11899b02018-06-05 21:54:35 +00002586 case X86::BI__builtin_ia32_vec_set_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00002587 case X86::BI__builtin_ia32_vec_set_v4si:
2588 case X86::BI__builtin_ia32_vec_set_v4di:
Craig Topper39c87102016-05-18 03:18:12 +00002589 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002590 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002591 case X86::BI__builtin_ia32_vpermil2pd:
2592 case X86::BI__builtin_ia32_vpermil2pd256:
2593 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002594 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002595 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002596 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002597 case X86::BI__builtin_ia32_cmpb128_mask:
2598 case X86::BI__builtin_ia32_cmpw128_mask:
2599 case X86::BI__builtin_ia32_cmpd128_mask:
2600 case X86::BI__builtin_ia32_cmpq128_mask:
2601 case X86::BI__builtin_ia32_cmpb256_mask:
2602 case X86::BI__builtin_ia32_cmpw256_mask:
2603 case X86::BI__builtin_ia32_cmpd256_mask:
2604 case X86::BI__builtin_ia32_cmpq256_mask:
2605 case X86::BI__builtin_ia32_cmpb512_mask:
2606 case X86::BI__builtin_ia32_cmpw512_mask:
2607 case X86::BI__builtin_ia32_cmpd512_mask:
2608 case X86::BI__builtin_ia32_cmpq512_mask:
2609 case X86::BI__builtin_ia32_ucmpb128_mask:
2610 case X86::BI__builtin_ia32_ucmpw128_mask:
2611 case X86::BI__builtin_ia32_ucmpd128_mask:
2612 case X86::BI__builtin_ia32_ucmpq128_mask:
2613 case X86::BI__builtin_ia32_ucmpb256_mask:
2614 case X86::BI__builtin_ia32_ucmpw256_mask:
2615 case X86::BI__builtin_ia32_ucmpd256_mask:
2616 case X86::BI__builtin_ia32_ucmpq256_mask:
2617 case X86::BI__builtin_ia32_ucmpb512_mask:
2618 case X86::BI__builtin_ia32_ucmpw512_mask:
2619 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002620 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002621 case X86::BI__builtin_ia32_vpcomub:
2622 case X86::BI__builtin_ia32_vpcomuw:
2623 case X86::BI__builtin_ia32_vpcomud:
2624 case X86::BI__builtin_ia32_vpcomuq:
2625 case X86::BI__builtin_ia32_vpcomb:
2626 case X86::BI__builtin_ia32_vpcomw:
2627 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002628 case X86::BI__builtin_ia32_vpcomq:
Craig Topperf3914b72018-06-06 00:24:55 +00002629 case X86::BI__builtin_ia32_vec_set_v8hi:
2630 case X86::BI__builtin_ia32_vec_set_v8si:
Craig Topper39c87102016-05-18 03:18:12 +00002631 i = 2; l = 0; u = 7;
2632 break;
2633 case X86::BI__builtin_ia32_roundps:
2634 case X86::BI__builtin_ia32_roundpd:
2635 case X86::BI__builtin_ia32_roundps256:
2636 case X86::BI__builtin_ia32_roundpd256:
Craig Topperf3914b72018-06-06 00:24:55 +00002637 case X86::BI__builtin_ia32_vec_ext_v16qi:
2638 case X86::BI__builtin_ia32_vec_ext_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00002639 i = 1; l = 0; u = 15;
2640 break;
2641 case X86::BI__builtin_ia32_roundss:
2642 case X86::BI__builtin_ia32_roundsd:
2643 case X86::BI__builtin_ia32_rangepd128_mask:
2644 case X86::BI__builtin_ia32_rangepd256_mask:
2645 case X86::BI__builtin_ia32_rangepd512_mask:
2646 case X86::BI__builtin_ia32_rangeps128_mask:
2647 case X86::BI__builtin_ia32_rangeps256_mask:
2648 case X86::BI__builtin_ia32_rangeps512_mask:
2649 case X86::BI__builtin_ia32_getmantsd_round_mask:
2650 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00002651 case X86::BI__builtin_ia32_vec_set_v16qi:
2652 case X86::BI__builtin_ia32_vec_set_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00002653 i = 2; l = 0; u = 15;
2654 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002655 case X86::BI__builtin_ia32_vec_ext_v32qi:
2656 i = 1; l = 0; u = 31;
2657 break;
Craig Topper39c87102016-05-18 03:18:12 +00002658 case X86::BI__builtin_ia32_cmpps:
2659 case X86::BI__builtin_ia32_cmpss:
2660 case X86::BI__builtin_ia32_cmppd:
2661 case X86::BI__builtin_ia32_cmpsd:
2662 case X86::BI__builtin_ia32_cmpps256:
2663 case X86::BI__builtin_ia32_cmppd256:
2664 case X86::BI__builtin_ia32_cmpps128_mask:
2665 case X86::BI__builtin_ia32_cmppd128_mask:
2666 case X86::BI__builtin_ia32_cmpps256_mask:
2667 case X86::BI__builtin_ia32_cmppd256_mask:
2668 case X86::BI__builtin_ia32_cmpps512_mask:
2669 case X86::BI__builtin_ia32_cmppd512_mask:
2670 case X86::BI__builtin_ia32_cmpsd_mask:
2671 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00002672 case X86::BI__builtin_ia32_vec_set_v32qi:
Craig Topper39c87102016-05-18 03:18:12 +00002673 i = 2; l = 0; u = 31;
2674 break;
Craig Topper39c87102016-05-18 03:18:12 +00002675 case X86::BI__builtin_ia32_vcvtps2ph:
Craig Topper23a30222017-11-08 04:54:26 +00002676 case X86::BI__builtin_ia32_vcvtps2ph_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002677 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper23a30222017-11-08 04:54:26 +00002678 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2679 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002680 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2681 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2682 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2683 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2684 case X86::BI__builtin_ia32_rndscaleps_mask:
2685 case X86::BI__builtin_ia32_rndscalepd_mask:
2686 case X86::BI__builtin_ia32_reducepd128_mask:
2687 case X86::BI__builtin_ia32_reducepd256_mask:
2688 case X86::BI__builtin_ia32_reducepd512_mask:
2689 case X86::BI__builtin_ia32_reduceps128_mask:
2690 case X86::BI__builtin_ia32_reduceps256_mask:
2691 case X86::BI__builtin_ia32_reduceps512_mask:
2692 case X86::BI__builtin_ia32_prold512_mask:
2693 case X86::BI__builtin_ia32_prolq512_mask:
2694 case X86::BI__builtin_ia32_prold128_mask:
2695 case X86::BI__builtin_ia32_prold256_mask:
2696 case X86::BI__builtin_ia32_prolq128_mask:
2697 case X86::BI__builtin_ia32_prolq256_mask:
2698 case X86::BI__builtin_ia32_prord128_mask:
2699 case X86::BI__builtin_ia32_prord256_mask:
2700 case X86::BI__builtin_ia32_prorq128_mask:
2701 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002702 case X86::BI__builtin_ia32_fpclasspd128_mask:
2703 case X86::BI__builtin_ia32_fpclasspd256_mask:
2704 case X86::BI__builtin_ia32_fpclassps128_mask:
2705 case X86::BI__builtin_ia32_fpclassps256_mask:
2706 case X86::BI__builtin_ia32_fpclassps512_mask:
2707 case X86::BI__builtin_ia32_fpclasspd512_mask:
2708 case X86::BI__builtin_ia32_fpclasssd_mask:
2709 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002710 i = 1; l = 0; u = 255;
2711 break;
Craig Topper39c87102016-05-18 03:18:12 +00002712 case X86::BI__builtin_ia32_palignr128:
2713 case X86::BI__builtin_ia32_palignr256:
Craig Topper8e3689c2018-05-22 20:48:24 +00002714 case X86::BI__builtin_ia32_palignr512:
Craig Toppere56819e2018-06-07 21:27:41 +00002715 case X86::BI__builtin_ia32_alignq512:
2716 case X86::BI__builtin_ia32_alignd512:
2717 case X86::BI__builtin_ia32_alignd128:
2718 case X86::BI__builtin_ia32_alignd256:
2719 case X86::BI__builtin_ia32_alignq128:
2720 case X86::BI__builtin_ia32_alignq256:
Craig Topper39c87102016-05-18 03:18:12 +00002721 case X86::BI__builtin_ia32_vcomisd:
2722 case X86::BI__builtin_ia32_vcomiss:
Craig Topper39c87102016-05-18 03:18:12 +00002723 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2724 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2725 case X86::BI__builtin_ia32_dbpsadbw512_mask:
Craig Topper91926432018-01-11 01:38:02 +00002726 case X86::BI__builtin_ia32_vpshldd128_mask:
2727 case X86::BI__builtin_ia32_vpshldd256_mask:
2728 case X86::BI__builtin_ia32_vpshldd512_mask:
2729 case X86::BI__builtin_ia32_vpshldq128_mask:
2730 case X86::BI__builtin_ia32_vpshldq256_mask:
2731 case X86::BI__builtin_ia32_vpshldq512_mask:
2732 case X86::BI__builtin_ia32_vpshldw128_mask:
2733 case X86::BI__builtin_ia32_vpshldw256_mask:
2734 case X86::BI__builtin_ia32_vpshldw512_mask:
2735 case X86::BI__builtin_ia32_vpshrdd128_mask:
2736 case X86::BI__builtin_ia32_vpshrdd256_mask:
2737 case X86::BI__builtin_ia32_vpshrdd512_mask:
2738 case X86::BI__builtin_ia32_vpshrdq128_mask:
2739 case X86::BI__builtin_ia32_vpshrdq256_mask:
2740 case X86::BI__builtin_ia32_vpshrdq512_mask:
2741 case X86::BI__builtin_ia32_vpshrdw128_mask:
2742 case X86::BI__builtin_ia32_vpshrdw256_mask:
2743 case X86::BI__builtin_ia32_vpshrdw512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002744 i = 2; l = 0; u = 255;
2745 break;
2746 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2747 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2748 case X86::BI__builtin_ia32_fixupimmps512_mask:
2749 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2750 case X86::BI__builtin_ia32_fixupimmsd_mask:
2751 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2752 case X86::BI__builtin_ia32_fixupimmss_mask:
2753 case X86::BI__builtin_ia32_fixupimmss_maskz:
2754 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2755 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2756 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2757 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2758 case X86::BI__builtin_ia32_fixupimmps128_mask:
2759 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2760 case X86::BI__builtin_ia32_fixupimmps256_mask:
2761 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2762 case X86::BI__builtin_ia32_pternlogd512_mask:
2763 case X86::BI__builtin_ia32_pternlogd512_maskz:
2764 case X86::BI__builtin_ia32_pternlogq512_mask:
2765 case X86::BI__builtin_ia32_pternlogq512_maskz:
2766 case X86::BI__builtin_ia32_pternlogd128_mask:
2767 case X86::BI__builtin_ia32_pternlogd128_maskz:
2768 case X86::BI__builtin_ia32_pternlogd256_mask:
2769 case X86::BI__builtin_ia32_pternlogd256_maskz:
2770 case X86::BI__builtin_ia32_pternlogq128_mask:
2771 case X86::BI__builtin_ia32_pternlogq128_maskz:
2772 case X86::BI__builtin_ia32_pternlogq256_mask:
2773 case X86::BI__builtin_ia32_pternlogq256_maskz:
2774 i = 3; l = 0; u = 255;
2775 break;
Craig Topper9625db02017-03-12 22:19:10 +00002776 case X86::BI__builtin_ia32_gatherpfdpd:
2777 case X86::BI__builtin_ia32_gatherpfdps:
2778 case X86::BI__builtin_ia32_gatherpfqpd:
2779 case X86::BI__builtin_ia32_gatherpfqps:
2780 case X86::BI__builtin_ia32_scatterpfdpd:
2781 case X86::BI__builtin_ia32_scatterpfdps:
2782 case X86::BI__builtin_ia32_scatterpfqpd:
2783 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00002784 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00002785 break;
Craig Topper39c87102016-05-18 03:18:12 +00002786 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2787 case X86::BI__builtin_ia32_rndscaless_round_mask:
2788 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002789 break;
Craig Topperd3623152018-06-07 17:28:03 +00002790 case X86::BI__builtin_ia32_pslldqi128:
2791 case X86::BI__builtin_ia32_pslldqi256:
2792 case X86::BI__builtin_ia32_pslldqi512:
2793 case X86::BI__builtin_ia32_psrldqi128:
2794 case X86::BI__builtin_ia32_psrldqi256:
2795 case X86::BI__builtin_ia32_psrldqi512:
2796 i = 1; l = 0; u = 1023;
2797 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002798 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002799 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002800}
2801
Richard Smith55ce3522012-06-25 20:30:08 +00002802/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2803/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2804/// Returns true when the format fits the function and the FormatStringInfo has
2805/// been populated.
2806bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2807 FormatStringInfo *FSI) {
2808 FSI->HasVAListArg = Format->getFirstArg() == 0;
2809 FSI->FormatIdx = Format->getFormatIdx() - 1;
2810 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002811
Richard Smith55ce3522012-06-25 20:30:08 +00002812 // The way the format attribute works in GCC, the implicit this argument
2813 // of member functions is counted. However, it doesn't appear in our own
2814 // lists, so decrement format_idx in that case.
2815 if (IsCXXMember) {
2816 if(FSI->FormatIdx == 0)
2817 return false;
2818 --FSI->FormatIdx;
2819 if (FSI->FirstDataArg != 0)
2820 --FSI->FirstDataArg;
2821 }
2822 return true;
2823}
Mike Stump11289f42009-09-09 15:08:12 +00002824
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002825/// Checks if a the given expression evaluates to null.
2826///
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002827/// Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002828static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002829 // If the expression has non-null type, it doesn't evaluate to null.
2830 if (auto nullability
2831 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2832 if (*nullability == NullabilityKind::NonNull)
2833 return false;
2834 }
2835
Ted Kremeneka146db32014-01-17 06:24:47 +00002836 // As a special case, transparent unions initialized with zero are
2837 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002838 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002839 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2840 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002841 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002842 if (const InitListExpr *ILE =
2843 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002844 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002845 }
2846
2847 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002848 return (!Expr->isValueDependent() &&
2849 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2850 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002851}
2852
2853static void CheckNonNullArgument(Sema &S,
2854 const Expr *ArgExpr,
2855 SourceLocation CallSiteLoc) {
2856 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002857 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2858 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002859}
2860
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002861bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2862 FormatStringInfo FSI;
2863 if ((GetFormatStringType(Format) == FST_NSString) &&
2864 getFormatStringInfo(Format, false, &FSI)) {
2865 Idx = FSI.FormatIdx;
2866 return true;
2867 }
2868 return false;
2869}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002870
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002871/// Diagnose use of %s directive in an NSString which is being passed
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002872/// as formatting string to formatting method.
2873static void
2874DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2875 const NamedDecl *FDecl,
2876 Expr **Args,
2877 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002878 unsigned Idx = 0;
2879 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002880 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2881 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002882 Idx = 2;
2883 Format = true;
2884 }
2885 else
2886 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2887 if (S.GetFormatNSStringIdx(I, Idx)) {
2888 Format = true;
2889 break;
2890 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002891 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002892 if (!Format || NumArgs <= Idx)
2893 return;
2894 const Expr *FormatExpr = Args[Idx];
2895 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2896 FormatExpr = CSCE->getSubExpr();
2897 const StringLiteral *FormatString;
2898 if (const ObjCStringLiteral *OSL =
2899 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2900 FormatString = OSL->getString();
2901 else
2902 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2903 if (!FormatString)
2904 return;
2905 if (S.FormatStringHasSArg(FormatString)) {
2906 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2907 << "%s" << 1 << 1;
2908 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2909 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002910 }
2911}
2912
Douglas Gregorb4866e82015-06-19 18:13:19 +00002913/// Determine whether the given type has a non-null nullability annotation.
2914static bool isNonNullType(ASTContext &ctx, QualType type) {
2915 if (auto nullability = type->getNullability(ctx))
2916 return *nullability == NullabilityKind::NonNull;
2917
2918 return false;
2919}
2920
Ted Kremenek2bc73332014-01-17 06:24:43 +00002921static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002922 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002923 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002924 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002925 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002926 assert((FDecl || Proto) && "Need a function declaration or prototype");
2927
Ted Kremenek9aedc152014-01-17 06:24:56 +00002928 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002929 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002930 if (FDecl) {
2931 // Handle the nonnull attribute on the function/method declaration itself.
2932 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2933 if (!NonNull->args_size()) {
2934 // Easy case: all pointer arguments are nonnull.
2935 for (const auto *Arg : Args)
2936 if (S.isValidPointerAttrType(Arg->getType()))
2937 CheckNonNullArgument(S, Arg, CallSiteLoc);
2938 return;
2939 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002940
Joel E. Denny81508102018-03-13 14:51:22 +00002941 for (const ParamIdx &Idx : NonNull->args()) {
2942 unsigned IdxAST = Idx.getASTIndex();
2943 if (IdxAST >= Args.size())
Douglas Gregorb4866e82015-06-19 18:13:19 +00002944 continue;
2945 if (NonNullArgs.empty())
2946 NonNullArgs.resize(Args.size());
Joel E. Denny81508102018-03-13 14:51:22 +00002947 NonNullArgs.set(IdxAST);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002948 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002949 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002950 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002951
Douglas Gregorb4866e82015-06-19 18:13:19 +00002952 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2953 // Handle the nonnull attribute on the parameters of the
2954 // function/method.
2955 ArrayRef<ParmVarDecl*> parms;
2956 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2957 parms = FD->parameters();
2958 else
2959 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2960
2961 unsigned ParamIndex = 0;
2962 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2963 I != E; ++I, ++ParamIndex) {
2964 const ParmVarDecl *PVD = *I;
2965 if (PVD->hasAttr<NonNullAttr>() ||
2966 isNonNullType(S.Context, PVD->getType())) {
2967 if (NonNullArgs.empty())
2968 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002969
Douglas Gregorb4866e82015-06-19 18:13:19 +00002970 NonNullArgs.set(ParamIndex);
2971 }
2972 }
2973 } else {
2974 // If we have a non-function, non-method declaration but no
2975 // function prototype, try to dig out the function prototype.
2976 if (!Proto) {
2977 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2978 QualType type = VD->getType().getNonReferenceType();
2979 if (auto pointerType = type->getAs<PointerType>())
2980 type = pointerType->getPointeeType();
2981 else if (auto blockType = type->getAs<BlockPointerType>())
2982 type = blockType->getPointeeType();
2983 // FIXME: data member pointers?
2984
2985 // Dig out the function prototype, if there is one.
2986 Proto = type->getAs<FunctionProtoType>();
2987 }
2988 }
2989
2990 // Fill in non-null argument information from the nullability
2991 // information on the parameter types (if we have them).
2992 if (Proto) {
2993 unsigned Index = 0;
2994 for (auto paramType : Proto->getParamTypes()) {
2995 if (isNonNullType(S.Context, paramType)) {
2996 if (NonNullArgs.empty())
2997 NonNullArgs.resize(Args.size());
2998
2999 NonNullArgs.set(Index);
3000 }
3001
3002 ++Index;
3003 }
3004 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00003005 }
Richard Smith588bd9b2014-08-27 04:59:42 +00003006
Douglas Gregorb4866e82015-06-19 18:13:19 +00003007 // Check for non-null arguments.
3008 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3009 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00003010 if (NonNullArgs[ArgIndex])
3011 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00003012 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00003013}
3014
Richard Smith55ce3522012-06-25 20:30:08 +00003015/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00003016/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
3017/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00003018void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00003019 const Expr *ThisArg, ArrayRef<const Expr *> Args,
3020 bool IsMemberFunction, SourceLocation Loc,
3021 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00003022 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00003023 if (CurContext->isDependentContext())
3024 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00003025
Ted Kremenekb8176da2010-09-09 04:33:05 +00003026 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00003027 llvm::SmallBitVector CheckedVarArgs;
3028 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003029 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00003030 // Only create vector if there are format attributes.
3031 CheckedVarArgs.resize(Args.size());
3032
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003033 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00003034 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00003035 }
Richard Smithd7293d72013-08-05 18:49:43 +00003036 }
Richard Smith55ce3522012-06-25 20:30:08 +00003037
3038 // Refuse POD arguments that weren't caught by the format string
3039 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00003040 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3041 if (CallType != VariadicDoesNotApply &&
3042 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00003043 unsigned NumParams = Proto ? Proto->getNumParams()
3044 : FDecl && isa<FunctionDecl>(FDecl)
3045 ? cast<FunctionDecl>(FDecl)->getNumParams()
3046 : FDecl && isa<ObjCMethodDecl>(FDecl)
3047 ? cast<ObjCMethodDecl>(FDecl)->param_size()
3048 : 0;
3049
Alp Toker9cacbab2014-01-20 20:26:09 +00003050 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00003051 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00003052 if (const Expr *Arg = Args[ArgIdx]) {
3053 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3054 checkVariadicArgument(Arg, CallType);
3055 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00003056 }
Richard Smithd7293d72013-08-05 18:49:43 +00003057 }
Mike Stump11289f42009-09-09 15:08:12 +00003058
Douglas Gregorb4866e82015-06-19 18:13:19 +00003059 if (FDecl || Proto) {
3060 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00003061
Richard Trieu41bc0992013-06-22 00:20:41 +00003062 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00003063 if (FDecl) {
3064 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +00003065 CheckArgumentWithTypeTag(I, Args, Loc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00003066 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00003067 }
George Burgess IVce6284b2017-01-28 02:19:40 +00003068
3069 if (FD)
3070 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00003071}
3072
3073/// CheckConstructorCall - Check a constructor call for correctness and safety
3074/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003075void Sema::CheckConstructorCall(FunctionDecl *FDecl,
3076 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003077 const FunctionProtoType *Proto,
3078 SourceLocation Loc) {
3079 VariadicCallType CallType =
3080 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00003081 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
3082 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00003083}
3084
3085/// CheckFunctionCall - Check a direct function call for various correctness
3086/// and safety properties not strictly enforced by the C type system.
3087bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
3088 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00003089 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
3090 isa<CXXMethodDecl>(FDecl);
3091 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
3092 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00003093 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
3094 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00003095 Expr** Args = TheCall->getArgs();
3096 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00003097
3098 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00003099 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00003100 // If this is a call to a member operator, hide the first argument
3101 // from checkCall.
3102 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00003103 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00003104 ++Args;
3105 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00003106 } else if (IsMemberFunction)
3107 ImplicitThis =
3108 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
3109
3110 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00003111 IsMemberFunction, TheCall->getRParenLoc(),
3112 TheCall->getCallee()->getSourceRange(), CallType);
3113
3114 IdentifierInfo *FnInfo = FDecl->getIdentifier();
3115 // None of the checks below are needed for functions that don't have
3116 // simple names (e.g., C++ conversion functions).
3117 if (!FnInfo)
3118 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003119
Richard Trieua7f30b12016-12-06 01:42:28 +00003120 CheckAbsoluteValueFunction(TheCall, FDecl);
3121 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00003122
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003123 if (getLangOpts().ObjC1)
3124 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003125
Anna Zaks22122702012-01-17 00:37:07 +00003126 unsigned CMId = FDecl->getMemoryFunctionKind();
3127 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00003128 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00003129
Anna Zaks201d4892012-01-13 21:52:01 +00003130 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00003131 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00003132 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00003133 else if (CMId == Builtin::BIstrncat)
3134 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00003135 else
Anna Zaks22122702012-01-17 00:37:07 +00003136 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003137
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003138 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00003139}
3140
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003141bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00003142 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00003143 VariadicCallType CallType =
3144 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003145
George Burgess IVce6284b2017-01-28 02:19:40 +00003146 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
3147 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00003148 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003149
3150 return false;
3151}
3152
Richard Trieu664c4c62013-06-20 21:03:13 +00003153bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
3154 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00003155 QualType Ty;
3156 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00003157 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00003158 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00003159 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00003160 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003161 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003162
Douglas Gregorb4866e82015-06-19 18:13:19 +00003163 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
3164 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003165 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003166
Richard Trieu664c4c62013-06-20 21:03:13 +00003167 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00003168 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00003169 CallType = VariadicDoesNotApply;
3170 } else if (Ty->isBlockPointerType()) {
3171 CallType = VariadicBlock;
3172 } else { // Ty->isFunctionPointerType()
3173 CallType = VariadicFunction;
3174 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003175
George Burgess IVce6284b2017-01-28 02:19:40 +00003176 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00003177 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
3178 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00003179 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00003180
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003181 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00003182}
3183
Richard Trieu41bc0992013-06-22 00:20:41 +00003184/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
3185/// such as function pointers returned from functions.
3186bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003187 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00003188 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00003189 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00003190 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00003191 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00003192 TheCall->getCallee()->getSourceRange(), CallType);
3193
3194 return false;
3195}
3196
Tim Northovere94a34c2014-03-11 10:49:14 +00003197static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00003198 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00003199 return false;
3200
JF Bastiendda2cb12016-04-18 18:01:49 +00003201 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00003202 switch (Op) {
3203 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00003204 case AtomicExpr::AO__opencl_atomic_init:
Tim Northovere94a34c2014-03-11 10:49:14 +00003205 llvm_unreachable("There is no ordering argument for an init");
3206
3207 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00003208 case AtomicExpr::AO__opencl_atomic_load:
Tim Northovere94a34c2014-03-11 10:49:14 +00003209 case AtomicExpr::AO__atomic_load_n:
3210 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00003211 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
3212 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00003213
3214 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00003215 case AtomicExpr::AO__opencl_atomic_store:
Tim Northovere94a34c2014-03-11 10:49:14 +00003216 case AtomicExpr::AO__atomic_store:
3217 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00003218 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
3219 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
3220 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00003221
3222 default:
3223 return true;
3224 }
3225}
3226
Richard Smithfeea8832012-04-12 05:08:17 +00003227ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
3228 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003229 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3230 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003231
Yaxun Liu39195062017-08-04 18:16:31 +00003232 // All the non-OpenCL operations take one of the following forms.
3233 // The OpenCL operations take the __c11 forms with one extra argument for
3234 // synchronization scope.
Richard Smithfeea8832012-04-12 05:08:17 +00003235 enum {
3236 // C __c11_atomic_init(A *, C)
3237 Init,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003238
Richard Smithfeea8832012-04-12 05:08:17 +00003239 // C __c11_atomic_load(A *, int)
3240 Load,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003241
Richard Smithfeea8832012-04-12 05:08:17 +00003242 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00003243 LoadCopy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003244
Eric Fiselier8d662442016-03-30 23:39:56 +00003245 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00003246 Copy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003247
Richard Smithfeea8832012-04-12 05:08:17 +00003248 // C __c11_atomic_add(A *, M, int)
3249 Arithmetic,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003250
Richard Smithfeea8832012-04-12 05:08:17 +00003251 // C __atomic_exchange_n(A *, CP, int)
3252 Xchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003253
Richard Smithfeea8832012-04-12 05:08:17 +00003254 // void __atomic_exchange(A *, C *, CP, int)
3255 GNUXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003256
Richard Smithfeea8832012-04-12 05:08:17 +00003257 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
3258 C11CmpXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003259
Richard Smithfeea8832012-04-12 05:08:17 +00003260 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
3261 GNUCmpXchg
3262 } Form = Init;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003263
Yaxun Liu39195062017-08-04 18:16:31 +00003264 const unsigned NumForm = GNUCmpXchg + 1;
Eric Fiselier8d662442016-03-30 23:39:56 +00003265 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
3266 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00003267 // where:
3268 // C is an appropriate type,
3269 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
3270 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
3271 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
3272 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003273
Yaxun Liu39195062017-08-04 18:16:31 +00003274 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
3275 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
3276 "need to update code for modified forms");
Gabor Horvath98bd0982015-03-16 09:59:54 +00003277 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
3278 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
3279 AtomicExpr::AO__atomic_load,
3280 "need to update code for modified C11 atomics");
Yaxun Liu39195062017-08-04 18:16:31 +00003281 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
3282 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
3283 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
3284 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
3285 IsOpenCL;
Richard Smithfeea8832012-04-12 05:08:17 +00003286 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
3287 Op == AtomicExpr::AO__atomic_store_n ||
3288 Op == AtomicExpr::AO__atomic_exchange_n ||
3289 Op == AtomicExpr::AO__atomic_compare_exchange_n;
3290 bool IsAddSub = false;
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003291 bool IsMinMax = false;
Richard Smithfeea8832012-04-12 05:08:17 +00003292
3293 switch (Op) {
3294 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00003295 case AtomicExpr::AO__opencl_atomic_init:
Richard Smithfeea8832012-04-12 05:08:17 +00003296 Form = Init;
3297 break;
3298
3299 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00003300 case AtomicExpr::AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00003301 case AtomicExpr::AO__atomic_load_n:
3302 Form = Load;
3303 break;
3304
Richard Smithfeea8832012-04-12 05:08:17 +00003305 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00003306 Form = LoadCopy;
3307 break;
3308
3309 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00003310 case AtomicExpr::AO__opencl_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00003311 case AtomicExpr::AO__atomic_store:
3312 case AtomicExpr::AO__atomic_store_n:
3313 Form = Copy;
3314 break;
3315
3316 case AtomicExpr::AO__c11_atomic_fetch_add:
3317 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00003318 case AtomicExpr::AO__opencl_atomic_fetch_add:
3319 case AtomicExpr::AO__opencl_atomic_fetch_sub:
3320 case AtomicExpr::AO__opencl_atomic_fetch_min:
3321 case AtomicExpr::AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00003322 case AtomicExpr::AO__atomic_fetch_add:
3323 case AtomicExpr::AO__atomic_fetch_sub:
3324 case AtomicExpr::AO__atomic_add_fetch:
3325 case AtomicExpr::AO__atomic_sub_fetch:
3326 IsAddSub = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00003327 LLVM_FALLTHROUGH;
Richard Smithfeea8832012-04-12 05:08:17 +00003328 case AtomicExpr::AO__c11_atomic_fetch_and:
3329 case AtomicExpr::AO__c11_atomic_fetch_or:
3330 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00003331 case AtomicExpr::AO__opencl_atomic_fetch_and:
3332 case AtomicExpr::AO__opencl_atomic_fetch_or:
3333 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Richard Smithfeea8832012-04-12 05:08:17 +00003334 case AtomicExpr::AO__atomic_fetch_and:
3335 case AtomicExpr::AO__atomic_fetch_or:
3336 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00003337 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00003338 case AtomicExpr::AO__atomic_and_fetch:
3339 case AtomicExpr::AO__atomic_or_fetch:
3340 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00003341 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00003342 Form = Arithmetic;
3343 break;
3344
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003345 case AtomicExpr::AO__atomic_fetch_min:
3346 case AtomicExpr::AO__atomic_fetch_max:
3347 IsMinMax = true;
3348 Form = Arithmetic;
3349 break;
3350
Richard Smithfeea8832012-04-12 05:08:17 +00003351 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00003352 case AtomicExpr::AO__opencl_atomic_exchange:
Richard Smithfeea8832012-04-12 05:08:17 +00003353 case AtomicExpr::AO__atomic_exchange_n:
3354 Form = Xchg;
3355 break;
3356
3357 case AtomicExpr::AO__atomic_exchange:
3358 Form = GNUXchg;
3359 break;
3360
3361 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3362 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +00003363 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3364 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00003365 Form = C11CmpXchg;
3366 break;
3367
3368 case AtomicExpr::AO__atomic_compare_exchange:
3369 case AtomicExpr::AO__atomic_compare_exchange_n:
3370 Form = GNUCmpXchg;
3371 break;
3372 }
3373
Yaxun Liu39195062017-08-04 18:16:31 +00003374 unsigned AdjustedNumArgs = NumArgs[Form];
3375 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3376 ++AdjustedNumArgs;
Richard Smithfeea8832012-04-12 05:08:17 +00003377 // Check we have the right number of arguments.
Yaxun Liu39195062017-08-04 18:16:31 +00003378 if (TheCall->getNumArgs() < AdjustedNumArgs) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003379 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003380 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003381 << TheCall->getCallee()->getSourceRange();
3382 return ExprError();
Yaxun Liu39195062017-08-04 18:16:31 +00003383 } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3384 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003385 diag::err_typecheck_call_too_many_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003386 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003387 << TheCall->getCallee()->getSourceRange();
3388 return ExprError();
3389 }
3390
Richard Smithfeea8832012-04-12 05:08:17 +00003391 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003392 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00003393 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3394 if (ConvertedPtr.isInvalid())
3395 return ExprError();
3396
3397 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003398 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3399 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00003400 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003401 << Ptr->getType() << Ptr->getSourceRange();
3402 return ExprError();
3403 }
3404
Richard Smithfeea8832012-04-12 05:08:17 +00003405 // For a __c11 builtin, this should be a pointer to an _Atomic type.
3406 QualType AtomTy = pointerType->getPointeeType(); // 'A'
3407 QualType ValType = AtomTy; // 'C'
3408 if (IsC11) {
3409 if (!AtomTy->isAtomicType()) {
3410 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3411 << Ptr->getType() << Ptr->getSourceRange();
3412 return ExprError();
3413 }
Yaxun Liu39195062017-08-04 18:16:31 +00003414 if (AtomTy.isConstQualified() ||
3415 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
Richard Smithe00921a2012-09-15 06:09:58 +00003416 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
Yaxun Liu39195062017-08-04 18:16:31 +00003417 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3418 << Ptr->getSourceRange();
Richard Smithe00921a2012-09-15 06:09:58 +00003419 return ExprError();
3420 }
Richard Smithfeea8832012-04-12 05:08:17 +00003421 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00003422 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00003423 if (ValType.isConstQualified()) {
3424 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3425 << Ptr->getType() << Ptr->getSourceRange();
3426 return ExprError();
3427 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003428 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003429
Richard Smithfeea8832012-04-12 05:08:17 +00003430 // For an arithmetic operation, the implied arithmetic must be well-formed.
3431 if (Form == Arithmetic) {
3432 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003433 if (IsAddSub && !ValType->isIntegerType()
3434 && !ValType->isPointerType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003435 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3436 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3437 return ExprError();
3438 }
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003439 if (IsMinMax) {
3440 const BuiltinType *BT = ValType->getAs<BuiltinType>();
3441 if (!BT || (BT->getKind() != BuiltinType::Int &&
3442 BT->getKind() != BuiltinType::UInt)) {
3443 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_int32_or_ptr);
3444 return ExprError();
3445 }
3446 }
3447 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003448 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3449 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3450 return ExprError();
3451 }
David Majnemere85cff82015-01-28 05:48:06 +00003452 if (IsC11 && ValType->isPointerType() &&
3453 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3454 diag::err_incomplete_type)) {
3455 return ExprError();
3456 }
Richard Smithfeea8832012-04-12 05:08:17 +00003457 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3458 // For __atomic_*_n operations, the value type must be a scalar integral or
3459 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003460 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00003461 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3462 return ExprError();
3463 }
3464
Eli Friedmanaa769812013-09-11 03:49:34 +00003465 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3466 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003467 // For GNU atomics, require a trivially-copyable type. This is not part of
3468 // the GNU atomics specification, but we enforce it for sanity.
3469 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003470 << Ptr->getType() << Ptr->getSourceRange();
3471 return ExprError();
3472 }
3473
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003474 switch (ValType.getObjCLifetime()) {
3475 case Qualifiers::OCL_None:
3476 case Qualifiers::OCL_ExplicitNone:
3477 // okay
3478 break;
3479
3480 case Qualifiers::OCL_Weak:
3481 case Qualifiers::OCL_Strong:
3482 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00003483 // FIXME: Can this happen? By this point, ValType should be known
3484 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003485 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3486 << ValType << Ptr->getSourceRange();
3487 return ExprError();
3488 }
3489
JF Bastien7f0a05a2018-05-25 00:07:09 +00003490 // All atomic operations have an overload which takes a pointer to a volatile
3491 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
3492 // into the result or the other operands. Similarly atomic_load takes a
3493 // pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00003494 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00003495 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003496 QualType ResultType = ValType;
Yaxun Liu39195062017-08-04 18:16:31 +00003497 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3498 Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003499 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00003500 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003501 ResultType = Context.BoolTy;
3502
Richard Smithfeea8832012-04-12 05:08:17 +00003503 // The type of a parameter passed 'by value'. In the GNU atomics, such
3504 // arguments are actually passed as pointers.
3505 QualType ByValType = ValType; // 'CP'
JF Bastien7f0a05a2018-05-25 00:07:09 +00003506 bool IsPassedByAddress = false;
3507 if (!IsC11 && !IsN) {
Richard Smithfeea8832012-04-12 05:08:17 +00003508 ByValType = Ptr->getType();
JF Bastien7f0a05a2018-05-25 00:07:09 +00003509 IsPassedByAddress = true;
3510 }
Richard Smithfeea8832012-04-12 05:08:17 +00003511
JF Bastien7f0a05a2018-05-25 00:07:09 +00003512 // The first argument's non-CV pointer type is used to deduce the type of
3513 // subsequent arguments, except for:
3514 // - weak flag (always converted to bool)
3515 // - memory order (always converted to int)
3516 // - scope (always converted to int)
3517 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003518 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00003519 if (i < NumVals[Form] + 1) {
3520 switch (i) {
JF Bastien7f0a05a2018-05-25 00:07:09 +00003521 case 0:
3522 // The first argument is always a pointer. It has a fixed type.
3523 // It is always dereferenced, a nullptr is undefined.
3524 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
3525 // Nothing else to do: we already know all we want about this pointer.
3526 continue;
Richard Smithfeea8832012-04-12 05:08:17 +00003527 case 1:
3528 // The second argument is the non-atomic operand. For arithmetic, this
3529 // is always passed by value, and for a compare_exchange it is always
3530 // passed by address. For the rest, GNU uses by-address and C11 uses
3531 // by-value.
3532 assert(Form != Load);
3533 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3534 Ty = ValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00003535 else if (Form == Copy || Form == Xchg) {
3536 if (IsPassedByAddress)
3537 // The value pointer is always dereferenced, a nullptr is undefined.
3538 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
Richard Smithfeea8832012-04-12 05:08:17 +00003539 Ty = ByValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00003540 } else if (Form == Arithmetic)
Richard Smithfeea8832012-04-12 05:08:17 +00003541 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003542 else {
3543 Expr *ValArg = TheCall->getArg(i);
JF Bastien7f0a05a2018-05-25 00:07:09 +00003544 // The value pointer is always dereferenced, a nullptr is undefined.
Alex Lorenz67522152016-11-23 16:57:03 +00003545 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Alexander Richardson6d989432017-10-15 18:48:14 +00003546 LangAS AS = LangAS::Default;
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003547 // Keep address space of non-atomic pointer type.
3548 if (const PointerType *PtrTy =
3549 ValArg->getType()->getAs<PointerType>()) {
3550 AS = PtrTy->getPointeeType().getAddressSpace();
3551 }
3552 Ty = Context.getPointerType(
3553 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3554 }
Richard Smithfeea8832012-04-12 05:08:17 +00003555 break;
3556 case 2:
JF Bastien7f0a05a2018-05-25 00:07:09 +00003557 // The third argument to compare_exchange / GNU exchange is the desired
JF Bastien7853d5f2018-05-25 17:36:49 +00003558 // value, either by-value (for the C11 and *_n variant) or as a pointer.
3559 if (IsPassedByAddress)
JF Bastien7f0a05a2018-05-25 00:07:09 +00003560 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
Richard Smithfeea8832012-04-12 05:08:17 +00003561 Ty = ByValType;
3562 break;
3563 case 3:
3564 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3565 Ty = Context.BoolTy;
3566 break;
3567 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003568 } else {
Yaxun Liu39195062017-08-04 18:16:31 +00003569 // The order(s) and scope are always converted to int.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003570 Ty = Context.IntTy;
3571 }
Richard Smithfeea8832012-04-12 05:08:17 +00003572
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003573 InitializedEntity Entity =
3574 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00003575 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003576 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3577 if (Arg.isInvalid())
3578 return true;
3579 TheCall->setArg(i, Arg.get());
3580 }
3581
Richard Smithfeea8832012-04-12 05:08:17 +00003582 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003583 SmallVector<Expr*, 5> SubExprs;
3584 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00003585 switch (Form) {
3586 case Init:
3587 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00003588 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003589 break;
3590 case Load:
3591 SubExprs.push_back(TheCall->getArg(1)); // Order
3592 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00003593 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00003594 case Copy:
3595 case Arithmetic:
3596 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003597 SubExprs.push_back(TheCall->getArg(2)); // Order
3598 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003599 break;
3600 case GNUXchg:
3601 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3602 SubExprs.push_back(TheCall->getArg(3)); // Order
3603 SubExprs.push_back(TheCall->getArg(1)); // Val1
3604 SubExprs.push_back(TheCall->getArg(2)); // Val2
3605 break;
3606 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003607 SubExprs.push_back(TheCall->getArg(3)); // Order
3608 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003609 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00003610 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00003611 break;
3612 case GNUCmpXchg:
3613 SubExprs.push_back(TheCall->getArg(4)); // Order
3614 SubExprs.push_back(TheCall->getArg(1)); // Val1
3615 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3616 SubExprs.push_back(TheCall->getArg(2)); // Val2
3617 SubExprs.push_back(TheCall->getArg(3)); // Weak
3618 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003619 }
Tim Northovere94a34c2014-03-11 10:49:14 +00003620
3621 if (SubExprs.size() >= 2 && Form != Init) {
3622 llvm::APSInt Result(32);
3623 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3624 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00003625 Diag(SubExprs[1]->getLocStart(),
3626 diag::warn_atomic_op_has_invalid_memory_order)
3627 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00003628 }
3629
Yaxun Liu30d652a2017-08-15 16:02:49 +00003630 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3631 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3632 llvm::APSInt Result(32);
3633 if (Scope->isIntegerConstantExpr(Result, Context) &&
3634 !ScopeModel->isValid(Result.getZExtValue())) {
3635 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3636 << Scope->getSourceRange();
3637 }
3638 SubExprs.push_back(Scope);
3639 }
3640
Fariborz Jahanian615de762013-05-28 17:37:39 +00003641 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3642 SubExprs, ResultType, Op,
3643 TheCall->getRParenLoc());
3644
3645 if ((Op == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00003646 Op == AtomicExpr::AO__c11_atomic_store ||
3647 Op == AtomicExpr::AO__opencl_atomic_load ||
3648 Op == AtomicExpr::AO__opencl_atomic_store ) &&
Fariborz Jahanian615de762013-05-28 17:37:39 +00003649 Context.AtomicUsesUnsupportedLibcall(AE))
Yaxun Liu39195062017-08-04 18:16:31 +00003650 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3651 << ((Op == AtomicExpr::AO__c11_atomic_load ||
3652 Op == AtomicExpr::AO__opencl_atomic_load)
3653 ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003654
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003655 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003656}
3657
John McCall29ad95b2011-08-27 01:09:30 +00003658/// checkBuiltinArgument - Given a call to a builtin function, perform
3659/// normal type-checking on the given argument, updating the call in
3660/// place. This is useful when a builtin function requires custom
3661/// type-checking for some of its arguments but not necessarily all of
3662/// them.
3663///
3664/// Returns true on error.
3665static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3666 FunctionDecl *Fn = E->getDirectCallee();
3667 assert(Fn && "builtin call without direct callee!");
3668
3669 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3670 InitializedEntity Entity =
3671 InitializedEntity::InitializeParameter(S.Context, Param);
3672
3673 ExprResult Arg = E->getArg(0);
3674 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3675 if (Arg.isInvalid())
3676 return true;
3677
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003678 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003679 return false;
3680}
3681
Chris Lattnerdc046542009-05-08 06:58:22 +00003682/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3683/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3684/// type of its first argument. The main ActOnCallExpr routines have already
3685/// promoted the types of arguments because all of these calls are prototyped as
3686/// void(...).
3687///
3688/// This function goes through and does final semantic checking for these
3689/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003690ExprResult
3691Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003692 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003693 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3694 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3695
3696 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003697 if (TheCall->getNumArgs() < 1) {
3698 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3699 << 0 << 1 << TheCall->getNumArgs()
3700 << TheCall->getCallee()->getSourceRange();
3701 return ExprError();
3702 }
Mike Stump11289f42009-09-09 15:08:12 +00003703
Chris Lattnerdc046542009-05-08 06:58:22 +00003704 // Inspect the first argument of the atomic builtin. This should always be
3705 // a pointer type, whose element is an integral scalar or pointer type.
3706 // Because it is a pointer type, we don't have to worry about any implicit
3707 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003708 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003709 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003710 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3711 if (FirstArgResult.isInvalid())
3712 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003713 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003714 TheCall->setArg(0, FirstArg);
3715
John McCall31168b02011-06-15 23:02:42 +00003716 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3717 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003718 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3719 << FirstArg->getType() << FirstArg->getSourceRange();
3720 return ExprError();
3721 }
Mike Stump11289f42009-09-09 15:08:12 +00003722
John McCall31168b02011-06-15 23:02:42 +00003723 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003724 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003725 !ValType->isBlockPointerType()) {
3726 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3727 << FirstArg->getType() << FirstArg->getSourceRange();
3728 return ExprError();
3729 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003730
Aaron Ballmana383c942018-05-05 17:38:42 +00003731 if (ValType.isConstQualified()) {
3732 Diag(DRE->getLocStart(), diag::err_atomic_builtin_cannot_be_const)
3733 << FirstArg->getType() << FirstArg->getSourceRange();
3734 return ExprError();
3735 }
3736
John McCall31168b02011-06-15 23:02:42 +00003737 switch (ValType.getObjCLifetime()) {
3738 case Qualifiers::OCL_None:
3739 case Qualifiers::OCL_ExplicitNone:
3740 // okay
3741 break;
3742
3743 case Qualifiers::OCL_Weak:
3744 case Qualifiers::OCL_Strong:
3745 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003746 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003747 << ValType << FirstArg->getSourceRange();
3748 return ExprError();
3749 }
3750
John McCallb50451a2011-10-05 07:41:44 +00003751 // Strip any qualifiers off ValType.
3752 ValType = ValType.getUnqualifiedType();
3753
Chandler Carruth3973af72010-07-18 20:54:12 +00003754 // The majority of builtins return a value, but a few have special return
3755 // types, so allow them to override appropriately below.
3756 QualType ResultType = ValType;
3757
Chris Lattnerdc046542009-05-08 06:58:22 +00003758 // We need to figure out which concrete builtin this maps onto. For example,
3759 // __sync_fetch_and_add with a 2 byte object turns into
3760 // __sync_fetch_and_add_2.
3761#define BUILTIN_ROW(x) \
3762 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3763 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003764
Chris Lattnerdc046542009-05-08 06:58:22 +00003765 static const unsigned BuiltinIndices[][5] = {
3766 BUILTIN_ROW(__sync_fetch_and_add),
3767 BUILTIN_ROW(__sync_fetch_and_sub),
3768 BUILTIN_ROW(__sync_fetch_and_or),
3769 BUILTIN_ROW(__sync_fetch_and_and),
3770 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003771 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003772
Chris Lattnerdc046542009-05-08 06:58:22 +00003773 BUILTIN_ROW(__sync_add_and_fetch),
3774 BUILTIN_ROW(__sync_sub_and_fetch),
3775 BUILTIN_ROW(__sync_and_and_fetch),
3776 BUILTIN_ROW(__sync_or_and_fetch),
3777 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003778 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003779
Chris Lattnerdc046542009-05-08 06:58:22 +00003780 BUILTIN_ROW(__sync_val_compare_and_swap),
3781 BUILTIN_ROW(__sync_bool_compare_and_swap),
3782 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003783 BUILTIN_ROW(__sync_lock_release),
3784 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003785 };
Mike Stump11289f42009-09-09 15:08:12 +00003786#undef BUILTIN_ROW
3787
Chris Lattnerdc046542009-05-08 06:58:22 +00003788 // Determine the index of the size.
3789 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003790 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003791 case 1: SizeIndex = 0; break;
3792 case 2: SizeIndex = 1; break;
3793 case 4: SizeIndex = 2; break;
3794 case 8: SizeIndex = 3; break;
3795 case 16: SizeIndex = 4; break;
3796 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003797 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3798 << FirstArg->getType() << FirstArg->getSourceRange();
3799 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003800 }
Mike Stump11289f42009-09-09 15:08:12 +00003801
Chris Lattnerdc046542009-05-08 06:58:22 +00003802 // Each of these builtins has one pointer argument, followed by some number of
3803 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3804 // that we ignore. Find out which row of BuiltinIndices to read from as well
3805 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003806 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003807 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003808 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003809 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003810 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003811 case Builtin::BI__sync_fetch_and_add:
3812 case Builtin::BI__sync_fetch_and_add_1:
3813 case Builtin::BI__sync_fetch_and_add_2:
3814 case Builtin::BI__sync_fetch_and_add_4:
3815 case Builtin::BI__sync_fetch_and_add_8:
3816 case Builtin::BI__sync_fetch_and_add_16:
3817 BuiltinIndex = 0;
3818 break;
3819
3820 case Builtin::BI__sync_fetch_and_sub:
3821 case Builtin::BI__sync_fetch_and_sub_1:
3822 case Builtin::BI__sync_fetch_and_sub_2:
3823 case Builtin::BI__sync_fetch_and_sub_4:
3824 case Builtin::BI__sync_fetch_and_sub_8:
3825 case Builtin::BI__sync_fetch_and_sub_16:
3826 BuiltinIndex = 1;
3827 break;
3828
3829 case Builtin::BI__sync_fetch_and_or:
3830 case Builtin::BI__sync_fetch_and_or_1:
3831 case Builtin::BI__sync_fetch_and_or_2:
3832 case Builtin::BI__sync_fetch_and_or_4:
3833 case Builtin::BI__sync_fetch_and_or_8:
3834 case Builtin::BI__sync_fetch_and_or_16:
3835 BuiltinIndex = 2;
3836 break;
3837
3838 case Builtin::BI__sync_fetch_and_and:
3839 case Builtin::BI__sync_fetch_and_and_1:
3840 case Builtin::BI__sync_fetch_and_and_2:
3841 case Builtin::BI__sync_fetch_and_and_4:
3842 case Builtin::BI__sync_fetch_and_and_8:
3843 case Builtin::BI__sync_fetch_and_and_16:
3844 BuiltinIndex = 3;
3845 break;
Mike Stump11289f42009-09-09 15:08:12 +00003846
Douglas Gregor73722482011-11-28 16:30:08 +00003847 case Builtin::BI__sync_fetch_and_xor:
3848 case Builtin::BI__sync_fetch_and_xor_1:
3849 case Builtin::BI__sync_fetch_and_xor_2:
3850 case Builtin::BI__sync_fetch_and_xor_4:
3851 case Builtin::BI__sync_fetch_and_xor_8:
3852 case Builtin::BI__sync_fetch_and_xor_16:
3853 BuiltinIndex = 4;
3854 break;
3855
Hal Finkeld2208b52014-10-02 20:53:50 +00003856 case Builtin::BI__sync_fetch_and_nand:
3857 case Builtin::BI__sync_fetch_and_nand_1:
3858 case Builtin::BI__sync_fetch_and_nand_2:
3859 case Builtin::BI__sync_fetch_and_nand_4:
3860 case Builtin::BI__sync_fetch_and_nand_8:
3861 case Builtin::BI__sync_fetch_and_nand_16:
3862 BuiltinIndex = 5;
3863 WarnAboutSemanticsChange = true;
3864 break;
3865
Douglas Gregor73722482011-11-28 16:30:08 +00003866 case Builtin::BI__sync_add_and_fetch:
3867 case Builtin::BI__sync_add_and_fetch_1:
3868 case Builtin::BI__sync_add_and_fetch_2:
3869 case Builtin::BI__sync_add_and_fetch_4:
3870 case Builtin::BI__sync_add_and_fetch_8:
3871 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003872 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003873 break;
3874
3875 case Builtin::BI__sync_sub_and_fetch:
3876 case Builtin::BI__sync_sub_and_fetch_1:
3877 case Builtin::BI__sync_sub_and_fetch_2:
3878 case Builtin::BI__sync_sub_and_fetch_4:
3879 case Builtin::BI__sync_sub_and_fetch_8:
3880 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003881 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003882 break;
3883
3884 case Builtin::BI__sync_and_and_fetch:
3885 case Builtin::BI__sync_and_and_fetch_1:
3886 case Builtin::BI__sync_and_and_fetch_2:
3887 case Builtin::BI__sync_and_and_fetch_4:
3888 case Builtin::BI__sync_and_and_fetch_8:
3889 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003890 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003891 break;
3892
3893 case Builtin::BI__sync_or_and_fetch:
3894 case Builtin::BI__sync_or_and_fetch_1:
3895 case Builtin::BI__sync_or_and_fetch_2:
3896 case Builtin::BI__sync_or_and_fetch_4:
3897 case Builtin::BI__sync_or_and_fetch_8:
3898 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003899 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003900 break;
3901
3902 case Builtin::BI__sync_xor_and_fetch:
3903 case Builtin::BI__sync_xor_and_fetch_1:
3904 case Builtin::BI__sync_xor_and_fetch_2:
3905 case Builtin::BI__sync_xor_and_fetch_4:
3906 case Builtin::BI__sync_xor_and_fetch_8:
3907 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003908 BuiltinIndex = 10;
3909 break;
3910
3911 case Builtin::BI__sync_nand_and_fetch:
3912 case Builtin::BI__sync_nand_and_fetch_1:
3913 case Builtin::BI__sync_nand_and_fetch_2:
3914 case Builtin::BI__sync_nand_and_fetch_4:
3915 case Builtin::BI__sync_nand_and_fetch_8:
3916 case Builtin::BI__sync_nand_and_fetch_16:
3917 BuiltinIndex = 11;
3918 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003919 break;
Mike Stump11289f42009-09-09 15:08:12 +00003920
Chris Lattnerdc046542009-05-08 06:58:22 +00003921 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003922 case Builtin::BI__sync_val_compare_and_swap_1:
3923 case Builtin::BI__sync_val_compare_and_swap_2:
3924 case Builtin::BI__sync_val_compare_and_swap_4:
3925 case Builtin::BI__sync_val_compare_and_swap_8:
3926 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003927 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003928 NumFixed = 2;
3929 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003930
Chris Lattnerdc046542009-05-08 06:58:22 +00003931 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003932 case Builtin::BI__sync_bool_compare_and_swap_1:
3933 case Builtin::BI__sync_bool_compare_and_swap_2:
3934 case Builtin::BI__sync_bool_compare_and_swap_4:
3935 case Builtin::BI__sync_bool_compare_and_swap_8:
3936 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003937 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003938 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003939 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003940 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003941
JF Bastien7f0a05a2018-05-25 00:07:09 +00003942 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +00003943 case Builtin::BI__sync_lock_test_and_set_1:
3944 case Builtin::BI__sync_lock_test_and_set_2:
3945 case Builtin::BI__sync_lock_test_and_set_4:
3946 case Builtin::BI__sync_lock_test_and_set_8:
3947 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003948 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003949 break;
3950
Chris Lattnerdc046542009-05-08 06:58:22 +00003951 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003952 case Builtin::BI__sync_lock_release_1:
3953 case Builtin::BI__sync_lock_release_2:
3954 case Builtin::BI__sync_lock_release_4:
3955 case Builtin::BI__sync_lock_release_8:
3956 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003957 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003958 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003959 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003960 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003961
3962 case Builtin::BI__sync_swap:
3963 case Builtin::BI__sync_swap_1:
3964 case Builtin::BI__sync_swap_2:
3965 case Builtin::BI__sync_swap_4:
3966 case Builtin::BI__sync_swap_8:
3967 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003968 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003969 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003970 }
Mike Stump11289f42009-09-09 15:08:12 +00003971
Chris Lattnerdc046542009-05-08 06:58:22 +00003972 // Now that we know how many fixed arguments we expect, first check that we
3973 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003974 if (TheCall->getNumArgs() < 1+NumFixed) {
3975 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3976 << 0 << 1+NumFixed << TheCall->getNumArgs()
3977 << TheCall->getCallee()->getSourceRange();
3978 return ExprError();
3979 }
Mike Stump11289f42009-09-09 15:08:12 +00003980
Hal Finkeld2208b52014-10-02 20:53:50 +00003981 if (WarnAboutSemanticsChange) {
3982 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3983 << TheCall->getCallee()->getSourceRange();
3984 }
3985
Chris Lattner5b9241b2009-05-08 15:36:58 +00003986 // Get the decl for the concrete builtin from this, we can tell what the
3987 // concrete integer type we should convert to is.
3988 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003989 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003990 FunctionDecl *NewBuiltinDecl;
3991 if (NewBuiltinID == BuiltinID)
3992 NewBuiltinDecl = FDecl;
3993 else {
3994 // Perform builtin lookup to avoid redeclaring it.
3995 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3996 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3997 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3998 assert(Res.getFoundDecl());
3999 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004000 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00004001 return ExprError();
4002 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004003
John McCallcf142162010-08-07 06:22:56 +00004004 // The first argument --- the pointer --- has a fixed type; we
4005 // deduce the types of the rest of the arguments accordingly. Walk
4006 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00004007 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00004008 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00004009
Chris Lattnerdc046542009-05-08 06:58:22 +00004010 // GCC does an implicit conversion to the pointer or integer ValType. This
4011 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00004012 // Initialize the argument.
4013 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4014 ValType, /*consume*/ false);
4015 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00004016 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004017 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004018
Chris Lattnerdc046542009-05-08 06:58:22 +00004019 // Okay, we have something that *can* be converted to the right type. Check
4020 // to see if there is a potentially weird extension going on here. This can
4021 // happen when you do an atomic operation on something like an char* and
4022 // pass in 42. The 42 gets converted to char. This is even more strange
4023 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00004024 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004025 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00004026 }
Mike Stump11289f42009-09-09 15:08:12 +00004027
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004028 ASTContext& Context = this->getASTContext();
4029
4030 // Create a new DeclRefExpr to refer to the new decl.
4031 DeclRefExpr* NewDRE = DeclRefExpr::Create(
4032 Context,
4033 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00004034 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004035 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00004036 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004037 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00004038 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004039 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00004040
Chris Lattnerdc046542009-05-08 06:58:22 +00004041 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00004042 // FIXME: This loses syntactic information.
4043 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
4044 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
4045 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004046 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00004047
Chandler Carruthbc8cab12010-07-18 07:23:17 +00004048 // Change the result type of the call to match the original value type. This
4049 // is arbitrary, but the codegen for these builtins ins design to handle it
4050 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00004051 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004052
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004053 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00004054}
4055
Michael Zolotukhin84df1232015-09-08 23:52:33 +00004056/// SemaBuiltinNontemporalOverloaded - We have a call to
4057/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
4058/// overloaded function based on the pointer type of its last argument.
4059///
4060/// This function goes through and does final semantic checking for these
4061/// builtins.
4062ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
4063 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
4064 DeclRefExpr *DRE =
4065 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4066 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4067 unsigned BuiltinID = FDecl->getBuiltinID();
4068 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
4069 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
4070 "Unexpected nontemporal load/store builtin!");
4071 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
4072 unsigned numArgs = isStore ? 2 : 1;
4073
4074 // Ensure that we have the proper number of arguments.
4075 if (checkArgCount(*this, TheCall, numArgs))
4076 return ExprError();
4077
4078 // Inspect the last argument of the nontemporal builtin. This should always
4079 // be a pointer type, from which we imply the type of the memory access.
4080 // Because it is a pointer type, we don't have to worry about any implicit
4081 // casts here.
4082 Expr *PointerArg = TheCall->getArg(numArgs - 1);
4083 ExprResult PointerArgResult =
4084 DefaultFunctionArrayLvalueConversion(PointerArg);
4085
4086 if (PointerArgResult.isInvalid())
4087 return ExprError();
4088 PointerArg = PointerArgResult.get();
4089 TheCall->setArg(numArgs - 1, PointerArg);
4090
4091 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
4092 if (!pointerType) {
4093 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
4094 << PointerArg->getType() << PointerArg->getSourceRange();
4095 return ExprError();
4096 }
4097
4098 QualType ValType = pointerType->getPointeeType();
4099
4100 // Strip any qualifiers off ValType.
4101 ValType = ValType.getUnqualifiedType();
4102 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4103 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
4104 !ValType->isVectorType()) {
4105 Diag(DRE->getLocStart(),
4106 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
4107 << PointerArg->getType() << PointerArg->getSourceRange();
4108 return ExprError();
4109 }
4110
4111 if (!isStore) {
4112 TheCall->setType(ValType);
4113 return TheCallResult;
4114 }
4115
4116 ExprResult ValArg = TheCall->getArg(0);
4117 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4118 Context, ValType, /*consume*/ false);
4119 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
4120 if (ValArg.isInvalid())
4121 return ExprError();
4122
4123 TheCall->setArg(0, ValArg.get());
4124 TheCall->setType(Context.VoidTy);
4125 return TheCallResult;
4126}
4127
Chris Lattner6436fb62009-02-18 06:01:06 +00004128/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00004129/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00004130/// Note: It might also make sense to do the UTF-16 conversion here (would
4131/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00004132bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00004133 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00004134 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
4135
Douglas Gregorfb65e592011-07-27 05:40:30 +00004136 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00004137 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
4138 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00004139 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00004140 }
Mike Stump11289f42009-09-09 15:08:12 +00004141
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004142 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004143 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004144 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00004145 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
4146 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4147 llvm::UTF16 *ToPtr = &ToBuf[0];
4148
4149 llvm::ConversionResult Result =
4150 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4151 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004152 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00004153 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004154 Diag(Arg->getLocStart(),
4155 diag::warn_cfstring_truncated) << Arg->getSourceRange();
4156 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00004157 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004158}
4159
Mehdi Amini06d367c2016-10-24 20:39:34 +00004160/// CheckObjCString - Checks that the format string argument to the os_log()
4161/// and os_trace() functions is correct, and converts it to const char *.
4162ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
4163 Arg = Arg->IgnoreParenCasts();
4164 auto *Literal = dyn_cast<StringLiteral>(Arg);
4165 if (!Literal) {
4166 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
4167 Literal = ObjcLiteral->getString();
4168 }
4169 }
4170
4171 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
4172 return ExprError(
4173 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
4174 << Arg->getSourceRange());
4175 }
4176
4177 ExprResult Result(Literal);
4178 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
4179 InitializedEntity Entity =
4180 InitializedEntity::InitializeParameter(Context, ResultTy, false);
4181 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
4182 return Result;
4183}
4184
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004185/// Check that the user is calling the appropriate va_start builtin for the
4186/// target and calling convention.
4187static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
4188 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
4189 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
Martin Storsjo022e7822017-07-17 20:49:45 +00004190 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004191 bool IsWindows = TT.isOSWindows();
Martin Storsjo022e7822017-07-17 20:49:45 +00004192 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
4193 if (IsX64 || IsAArch64) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004194 CallingConv CC = CC_C;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004195 if (const FunctionDecl *FD = S.getCurFunctionDecl())
4196 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
4197 if (IsMSVAStart) {
4198 // Don't allow this in System V ABI functions.
Martin Storsjo022e7822017-07-17 20:49:45 +00004199 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004200 return S.Diag(Fn->getLocStart(),
4201 diag::err_ms_va_start_used_in_sysv_function);
4202 } else {
Martin Storsjo022e7822017-07-17 20:49:45 +00004203 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004204 // On x64 Windows, don't allow this in System V ABI functions.
4205 // (Yes, that means there's no corresponding way to support variadic
4206 // System V ABI functions on Windows.)
4207 if ((IsWindows && CC == CC_X86_64SysV) ||
Martin Storsjo022e7822017-07-17 20:49:45 +00004208 (!IsWindows && CC == CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004209 return S.Diag(Fn->getLocStart(),
4210 diag::err_va_start_used_in_wrong_abi_function)
4211 << !IsWindows;
4212 }
4213 return false;
4214 }
4215
4216 if (IsMSVAStart)
Martin Storsjo022e7822017-07-17 20:49:45 +00004217 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004218 return false;
4219}
4220
4221static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
4222 ParmVarDecl **LastParam = nullptr) {
4223 // Determine whether the current function, block, or obj-c method is variadic
4224 // and get its parameter list.
4225 bool IsVariadic = false;
4226 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00004227 DeclContext *Caller = S.CurContext;
4228 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
4229 IsVariadic = Block->isVariadic();
4230 Params = Block->parameters();
4231 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004232 IsVariadic = FD->isVariadic();
4233 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00004234 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004235 IsVariadic = MD->isVariadic();
4236 // FIXME: This isn't correct for methods (results in bogus warning).
4237 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00004238 } else if (isa<CapturedDecl>(Caller)) {
4239 // We don't support va_start in a CapturedDecl.
4240 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
4241 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004242 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00004243 // This must be some other declcontext that parses exprs.
4244 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
4245 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004246 }
4247
4248 if (!IsVariadic) {
Reid Klecknerf1deb832017-05-04 19:51:05 +00004249 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004250 return true;
4251 }
4252
4253 if (LastParam)
4254 *LastParam = Params.empty() ? nullptr : Params.back();
4255
4256 return false;
4257}
4258
Charles Davisc7d5c942015-09-17 20:55:33 +00004259/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
4260/// for validity. Emit an error and return true on failure; return false
4261/// on success.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004262bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00004263 Expr *Fn = TheCall->getCallee();
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004264
4265 if (checkVAStartABI(*this, BuiltinID, Fn))
4266 return true;
4267
Chris Lattner08464942007-12-28 05:29:59 +00004268 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00004269 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004270 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004271 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4272 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00004273 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004274 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00004275 return true;
4276 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00004277
4278 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00004279 return Diag(TheCall->getLocEnd(),
4280 diag::err_typecheck_call_too_few_args_at_least)
4281 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00004282 }
4283
John McCall29ad95b2011-08-27 01:09:30 +00004284 // Type-check the first argument normally.
4285 if (checkBuiltinArgument(*this, TheCall, 0))
4286 return true;
4287
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004288 // Check that the current function is variadic, and get its last parameter.
4289 ParmVarDecl *LastParam;
4290 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
Chris Lattner43be2e62007-12-19 23:59:04 +00004291 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004292
Chris Lattner43be2e62007-12-19 23:59:04 +00004293 // Verify that the second argument to the builtin is the last argument of the
4294 // current function or method.
4295 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00004296 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004297
Nico Weber9eea7642013-05-24 23:31:57 +00004298 // These are valid if SecondArgIsLastNamedArgument is false after the next
4299 // block.
4300 QualType Type;
4301 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00004302 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00004303
Anders Carlsson6a8350b2008-02-11 04:20:54 +00004304 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
4305 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004306 SecondArgIsLastNamedArgument = PV == LastParam;
Nico Weber9eea7642013-05-24 23:31:57 +00004307
4308 Type = PV->getType();
4309 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00004310 IsCRegister =
4311 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00004312 }
4313 }
Mike Stump11289f42009-09-09 15:08:12 +00004314
Chris Lattner43be2e62007-12-19 23:59:04 +00004315 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00004316 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00004317 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00004318 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00004319 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
4320 // Promotable integers are UB, but enumerations need a bit of
4321 // extra checking to see what their promotable type actually is.
4322 if (!Type->isPromotableIntegerType())
4323 return false;
4324 if (!Type->isEnumeralType())
4325 return true;
4326 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
4327 return !(ED &&
4328 Context.typesAreCompatible(ED->getPromotionType(), Type));
4329 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00004330 unsigned Reason = 0;
4331 if (Type->isReferenceType()) Reason = 1;
4332 else if (IsCRegister) Reason = 2;
4333 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00004334 Diag(ParamLoc, diag::note_parameter_type) << Type;
4335 }
4336
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00004337 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00004338 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00004339}
Chris Lattner43be2e62007-12-19 23:59:04 +00004340
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +00004341bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004342 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
4343 // const char *named_addr);
4344
4345 Expr *Func = Call->getCallee();
4346
4347 if (Call->getNumArgs() < 3)
4348 return Diag(Call->getLocEnd(),
4349 diag::err_typecheck_call_too_few_args_at_least)
4350 << 0 /*function call*/ << 3 << Call->getNumArgs();
4351
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004352 // Type-check the first argument normally.
4353 if (checkBuiltinArgument(*this, Call, 0))
4354 return true;
4355
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004356 // Check that the current function is variadic.
4357 if (checkVAStartIsInVariadicFunction(*this, Func))
4358 return true;
4359
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004360 // __va_start on Windows does not validate the parameter qualifiers
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004361
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004362 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4363 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4364
4365 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4366 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4367
4368 const QualType &ConstCharPtrTy =
4369 Context.getPointerType(Context.CharTy.withConst());
4370 if (!Arg1Ty->isPointerType() ||
4371 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4372 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4373 << Arg1->getType() << ConstCharPtrTy
4374 << 1 /* different class */
4375 << 0 /* qualifier difference */
4376 << 3 /* parameter mismatch */
4377 << 2 << Arg1->getType() << ConstCharPtrTy;
4378
4379 const QualType SizeTy = Context.getSizeType();
4380 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4381 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4382 << Arg2->getType() << SizeTy
4383 << 1 /* different class */
4384 << 0 /* qualifier difference */
4385 << 3 /* parameter mismatch */
4386 << 3 << Arg2->getType() << SizeTy;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004387
4388 return false;
4389}
4390
Chris Lattner2da14fb2007-12-20 00:26:33 +00004391/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4392/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00004393bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4394 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00004395 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004396 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00004397 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00004398 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004399 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004400 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00004401 << SourceRange(TheCall->getArg(2)->getLocStart(),
4402 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004403
John Wiegley01296292011-04-08 18:41:53 +00004404 ExprResult OrigArg0 = TheCall->getArg(0);
4405 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004406
Chris Lattner2da14fb2007-12-20 00:26:33 +00004407 // Do standard promotions between the two arguments, returning their common
4408 // type.
Chris Lattner08464942007-12-28 05:29:59 +00004409 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00004410 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4411 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00004412
4413 // Make sure any conversions are pushed back into the call; this is
4414 // type safe since unordered compare builtins are declared as "_Bool
4415 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00004416 TheCall->setArg(0, OrigArg0.get());
4417 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00004418
John Wiegley01296292011-04-08 18:41:53 +00004419 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00004420 return false;
4421
Chris Lattner2da14fb2007-12-20 00:26:33 +00004422 // If the common type isn't a real floating type, then the arguments were
4423 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00004424 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00004425 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004426 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00004427 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4428 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004429
Chris Lattner2da14fb2007-12-20 00:26:33 +00004430 return false;
4431}
4432
Benjamin Kramer634fc102010-02-15 22:42:31 +00004433/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4434/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00004435/// to check everything. We expect the last argument to be a floating point
4436/// value.
4437bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4438 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00004439 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004440 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00004441 if (TheCall->getNumArgs() > NumArgs)
4442 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004443 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004444 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00004445 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004446 (*(TheCall->arg_end()-1))->getLocEnd());
4447
Benjamin Kramer64aae502010-02-16 10:07:31 +00004448 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00004449
Eli Friedman7e4faac2009-08-31 20:06:00 +00004450 if (OrigArg->isTypeDependent())
4451 return false;
4452
Chris Lattner68784ef2010-05-06 05:50:07 +00004453 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00004454 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00004455 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004456 diag::err_typecheck_call_invalid_unary_fp)
4457 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004458
Neil Hickey88c0fac2016-12-13 16:22:50 +00004459 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00004460 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00004461 // Only remove standard FloatCasts, leaving other casts inplace
4462 if (Cast->getCastKind() == CK_FloatingCast) {
4463 Expr *CastArg = Cast->getSubExpr();
4464 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4465 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4466 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4467 "promotion from float to either float or double is the only expected cast here");
4468 Cast->setSubExpr(nullptr);
4469 TheCall->setArg(NumArgs-1, CastArg);
4470 }
Chris Lattner68784ef2010-05-06 05:50:07 +00004471 }
4472 }
4473
Eli Friedman7e4faac2009-08-31 20:06:00 +00004474 return false;
4475}
4476
Tony Jiangbbc48e92017-05-24 15:13:32 +00004477// Customized Sema Checking for VSX builtins that have the following signature:
4478// vector [...] builtinName(vector [...], vector [...], const int);
4479// Which takes the same type of vectors (any legal vector type) for the first
4480// two arguments and takes compile time constant for the third argument.
4481// Example builtins are :
4482// vector double vec_xxpermdi(vector double, vector double, int);
4483// vector short vec_xxsldwi(vector short, vector short, int);
4484bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4485 unsigned ExpectedNumArgs = 3;
4486 if (TheCall->getNumArgs() < ExpectedNumArgs)
4487 return Diag(TheCall->getLocEnd(),
4488 diag::err_typecheck_call_too_few_args_at_least)
4489 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4490 << TheCall->getSourceRange();
4491
4492 if (TheCall->getNumArgs() > ExpectedNumArgs)
4493 return Diag(TheCall->getLocEnd(),
4494 diag::err_typecheck_call_too_many_args_at_most)
4495 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4496 << TheCall->getSourceRange();
4497
4498 // Check the third argument is a compile time constant
4499 llvm::APSInt Value;
4500 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4501 return Diag(TheCall->getLocStart(),
4502 diag::err_vsx_builtin_nonconstant_argument)
4503 << 3 /* argument index */ << TheCall->getDirectCallee()
4504 << SourceRange(TheCall->getArg(2)->getLocStart(),
4505 TheCall->getArg(2)->getLocEnd());
4506
4507 QualType Arg1Ty = TheCall->getArg(0)->getType();
4508 QualType Arg2Ty = TheCall->getArg(1)->getType();
4509
4510 // Check the type of argument 1 and argument 2 are vectors.
4511 SourceLocation BuiltinLoc = TheCall->getLocStart();
4512 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4513 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4514 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4515 << TheCall->getDirectCallee()
4516 << SourceRange(TheCall->getArg(0)->getLocStart(),
4517 TheCall->getArg(1)->getLocEnd());
4518 }
4519
4520 // Check the first two arguments are the same type.
4521 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4522 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4523 << TheCall->getDirectCallee()
4524 << SourceRange(TheCall->getArg(0)->getLocStart(),
4525 TheCall->getArg(1)->getLocEnd());
4526 }
4527
4528 // When default clang type checking is turned off and the customized type
4529 // checking is used, the returning type of the function must be explicitly
4530 // set. Otherwise it is _Bool by default.
4531 TheCall->setType(Arg1Ty);
4532
4533 return false;
4534}
4535
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004536/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4537// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00004538ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00004539 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004540 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00004541 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00004542 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4543 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004544
Nate Begemana0110022010-06-08 00:16:34 +00004545 // Determine which of the following types of shufflevector we're checking:
4546 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00004547 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00004548 QualType resType = TheCall->getArg(0)->getType();
4549 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00004550
Douglas Gregorc25f7662009-05-19 22:10:17 +00004551 if (!TheCall->getArg(0)->isTypeDependent() &&
4552 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00004553 QualType LHSType = TheCall->getArg(0)->getType();
4554 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00004555
Craig Topperbaca3892013-07-29 06:47:04 +00004556 if (!LHSType->isVectorType() || !RHSType->isVectorType())
4557 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004558 diag::err_vec_builtin_non_vector)
4559 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004560 << SourceRange(TheCall->getArg(0)->getLocStart(),
4561 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004562
Nate Begemana0110022010-06-08 00:16:34 +00004563 numElements = LHSType->getAs<VectorType>()->getNumElements();
4564 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00004565
Nate Begemana0110022010-06-08 00:16:34 +00004566 // Check to see if we have a call with 2 vector arguments, the unary shuffle
4567 // with mask. If so, verify that RHS is an integer vector type with the
4568 // same number of elts as lhs.
4569 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00004570 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00004571 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00004572 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004573 diag::err_vec_builtin_incompatible_vector)
4574 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004575 << SourceRange(TheCall->getArg(1)->getLocStart(),
4576 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004577 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00004578 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004579 diag::err_vec_builtin_incompatible_vector)
4580 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004581 << SourceRange(TheCall->getArg(0)->getLocStart(),
4582 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00004583 } else if (numElements != numResElements) {
4584 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00004585 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00004586 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004587 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004588 }
4589
4590 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00004591 if (TheCall->getArg(i)->isTypeDependent() ||
4592 TheCall->getArg(i)->isValueDependent())
4593 continue;
4594
Nate Begemana0110022010-06-08 00:16:34 +00004595 llvm::APSInt Result(32);
4596 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4597 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004598 diag::err_shufflevector_nonconstant_argument)
4599 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004600
Craig Topper50ad5b72013-08-03 17:40:38 +00004601 // Allow -1 which will be translated to undef in the IR.
4602 if (Result.isSigned() && Result.isAllOnesValue())
4603 continue;
4604
Chris Lattner7ab824e2008-08-10 02:05:13 +00004605 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004606 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004607 diag::err_shufflevector_argument_too_large)
4608 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004609 }
4610
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004611 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004612
Chris Lattner7ab824e2008-08-10 02:05:13 +00004613 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004614 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00004615 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004616 }
4617
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004618 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4619 TheCall->getCallee()->getLocStart(),
4620 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004621}
Chris Lattner43be2e62007-12-19 23:59:04 +00004622
Hal Finkelc4d7c822013-09-18 03:29:45 +00004623/// SemaConvertVectorExpr - Handle __builtin_convertvector
4624ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4625 SourceLocation BuiltinLoc,
4626 SourceLocation RParenLoc) {
4627 ExprValueKind VK = VK_RValue;
4628 ExprObjectKind OK = OK_Ordinary;
4629 QualType DstTy = TInfo->getType();
4630 QualType SrcTy = E->getType();
4631
4632 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4633 return ExprError(Diag(BuiltinLoc,
4634 diag::err_convertvector_non_vector)
4635 << E->getSourceRange());
4636 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4637 return ExprError(Diag(BuiltinLoc,
4638 diag::err_convertvector_non_vector_type));
4639
4640 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4641 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4642 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4643 if (SrcElts != DstElts)
4644 return ExprError(Diag(BuiltinLoc,
4645 diag::err_convertvector_incompatible_vector)
4646 << E->getSourceRange());
4647 }
4648
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004649 return new (Context)
4650 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00004651}
4652
Daniel Dunbarb7257262008-07-21 22:59:13 +00004653/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4654// This is declared to take (const void*, ...) and can take two
4655// optional constant int args.
4656bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00004657 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004658
Chris Lattner3b054132008-11-19 05:08:23 +00004659 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004660 return Diag(TheCall->getLocEnd(),
4661 diag::err_typecheck_call_too_many_args_at_most)
4662 << 0 /*function call*/ << 3 << NumArgs
4663 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004664
4665 // Argument 0 is checked for us and the remaining arguments must be
4666 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00004667 for (unsigned i = 1; i != NumArgs; ++i)
4668 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004669 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004670
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004671 return false;
4672}
4673
Hal Finkelf0417332014-07-17 14:25:55 +00004674/// SemaBuiltinAssume - Handle __assume (MS Extension).
4675// __assume does not evaluate its arguments, and should warn if its argument
4676// has side effects.
4677bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4678 Expr *Arg = TheCall->getArg(0);
4679 if (Arg->isInstantiationDependent()) return false;
4680
4681 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00004682 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00004683 << Arg->getSourceRange()
4684 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4685
4686 return false;
4687}
4688
David Majnemer86b1bfa2016-10-31 18:07:57 +00004689/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00004690/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4691/// than 8.
4692bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4693 // The alignment must be a constant integer.
4694 Expr *Arg = TheCall->getArg(1);
4695
4696 // We can't check the value of a dependent argument.
4697 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00004698 if (const auto *UE =
4699 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4700 if (UE->getKind() == UETT_AlignOf)
4701 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4702 << Arg->getSourceRange();
4703
David Majnemer51169932016-10-31 05:37:48 +00004704 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4705
4706 if (!Result.isPowerOf2())
4707 return Diag(TheCall->getLocStart(),
4708 diag::err_alignment_not_power_of_two)
4709 << Arg->getSourceRange();
4710
4711 if (Result < Context.getCharWidth())
4712 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4713 << (unsigned)Context.getCharWidth()
4714 << Arg->getSourceRange();
4715
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004716 if (Result > std::numeric_limits<int32_t>::max())
David Majnemer51169932016-10-31 05:37:48 +00004717 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004718 << std::numeric_limits<int32_t>::max()
David Majnemer51169932016-10-31 05:37:48 +00004719 << Arg->getSourceRange();
4720 }
4721
4722 return false;
4723}
4724
4725/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00004726/// as (const void*, size_t, ...) and can take one optional constant int arg.
4727bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4728 unsigned NumArgs = TheCall->getNumArgs();
4729
4730 if (NumArgs > 3)
4731 return Diag(TheCall->getLocEnd(),
4732 diag::err_typecheck_call_too_many_args_at_most)
4733 << 0 /*function call*/ << 3 << NumArgs
4734 << TheCall->getSourceRange();
4735
4736 // The alignment must be a constant integer.
4737 Expr *Arg = TheCall->getArg(1);
4738
4739 // We can't check the value of a dependent argument.
4740 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4741 llvm::APSInt Result;
4742 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4743 return true;
4744
4745 if (!Result.isPowerOf2())
4746 return Diag(TheCall->getLocStart(),
4747 diag::err_alignment_not_power_of_two)
4748 << Arg->getSourceRange();
4749 }
4750
4751 if (NumArgs > 2) {
4752 ExprResult Arg(TheCall->getArg(2));
4753 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4754 Context.getSizeType(), false);
4755 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4756 if (Arg.isInvalid()) return true;
4757 TheCall->setArg(2, Arg.get());
4758 }
Hal Finkelf0417332014-07-17 14:25:55 +00004759
4760 return false;
4761}
4762
Mehdi Amini06d367c2016-10-24 20:39:34 +00004763bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4764 unsigned BuiltinID =
4765 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4766 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4767
4768 unsigned NumArgs = TheCall->getNumArgs();
4769 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4770 if (NumArgs < NumRequiredArgs) {
4771 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4772 << 0 /* function call */ << NumRequiredArgs << NumArgs
4773 << TheCall->getSourceRange();
4774 }
4775 if (NumArgs >= NumRequiredArgs + 0x100) {
4776 return Diag(TheCall->getLocEnd(),
4777 diag::err_typecheck_call_too_many_args_at_most)
4778 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4779 << TheCall->getSourceRange();
4780 }
4781 unsigned i = 0;
4782
4783 // For formatting call, check buffer arg.
4784 if (!IsSizeCall) {
4785 ExprResult Arg(TheCall->getArg(i));
4786 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4787 Context, Context.VoidPtrTy, false);
4788 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4789 if (Arg.isInvalid())
4790 return true;
4791 TheCall->setArg(i, Arg.get());
4792 i++;
4793 }
4794
4795 // Check string literal arg.
4796 unsigned FormatIdx = i;
4797 {
4798 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4799 if (Arg.isInvalid())
4800 return true;
4801 TheCall->setArg(i, Arg.get());
4802 i++;
4803 }
4804
4805 // Make sure variadic args are scalar.
4806 unsigned FirstDataArg = i;
4807 while (i < NumArgs) {
4808 ExprResult Arg = DefaultVariadicArgumentPromotion(
4809 TheCall->getArg(i), VariadicFunction, nullptr);
4810 if (Arg.isInvalid())
4811 return true;
4812 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4813 if (ArgSize.getQuantity() >= 0x100) {
4814 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4815 << i << (int)ArgSize.getQuantity() << 0xff
4816 << TheCall->getSourceRange();
4817 }
4818 TheCall->setArg(i, Arg.get());
4819 i++;
4820 }
4821
4822 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4823 // call to avoid duplicate diagnostics.
4824 if (!IsSizeCall) {
4825 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4826 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4827 bool Success = CheckFormatArguments(
4828 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4829 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4830 CheckedVarArgs);
4831 if (!Success)
4832 return true;
4833 }
4834
4835 if (IsSizeCall) {
4836 TheCall->setType(Context.getSizeType());
4837 } else {
4838 TheCall->setType(Context.VoidPtrTy);
4839 }
4840 return false;
4841}
4842
Eric Christopher8d0c6212010-04-17 02:26:23 +00004843/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4844/// TheCall is a constant expression.
4845bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4846 llvm::APSInt &Result) {
4847 Expr *Arg = TheCall->getArg(ArgNum);
4848 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4849 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4850
4851 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4852
4853 if (!Arg->isIntegerConstantExpr(Result, Context))
4854 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004855 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004856
Chris Lattnerd545ad12009-09-23 06:06:36 +00004857 return false;
4858}
4859
Richard Sandiford28940af2014-04-16 08:47:51 +00004860/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4861/// TheCall is a constant expression in the range [Low, High].
4862bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4863 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004864 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004865
4866 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004867 Expr *Arg = TheCall->getArg(ArgNum);
4868 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004869 return false;
4870
Eric Christopher8d0c6212010-04-17 02:26:23 +00004871 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004872 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004873 return true;
4874
Richard Sandiford28940af2014-04-16 08:47:51 +00004875 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004876 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004877 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004878
4879 return false;
4880}
4881
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004882/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4883/// TheCall is a constant expression is a multiple of Num..
4884bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4885 unsigned Num) {
4886 llvm::APSInt Result;
4887
4888 // We can't check the value of a dependent argument.
4889 Expr *Arg = TheCall->getArg(ArgNum);
4890 if (Arg->isTypeDependent() || Arg->isValueDependent())
4891 return false;
4892
4893 // Check constant-ness first.
4894 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4895 return true;
4896
4897 if (Result.getSExtValue() % Num != 0)
4898 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4899 << Num << Arg->getSourceRange();
4900
4901 return false;
4902}
4903
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004904/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4905/// TheCall is an ARM/AArch64 special register string literal.
4906bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4907 int ArgNum, unsigned ExpectedFieldNum,
4908 bool AllowName) {
4909 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4910 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4911 BuiltinID == ARM::BI__builtin_arm_rsr ||
4912 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4913 BuiltinID == ARM::BI__builtin_arm_wsr ||
4914 BuiltinID == ARM::BI__builtin_arm_wsrp;
4915 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4916 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4917 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4918 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4919 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4920 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4921 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4922
4923 // We can't check the value of a dependent argument.
4924 Expr *Arg = TheCall->getArg(ArgNum);
4925 if (Arg->isTypeDependent() || Arg->isValueDependent())
4926 return false;
4927
4928 // Check if the argument is a string literal.
4929 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4930 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4931 << Arg->getSourceRange();
4932
4933 // Check the type of special register given.
4934 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4935 SmallVector<StringRef, 6> Fields;
4936 Reg.split(Fields, ":");
4937
4938 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4939 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4940 << Arg->getSourceRange();
4941
4942 // If the string is the name of a register then we cannot check that it is
4943 // valid here but if the string is of one the forms described in ACLE then we
4944 // can check that the supplied fields are integers and within the valid
4945 // ranges.
4946 if (Fields.size() > 1) {
4947 bool FiveFields = Fields.size() == 5;
4948
4949 bool ValidString = true;
4950 if (IsARMBuiltin) {
4951 ValidString &= Fields[0].startswith_lower("cp") ||
4952 Fields[0].startswith_lower("p");
4953 if (ValidString)
4954 Fields[0] =
4955 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4956
4957 ValidString &= Fields[2].startswith_lower("c");
4958 if (ValidString)
4959 Fields[2] = Fields[2].drop_front(1);
4960
4961 if (FiveFields) {
4962 ValidString &= Fields[3].startswith_lower("c");
4963 if (ValidString)
4964 Fields[3] = Fields[3].drop_front(1);
4965 }
4966 }
4967
4968 SmallVector<int, 5> Ranges;
4969 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00004970 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004971 else
4972 Ranges.append({15, 7, 15});
4973
4974 for (unsigned i=0; i<Fields.size(); ++i) {
4975 int IntField;
4976 ValidString &= !Fields[i].getAsInteger(10, IntField);
4977 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4978 }
4979
4980 if (!ValidString)
4981 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4982 << Arg->getSourceRange();
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004983 } else if (IsAArch64Builtin && Fields.size() == 1) {
4984 // If the register name is one of those that appear in the condition below
4985 // and the special register builtin being used is one of the write builtins,
4986 // then we require that the argument provided for writing to the register
4987 // is an integer constant expression. This is because it will be lowered to
4988 // an MSR (immediate) instruction, so we need to know the immediate at
4989 // compile time.
4990 if (TheCall->getNumArgs() != 2)
4991 return false;
4992
4993 std::string RegLower = Reg.lower();
4994 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4995 RegLower != "pan" && RegLower != "uao")
4996 return false;
4997
4998 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4999 }
5000
5001 return false;
5002}
5003
Eli Friedmanc97d0142009-05-03 06:04:26 +00005004/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00005005/// This checks that the target supports __builtin_longjmp and
5006/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00005007bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00005008 if (!Context.getTargetInfo().hasSjLjLowering())
5009 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
5010 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
5011
Eli Friedmaneed8ad22009-05-03 04:46:36 +00005012 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00005013 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00005014
Eric Christopher8d0c6212010-04-17 02:26:23 +00005015 // TODO: This is less than ideal. Overload this to take a value.
5016 if (SemaBuiltinConstantArg(TheCall, 1, Result))
5017 return true;
5018
5019 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00005020 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
5021 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
5022
5023 return false;
5024}
5025
Joerg Sonnenberger27173282015-03-11 23:46:32 +00005026/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
5027/// This checks that the target supports __builtin_setjmp.
5028bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
5029 if (!Context.getTargetInfo().hasSjLjLowering())
5030 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
5031 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
5032 return false;
5033}
5034
Richard Smithd7293d72013-08-05 18:49:43 +00005035namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005036
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005037class UncoveredArgHandler {
5038 enum { Unknown = -1, AllCovered = -2 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005039
5040 signed FirstUncoveredArg = Unknown;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005041 SmallVector<const Expr *, 4> DiagnosticExprs;
5042
5043public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005044 UncoveredArgHandler() = default;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005045
5046 bool hasUncoveredArg() const {
5047 return (FirstUncoveredArg >= 0);
5048 }
5049
5050 unsigned getUncoveredArg() const {
5051 assert(hasUncoveredArg() && "no uncovered argument");
5052 return FirstUncoveredArg;
5053 }
5054
5055 void setAllCovered() {
5056 // A string has been found with all arguments covered, so clear out
5057 // the diagnostics.
5058 DiagnosticExprs.clear();
5059 FirstUncoveredArg = AllCovered;
5060 }
5061
5062 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
5063 assert(NewFirstUncoveredArg >= 0 && "Outside range");
5064
5065 // Don't update if a previous string covers all arguments.
5066 if (FirstUncoveredArg == AllCovered)
5067 return;
5068
5069 // UncoveredArgHandler tracks the highest uncovered argument index
5070 // and with it all the strings that match this index.
5071 if (NewFirstUncoveredArg == FirstUncoveredArg)
5072 DiagnosticExprs.push_back(StrExpr);
5073 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
5074 DiagnosticExprs.clear();
5075 DiagnosticExprs.push_back(StrExpr);
5076 FirstUncoveredArg = NewFirstUncoveredArg;
5077 }
5078 }
5079
5080 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
5081};
5082
Richard Smithd7293d72013-08-05 18:49:43 +00005083enum StringLiteralCheckType {
5084 SLCT_NotALiteral,
5085 SLCT_UncheckedLiteral,
5086 SLCT_CheckedLiteral
5087};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005088
5089} // namespace
Richard Smithd7293d72013-08-05 18:49:43 +00005090
Stephen Hines648c3692016-09-16 01:07:04 +00005091static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
5092 BinaryOperatorKind BinOpKind,
5093 bool AddendIsRight) {
5094 unsigned BitWidth = Offset.getBitWidth();
5095 unsigned AddendBitWidth = Addend.getBitWidth();
5096 // There might be negative interim results.
5097 if (Addend.isUnsigned()) {
5098 Addend = Addend.zext(++AddendBitWidth);
5099 Addend.setIsSigned(true);
5100 }
5101 // Adjust the bit width of the APSInts.
5102 if (AddendBitWidth > BitWidth) {
5103 Offset = Offset.sext(AddendBitWidth);
5104 BitWidth = AddendBitWidth;
5105 } else if (BitWidth > AddendBitWidth) {
5106 Addend = Addend.sext(BitWidth);
5107 }
5108
5109 bool Ov = false;
5110 llvm::APSInt ResOffset = Offset;
5111 if (BinOpKind == BO_Add)
5112 ResOffset = Offset.sadd_ov(Addend, Ov);
5113 else {
5114 assert(AddendIsRight && BinOpKind == BO_Sub &&
5115 "operator must be add or sub with addend on the right");
5116 ResOffset = Offset.ssub_ov(Addend, Ov);
5117 }
5118
5119 // We add an offset to a pointer here so we should support an offset as big as
5120 // possible.
5121 if (Ov) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005122 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
5123 "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00005124 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00005125 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
5126 return;
5127 }
5128
5129 Offset = ResOffset;
5130}
5131
5132namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005133
Stephen Hines648c3692016-09-16 01:07:04 +00005134// This is a wrapper class around StringLiteral to support offsetted string
5135// literals as format strings. It takes the offset into account when returning
5136// the string and its length or the source locations to display notes correctly.
5137class FormatStringLiteral {
5138 const StringLiteral *FExpr;
5139 int64_t Offset;
5140
5141 public:
5142 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
5143 : FExpr(fexpr), Offset(Offset) {}
5144
5145 StringRef getString() const {
5146 return FExpr->getString().drop_front(Offset);
5147 }
5148
5149 unsigned getByteLength() const {
5150 return FExpr->getByteLength() - getCharByteWidth() * Offset;
5151 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005152
Stephen Hines648c3692016-09-16 01:07:04 +00005153 unsigned getLength() const { return FExpr->getLength() - Offset; }
5154 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
5155
5156 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
5157
5158 QualType getType() const { return FExpr->getType(); }
5159
5160 bool isAscii() const { return FExpr->isAscii(); }
5161 bool isWide() const { return FExpr->isWide(); }
5162 bool isUTF8() const { return FExpr->isUTF8(); }
5163 bool isUTF16() const { return FExpr->isUTF16(); }
5164 bool isUTF32() const { return FExpr->isUTF32(); }
5165 bool isPascal() const { return FExpr->isPascal(); }
5166
5167 SourceLocation getLocationOfByte(
5168 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
5169 const TargetInfo &Target, unsigned *StartToken = nullptr,
5170 unsigned *StartTokenByteOffset = nullptr) const {
5171 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
5172 StartToken, StartTokenByteOffset);
5173 }
5174
5175 SourceLocation getLocStart() const LLVM_READONLY {
5176 return FExpr->getLocStart().getLocWithOffset(Offset);
5177 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005178
Stephen Hines648c3692016-09-16 01:07:04 +00005179 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
5180};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005181
5182} // namespace
Stephen Hines648c3692016-09-16 01:07:04 +00005183
5184static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005185 const Expr *OrigFormatExpr,
5186 ArrayRef<const Expr *> Args,
5187 bool HasVAListArg, unsigned format_idx,
5188 unsigned firstDataArg,
5189 Sema::FormatStringType Type,
5190 bool inFunctionCall,
5191 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005192 llvm::SmallBitVector &CheckedVarArgs,
5193 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005194
Richard Smith55ce3522012-06-25 20:30:08 +00005195// Determine if an expression is a string literal or constant string.
5196// If this function returns false on the arguments to a function expecting a
5197// format string, we will usually need to emit a warning.
5198// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00005199static StringLiteralCheckType
5200checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
5201 bool HasVAListArg, unsigned format_idx,
5202 unsigned firstDataArg, Sema::FormatStringType Type,
5203 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005204 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005205 UncoveredArgHandler &UncoveredArg,
5206 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00005207 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00005208 assert(Offset.isSigned() && "invalid offset");
5209
Douglas Gregorc25f7662009-05-19 22:10:17 +00005210 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00005211 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005212
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005213 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00005214
Richard Smithd7293d72013-08-05 18:49:43 +00005215 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00005216 // Technically -Wformat-nonliteral does not warn about this case.
5217 // The behavior of printf and friends in this case is implementation
5218 // dependent. Ideally if the format string cannot be null then
5219 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00005220 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00005221
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005222 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00005223 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005224 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00005225 // The expression is a literal if both sub-expressions were, and it was
5226 // completely checked only if both sub-expressions were checked.
5227 const AbstractConditionalOperator *C =
5228 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005229
5230 // Determine whether it is necessary to check both sub-expressions, for
5231 // example, because the condition expression is a constant that can be
5232 // evaluated at compile time.
5233 bool CheckLeft = true, CheckRight = true;
5234
5235 bool Cond;
5236 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
5237 if (Cond)
5238 CheckRight = false;
5239 else
5240 CheckLeft = false;
5241 }
5242
Stephen Hines648c3692016-09-16 01:07:04 +00005243 // We need to maintain the offsets for the right and the left hand side
5244 // separately to check if every possible indexed expression is a valid
5245 // string literal. They might have different offsets for different string
5246 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005247 StringLiteralCheckType Left;
5248 if (!CheckLeft)
5249 Left = SLCT_UncheckedLiteral;
5250 else {
5251 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
5252 HasVAListArg, format_idx, firstDataArg,
5253 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00005254 CheckedVarArgs, UncoveredArg, Offset);
5255 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005256 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00005257 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005258 }
5259
Richard Smith55ce3522012-06-25 20:30:08 +00005260 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00005261 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005262 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005263 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005264 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005265
5266 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005267 }
5268
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005269 case Stmt::ImplicitCastExprClass:
Ted Kremenek808829352010-09-09 03:51:39 +00005270 E = cast<ImplicitCastExpr>(E)->getSubExpr();
5271 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005272
John McCallc07a0c72011-02-17 10:25:35 +00005273 case Stmt::OpaqueValueExprClass:
5274 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
5275 E = src;
5276 goto tryAgain;
5277 }
Richard Smith55ce3522012-06-25 20:30:08 +00005278 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00005279
Ted Kremeneka8890832011-02-24 23:03:04 +00005280 case Stmt::PredefinedExprClass:
5281 // While __func__, etc., are technically not string literals, they
5282 // cannot contain format specifiers and thus are not a security
5283 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00005284 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00005285
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005286 case Stmt::DeclRefExprClass: {
5287 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005288
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005289 // As an exception, do not flag errors for variables binding to
5290 // const string literals.
5291 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
5292 bool isConstant = false;
5293 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005294
Richard Smithd7293d72013-08-05 18:49:43 +00005295 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
5296 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00005297 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00005298 isConstant = T.isConstant(S.Context) &&
5299 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00005300 } else if (T->isObjCObjectPointerType()) {
5301 // In ObjC, there is usually no "const ObjectPointer" type,
5302 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00005303 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005304 }
Mike Stump11289f42009-09-09 15:08:12 +00005305
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005306 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00005307 if (const Expr *Init = VD->getAnyInitializer()) {
5308 // Look through initializers like const char c[] = { "foo" }
5309 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
5310 if (InitList->isStringLiteralInit())
5311 Init = InitList->getInit(0)->IgnoreParenImpCasts();
5312 }
Richard Smithd7293d72013-08-05 18:49:43 +00005313 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005314 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005315 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005316 /*InFunctionCall*/ false, CheckedVarArgs,
5317 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00005318 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005319 }
Mike Stump11289f42009-09-09 15:08:12 +00005320
Anders Carlssonb012ca92009-06-28 19:55:58 +00005321 // For vprintf* functions (i.e., HasVAListArg==true), we add a
5322 // special check to see if the format string is a function parameter
5323 // of the function calling the printf function. If the function
5324 // has an attribute indicating it is a printf-like function, then we
5325 // should suppress warnings concerning non-literals being used in a call
5326 // to a vprintf function. For example:
5327 //
5328 // void
5329 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
5330 // va_list ap;
5331 // va_start(ap, fmt);
5332 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
5333 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00005334 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005335 if (HasVAListArg) {
5336 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
5337 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
5338 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00005339 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005340 // adjust for implicit parameter
5341 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5342 if (MD->isInstance())
5343 ++PVIndex;
5344 // We also check if the formats are compatible.
5345 // We can't pass a 'scanf' string to a 'printf' function.
5346 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00005347 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00005348 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005349 }
5350 }
5351 }
5352 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005353 }
Mike Stump11289f42009-09-09 15:08:12 +00005354
Richard Smith55ce3522012-06-25 20:30:08 +00005355 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005356 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005357
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005358 case Stmt::CallExprClass:
5359 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005360 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005361 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
5362 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00005363 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
Richard Smithd7293d72013-08-05 18:49:43 +00005364 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005365 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00005366 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00005367 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005368 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5369 unsigned BuiltinID = FD->getBuiltinID();
5370 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5371 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5372 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00005373 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005374 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005375 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005376 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005377 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005378 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005379 }
5380 }
Mike Stump11289f42009-09-09 15:08:12 +00005381
Richard Smith55ce3522012-06-25 20:30:08 +00005382 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005383 }
Alex Lorenzd9007142016-10-24 09:42:34 +00005384 case Stmt::ObjCMessageExprClass: {
5385 const auto *ME = cast<ObjCMessageExpr>(E);
5386 if (const auto *ND = ME->getMethodDecl()) {
5387 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00005388 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
Alex Lorenzd9007142016-10-24 09:42:34 +00005389 return checkFormatStringExpr(
5390 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5391 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5392 }
5393 }
5394
5395 return SLCT_NotALiteral;
5396 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005397 case Stmt::ObjCStringLiteralClass:
5398 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00005399 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005400
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005401 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005402 StrE = ObjCFExpr->getString();
5403 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005404 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005405
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005406 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005407 if (Offset.isNegative() || Offset > StrE->getLength()) {
5408 // TODO: It would be better to have an explicit warning for out of
5409 // bounds literals.
5410 return SLCT_NotALiteral;
5411 }
5412 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5413 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005414 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005415 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00005416 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005417 }
Mike Stump11289f42009-09-09 15:08:12 +00005418
Richard Smith55ce3522012-06-25 20:30:08 +00005419 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005420 }
Stephen Hines648c3692016-09-16 01:07:04 +00005421 case Stmt::BinaryOperatorClass: {
5422 llvm::APSInt LResult;
5423 llvm::APSInt RResult;
5424
5425 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5426
5427 // A string literal + an int offset is still a string literal.
5428 if (BinOp->isAdditiveOp()) {
5429 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5430 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5431
5432 if (LIsInt != RIsInt) {
5433 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5434
5435 if (LIsInt) {
5436 if (BinOpKind == BO_Add) {
5437 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5438 E = BinOp->getRHS();
5439 goto tryAgain;
5440 }
5441 } else {
5442 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5443 E = BinOp->getLHS();
5444 goto tryAgain;
5445 }
5446 }
Stephen Hines648c3692016-09-16 01:07:04 +00005447 }
George Burgess IVd273aab2016-09-22 00:00:26 +00005448
5449 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00005450 }
5451 case Stmt::UnaryOperatorClass: {
5452 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5453 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005454 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005455 llvm::APSInt IndexResult;
5456 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5457 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5458 E = ASE->getBase();
5459 goto tryAgain;
5460 }
5461 }
5462
5463 return SLCT_NotALiteral;
5464 }
Mike Stump11289f42009-09-09 15:08:12 +00005465
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005466 default:
Richard Smith55ce3522012-06-25 20:30:08 +00005467 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005468 }
5469}
5470
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005471Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00005472 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00005473 .Case("scanf", FST_Scanf)
5474 .Cases("printf", "printf0", FST_Printf)
5475 .Cases("NSString", "CFString", FST_NSString)
5476 .Case("strftime", FST_Strftime)
5477 .Case("strfmon", FST_Strfmon)
5478 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5479 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5480 .Case("os_trace", FST_OSLog)
5481 .Case("os_log", FST_OSLog)
5482 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005483}
5484
Jordan Rose3e0ec582012-07-19 18:10:23 +00005485/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00005486/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00005487/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005488bool Sema::CheckFormatArguments(const FormatAttr *Format,
5489 ArrayRef<const Expr *> Args,
5490 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005491 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005492 SourceLocation Loc, SourceRange Range,
5493 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00005494 FormatStringInfo FSI;
5495 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005496 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00005497 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00005498 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00005499 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005500}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00005501
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005502bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005503 bool HasVAListArg, unsigned format_idx,
5504 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005505 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005506 SourceLocation Loc, SourceRange Range,
5507 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00005508 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005509 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005510 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00005511 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005512 }
Mike Stump11289f42009-09-09 15:08:12 +00005513
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005514 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005515
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005516 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00005517 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005518 // Dynamically generated format strings are difficult to
5519 // automatically vet at compile time. Requiring that format strings
5520 // are string literals: (1) permits the checking of format strings by
5521 // the compiler and thereby (2) can practically remove the source of
5522 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00005523
Mike Stump11289f42009-09-09 15:08:12 +00005524 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00005525 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00005526 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00005527 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005528 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00005529 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00005530 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5531 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005532 /*IsFunctionCall*/ true, CheckedVarArgs,
5533 UncoveredArg,
5534 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005535
5536 // Generate a diagnostic where an uncovered argument is detected.
5537 if (UncoveredArg.hasUncoveredArg()) {
5538 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5539 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5540 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5541 }
5542
Richard Smith55ce3522012-06-25 20:30:08 +00005543 if (CT != SLCT_NotALiteral)
5544 // Literal format string found, check done!
5545 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00005546
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005547 // Strftime is particular as it always uses a single 'time' argument,
5548 // so it is safe to pass a non-literal string.
5549 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00005550 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005551
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005552 // Do not emit diag when the string param is a macro expansion and the
5553 // format is either NSString or CFString. This is a hack to prevent
5554 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5555 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005556 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5557 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00005558 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005559
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005560 // If there are no arguments specified, warn with -Wformat-security, otherwise
5561 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005562 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00005563 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5564 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005565 switch (Type) {
5566 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005567 break;
5568 case FST_Kprintf:
5569 case FST_FreeBSDKPrintf:
5570 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00005571 Diag(FormatLoc, diag::note_format_security_fixit)
5572 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005573 break;
5574 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00005575 Diag(FormatLoc, diag::note_format_security_fixit)
5576 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005577 break;
5578 }
5579 } else {
5580 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005581 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005582 }
Richard Smith55ce3522012-06-25 20:30:08 +00005583 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005584}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005585
Ted Kremenekab278de2010-01-28 23:39:18 +00005586namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005587
Ted Kremenek02087932010-07-16 02:11:22 +00005588class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5589protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00005590 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00005591 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00005592 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005593 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00005594 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00005595 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00005596 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00005597 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005598 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00005599 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00005600 llvm::SmallBitVector CoveredArgs;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005601 bool usesPositionalArgs = false;
5602 bool atFirstArg = true;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005603 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00005604 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00005605 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005606 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005607
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005608public:
Stephen Hines648c3692016-09-16 01:07:04 +00005609 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005610 const Expr *origFormatExpr,
5611 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005612 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005613 ArrayRef<const Expr *> Args, unsigned formatIdx,
5614 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005615 llvm::SmallBitVector &CheckedVarArgs,
5616 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005617 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5618 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5619 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
Mehdi Amini06d367c2016-10-24 20:39:34 +00005620 inFunctionCall(inFunctionCall), CallType(callType),
5621 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00005622 CoveredArgs.resize(numDataArgs);
5623 CoveredArgs.reset();
5624 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005625
Ted Kremenek019d2242010-01-29 01:50:07 +00005626 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005627
Ted Kremenek02087932010-07-16 02:11:22 +00005628 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005629 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005630
Jordan Rose92303592012-09-08 04:00:03 +00005631 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005632 const analyze_format_string::FormatSpecifier &FS,
5633 const analyze_format_string::ConversionSpecifier &CS,
5634 const char *startSpecifier, unsigned specifierLen,
5635 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00005636
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005637 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005638 const analyze_format_string::FormatSpecifier &FS,
5639 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005640
5641 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005642 const analyze_format_string::ConversionSpecifier &CS,
5643 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005644
Craig Toppere14c0f82014-03-12 04:55:44 +00005645 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005646
Craig Toppere14c0f82014-03-12 04:55:44 +00005647 void HandleInvalidPosition(const char *startSpecifier,
5648 unsigned specifierLen,
5649 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005650
Craig Toppere14c0f82014-03-12 04:55:44 +00005651 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005652
Craig Toppere14c0f82014-03-12 04:55:44 +00005653 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005654
Richard Trieu03cf7b72011-10-28 00:41:25 +00005655 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00005656 static void
5657 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5658 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5659 bool IsStringLocation, Range StringRange,
5660 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005661
Ted Kremenek02087932010-07-16 02:11:22 +00005662protected:
Ted Kremenekce815422010-07-19 21:25:57 +00005663 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5664 const char *startSpec,
5665 unsigned specifierLen,
5666 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005667
5668 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5669 const char *startSpec,
5670 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00005671
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005672 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00005673 CharSourceRange getSpecifierRange(const char *startSpecifier,
5674 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00005675 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005676
Ted Kremenek5739de72010-01-29 01:06:55 +00005677 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005678
5679 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5680 const analyze_format_string::ConversionSpecifier &CS,
5681 const char *startSpecifier, unsigned specifierLen,
5682 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005683
5684 template <typename Range>
5685 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5686 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005687 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00005688};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005689
5690} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005691
Ted Kremenek02087932010-07-16 02:11:22 +00005692SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00005693 return OrigFormatExpr->getSourceRange();
5694}
5695
Ted Kremenek02087932010-07-16 02:11:22 +00005696CharSourceRange CheckFormatHandler::
5697getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00005698 SourceLocation Start = getLocationOfByte(startSpecifier);
5699 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5700
5701 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00005702 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00005703
5704 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005705}
5706
Ted Kremenek02087932010-07-16 02:11:22 +00005707SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00005708 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5709 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00005710}
5711
Ted Kremenek02087932010-07-16 02:11:22 +00005712void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5713 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00005714 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5715 getLocationOfByte(startSpecifier),
5716 /*IsStringLocation*/true,
5717 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00005718}
5719
Jordan Rose92303592012-09-08 04:00:03 +00005720void CheckFormatHandler::HandleInvalidLengthModifier(
5721 const analyze_format_string::FormatSpecifier &FS,
5722 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00005723 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00005724 using namespace analyze_format_string;
5725
5726 const LengthModifier &LM = FS.getLengthModifier();
5727 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5728
5729 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005730 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00005731 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005732 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005733 getLocationOfByte(LM.getStart()),
5734 /*IsStringLocation*/true,
5735 getSpecifierRange(startSpecifier, specifierLen));
5736
5737 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5738 << FixedLM->toString()
5739 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5740
5741 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005742 FixItHint Hint;
5743 if (DiagID == diag::warn_format_nonsensical_length)
5744 Hint = FixItHint::CreateRemoval(LMRange);
5745
5746 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005747 getLocationOfByte(LM.getStart()),
5748 /*IsStringLocation*/true,
5749 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00005750 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00005751 }
5752}
5753
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005754void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005755 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005756 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005757 using namespace analyze_format_string;
5758
5759 const LengthModifier &LM = FS.getLengthModifier();
5760 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5761
5762 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005763 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005764 if (FixedLM) {
5765 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5766 << LM.toString() << 0,
5767 getLocationOfByte(LM.getStart()),
5768 /*IsStringLocation*/true,
5769 getSpecifierRange(startSpecifier, specifierLen));
5770
5771 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5772 << FixedLM->toString()
5773 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5774
5775 } else {
5776 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5777 << LM.toString() << 0,
5778 getLocationOfByte(LM.getStart()),
5779 /*IsStringLocation*/true,
5780 getSpecifierRange(startSpecifier, specifierLen));
5781 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005782}
5783
5784void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5785 const analyze_format_string::ConversionSpecifier &CS,
5786 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005787 using namespace analyze_format_string;
5788
5789 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005790 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005791 if (FixedCS) {
5792 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5793 << CS.toString() << /*conversion specifier*/1,
5794 getLocationOfByte(CS.getStart()),
5795 /*IsStringLocation*/true,
5796 getSpecifierRange(startSpecifier, specifierLen));
5797
5798 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5799 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5800 << FixedCS->toString()
5801 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5802 } else {
5803 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5804 << CS.toString() << /*conversion specifier*/1,
5805 getLocationOfByte(CS.getStart()),
5806 /*IsStringLocation*/true,
5807 getSpecifierRange(startSpecifier, specifierLen));
5808 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005809}
5810
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005811void CheckFormatHandler::HandlePosition(const char *startPos,
5812 unsigned posLen) {
5813 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5814 getLocationOfByte(startPos),
5815 /*IsStringLocation*/true,
5816 getSpecifierRange(startPos, posLen));
5817}
5818
Ted Kremenekd1668192010-02-27 01:41:03 +00005819void
Ted Kremenek02087932010-07-16 02:11:22 +00005820CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5821 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005822 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5823 << (unsigned) p,
5824 getLocationOfByte(startPos), /*IsStringLocation*/true,
5825 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005826}
5827
Ted Kremenek02087932010-07-16 02:11:22 +00005828void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005829 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005830 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5831 getLocationOfByte(startPos),
5832 /*IsStringLocation*/true,
5833 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005834}
5835
Ted Kremenek02087932010-07-16 02:11:22 +00005836void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005837 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005838 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005839 EmitFormatDiagnostic(
5840 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5841 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5842 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005843 }
Ted Kremenek02087932010-07-16 02:11:22 +00005844}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005845
Jordan Rose58bbe422012-07-19 18:10:08 +00005846// Note that this may return NULL if there was an error parsing or building
5847// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005848const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005849 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005850}
5851
5852void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005853 // Does the number of data arguments exceed the number of
5854 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005855 if (!HasVAListArg) {
5856 // Find any arguments that weren't covered.
5857 CoveredArgs.flip();
5858 signed notCoveredArg = CoveredArgs.find_first();
5859 if (notCoveredArg >= 0) {
5860 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005861 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5862 } else {
5863 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005864 }
5865 }
5866}
5867
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005868void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5869 const Expr *ArgExpr) {
5870 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5871 "Invalid state");
5872
5873 if (!ArgExpr)
5874 return;
5875
5876 SourceLocation Loc = ArgExpr->getLocStart();
5877
5878 if (S.getSourceManager().isInSystemMacro(Loc))
5879 return;
5880
5881 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5882 for (auto E : DiagnosticExprs)
5883 PDiag << E->getSourceRange();
5884
5885 CheckFormatHandler::EmitFormatDiagnostic(
5886 S, IsFunctionCall, DiagnosticExprs[0],
5887 PDiag, Loc, /*IsStringLocation*/false,
5888 DiagnosticExprs[0]->getSourceRange());
5889}
5890
Ted Kremenekce815422010-07-19 21:25:57 +00005891bool
5892CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5893 SourceLocation Loc,
5894 const char *startSpec,
5895 unsigned specifierLen,
5896 const char *csStart,
5897 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005898 bool keepGoing = true;
5899 if (argIndex < NumDataArgs) {
5900 // Consider the argument coverered, even though the specifier doesn't
5901 // make sense.
5902 CoveredArgs.set(argIndex);
5903 }
5904 else {
5905 // If argIndex exceeds the number of data arguments we
5906 // don't issue a warning because that is just a cascade of warnings (and
5907 // they may have intended '%%' anyway). We don't want to continue processing
5908 // the format string after this point, however, as we will like just get
5909 // gibberish when trying to match arguments.
5910 keepGoing = false;
5911 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005912
5913 StringRef Specifier(csStart, csLen);
5914
5915 // If the specifier in non-printable, it could be the first byte of a UTF-8
5916 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5917 // hex value.
5918 std::string CodePointStr;
5919 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005920 llvm::UTF32 CodePoint;
5921 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5922 const llvm::UTF8 *E =
5923 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5924 llvm::ConversionResult Result =
5925 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005926
Justin Lebar90910552016-09-30 00:38:45 +00005927 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005928 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005929 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005930 }
5931
5932 llvm::raw_string_ostream OS(CodePointStr);
5933 if (CodePoint < 256)
5934 OS << "\\x" << llvm::format("%02x", CodePoint);
5935 else if (CodePoint <= 0xFFFF)
5936 OS << "\\u" << llvm::format("%04x", CodePoint);
5937 else
5938 OS << "\\U" << llvm::format("%08x", CodePoint);
5939 OS.flush();
5940 Specifier = CodePointStr;
5941 }
5942
5943 EmitFormatDiagnostic(
5944 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5945 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5946
Ted Kremenekce815422010-07-19 21:25:57 +00005947 return keepGoing;
5948}
5949
Richard Trieu03cf7b72011-10-28 00:41:25 +00005950void
5951CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5952 const char *startSpec,
5953 unsigned specifierLen) {
5954 EmitFormatDiagnostic(
5955 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5956 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5957}
5958
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005959bool
5960CheckFormatHandler::CheckNumArgs(
5961 const analyze_format_string::FormatSpecifier &FS,
5962 const analyze_format_string::ConversionSpecifier &CS,
5963 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5964
5965 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005966 PartialDiagnostic PDiag = FS.usesPositionalArg()
5967 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5968 << (argIndex+1) << NumDataArgs)
5969 : S.PDiag(diag::warn_printf_insufficient_data_args);
5970 EmitFormatDiagnostic(
5971 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5972 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005973
5974 // Since more arguments than conversion tokens are given, by extension
5975 // all arguments are covered, so mark this as so.
5976 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005977 return false;
5978 }
5979 return true;
5980}
5981
Richard Trieu03cf7b72011-10-28 00:41:25 +00005982template<typename Range>
5983void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5984 SourceLocation Loc,
5985 bool IsStringLocation,
5986 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005987 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005988 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005989 Loc, IsStringLocation, StringRange, FixIt);
5990}
5991
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005992/// If the format string is not within the function call, emit a note
Richard Trieu03cf7b72011-10-28 00:41:25 +00005993/// so that the function call and string are in diagnostic messages.
5994///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005995/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005996/// call and only one diagnostic message will be produced. Otherwise, an
5997/// extra note will be emitted pointing to location of the format string.
5998///
5999/// \param ArgumentExpr the expression that is passed as the format string
6000/// argument in the function call. Used for getting locations when two
6001/// diagnostics are emitted.
6002///
6003/// \param PDiag the callee should already have provided any strings for the
6004/// diagnostic message. This function only adds locations and fixits
6005/// to diagnostics.
6006///
6007/// \param Loc primary location for diagnostic. If two diagnostics are
6008/// required, one will be at Loc and a new SourceLocation will be created for
6009/// the other one.
6010///
6011/// \param IsStringLocation if true, Loc points to the format string should be
6012/// used for the note. Otherwise, Loc points to the argument list and will
6013/// be used with PDiag.
6014///
6015/// \param StringRange some or all of the string to highlight. This is
6016/// templated so it can accept either a CharSourceRange or a SourceRange.
6017///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00006018/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00006019template <typename Range>
6020void CheckFormatHandler::EmitFormatDiagnostic(
6021 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
6022 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
6023 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00006024 if (InFunctionCall) {
6025 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
6026 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00006027 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00006028 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006029 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
6030 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00006031
6032 const Sema::SemaDiagnosticBuilder &Note =
6033 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
6034 diag::note_format_string_defined);
6035
6036 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00006037 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00006038 }
6039}
6040
Ted Kremenek02087932010-07-16 02:11:22 +00006041//===--- CHECK: Printf format string checking ------------------------------===//
6042
6043namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006044
Ted Kremenek02087932010-07-16 02:11:22 +00006045class CheckPrintfHandler : public CheckFormatHandler {
6046public:
Stephen Hines648c3692016-09-16 01:07:04 +00006047 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006048 const Expr *origFormatExpr,
6049 const Sema::FormatStringType type, unsigned firstDataArg,
6050 unsigned numDataArgs, bool isObjC, const char *beg,
6051 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006052 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00006053 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006054 llvm::SmallBitVector &CheckedVarArgs,
6055 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006056 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6057 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6058 inFunctionCall, CallType, CheckedVarArgs,
6059 UncoveredArg) {}
6060
6061 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
6062
6063 /// Returns true if '%@' specifiers are allowed in the format string.
6064 bool allowsObjCArg() const {
6065 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
6066 FSType == Sema::FST_OSTrace;
6067 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00006068
Ted Kremenek02087932010-07-16 02:11:22 +00006069 bool HandleInvalidPrintfConversionSpecifier(
6070 const analyze_printf::PrintfSpecifier &FS,
6071 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006072 unsigned specifierLen) override;
6073
Ted Kremenek02087932010-07-16 02:11:22 +00006074 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
6075 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006076 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00006077 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6078 const char *StartSpecifier,
6079 unsigned SpecifierLen,
6080 const Expr *E);
6081
Ted Kremenek02087932010-07-16 02:11:22 +00006082 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
6083 const char *startSpecifier, unsigned specifierLen);
6084 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
6085 const analyze_printf::OptionalAmount &Amt,
6086 unsigned type,
6087 const char *startSpecifier, unsigned specifierLen);
6088 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
6089 const analyze_printf::OptionalFlag &flag,
6090 const char *startSpecifier, unsigned specifierLen);
6091 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
6092 const analyze_printf::OptionalFlag &ignoredFlag,
6093 const analyze_printf::OptionalFlag &flag,
6094 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006095 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00006096 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00006097
6098 void HandleEmptyObjCModifierFlag(const char *startFlag,
6099 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00006100
Ted Kremenek2b417712015-07-02 05:39:16 +00006101 void HandleInvalidObjCModifierFlag(const char *startFlag,
6102 unsigned flagLen) override;
6103
6104 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
6105 const char *flagsEnd,
6106 const char *conversionPosition)
6107 override;
6108};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006109
6110} // namespace
Ted Kremenek02087932010-07-16 02:11:22 +00006111
6112bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
6113 const analyze_printf::PrintfSpecifier &FS,
6114 const char *startSpecifier,
6115 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006116 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006117 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006118
Ted Kremenekce815422010-07-19 21:25:57 +00006119 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6120 getLocationOfByte(CS.getStart()),
6121 startSpecifier, specifierLen,
6122 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00006123}
6124
Ted Kremenek02087932010-07-16 02:11:22 +00006125bool CheckPrintfHandler::HandleAmount(
6126 const analyze_format_string::OptionalAmount &Amt,
6127 unsigned k, const char *startSpecifier,
6128 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006129 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006130 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00006131 unsigned argIndex = Amt.getArgIndex();
6132 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006133 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
6134 << k,
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 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006142
Ted Kremenek5739de72010-01-29 01:06:55 +00006143 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00006144 // Although not in conformance with C99, we also allow the argument to be
6145 // an 'unsigned int' as that is a reasonably safe case. GCC also
6146 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00006147 CoveredArgs.set(argIndex);
6148 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006149 if (!Arg)
6150 return false;
6151
Ted Kremenek5739de72010-01-29 01:06:55 +00006152 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006153
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006154 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
6155 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006156
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006157 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006158 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006159 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00006160 << T << Arg->getSourceRange(),
6161 getLocationOfByte(Amt.getStart()),
6162 /*IsStringLocation*/true,
6163 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00006164 // Don't do any more checking. We will just emit
6165 // spurious errors.
6166 return false;
6167 }
6168 }
6169 }
6170 return true;
6171}
Ted Kremenek5739de72010-01-29 01:06:55 +00006172
Tom Careb49ec692010-06-17 19:00:27 +00006173void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00006174 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006175 const analyze_printf::OptionalAmount &Amt,
6176 unsigned type,
6177 const char *startSpecifier,
6178 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006179 const analyze_printf::PrintfConversionSpecifier &CS =
6180 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00006181
Richard Trieu03cf7b72011-10-28 00:41:25 +00006182 FixItHint fixit =
6183 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
6184 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
6185 Amt.getConstantLength()))
6186 : FixItHint();
6187
6188 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
6189 << type << CS.toString(),
6190 getLocationOfByte(Amt.getStart()),
6191 /*IsStringLocation*/true,
6192 getSpecifierRange(startSpecifier, specifierLen),
6193 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00006194}
6195
Ted Kremenek02087932010-07-16 02:11:22 +00006196void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006197 const analyze_printf::OptionalFlag &flag,
6198 const char *startSpecifier,
6199 unsigned specifierLen) {
6200 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006201 const analyze_printf::PrintfConversionSpecifier &CS =
6202 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00006203 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
6204 << flag.toString() << CS.toString(),
6205 getLocationOfByte(flag.getPosition()),
6206 /*IsStringLocation*/true,
6207 getSpecifierRange(startSpecifier, specifierLen),
6208 FixItHint::CreateRemoval(
6209 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00006210}
6211
6212void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00006213 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006214 const analyze_printf::OptionalFlag &ignoredFlag,
6215 const analyze_printf::OptionalFlag &flag,
6216 const char *startSpecifier,
6217 unsigned specifierLen) {
6218 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00006219 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
6220 << ignoredFlag.toString() << flag.toString(),
6221 getLocationOfByte(ignoredFlag.getPosition()),
6222 /*IsStringLocation*/true,
6223 getSpecifierRange(startSpecifier, specifierLen),
6224 FixItHint::CreateRemoval(
6225 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00006226}
6227
Ted Kremenek2b417712015-07-02 05:39:16 +00006228void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
6229 unsigned flagLen) {
6230 // Warn about an empty flag.
6231 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
6232 getLocationOfByte(startFlag),
6233 /*IsStringLocation*/true,
6234 getSpecifierRange(startFlag, flagLen));
6235}
6236
6237void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
6238 unsigned flagLen) {
6239 // Warn about an invalid flag.
6240 auto Range = getSpecifierRange(startFlag, flagLen);
6241 StringRef flag(startFlag, flagLen);
6242 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
6243 getLocationOfByte(startFlag),
6244 /*IsStringLocation*/true,
6245 Range, FixItHint::CreateRemoval(Range));
6246}
6247
6248void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
6249 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
6250 // Warn about using '[...]' without a '@' conversion.
6251 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
6252 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
6253 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
6254 getLocationOfByte(conversionPosition),
6255 /*IsStringLocation*/true,
6256 Range, FixItHint::CreateRemoval(Range));
6257}
6258
Richard Smith55ce3522012-06-25 20:30:08 +00006259// Determines if the specified is a C++ class or struct containing
6260// a member with the specified name and kind (e.g. a CXXMethodDecl named
6261// "c_str()").
6262template<typename MemberKind>
6263static llvm::SmallPtrSet<MemberKind*, 1>
6264CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
6265 const RecordType *RT = Ty->getAs<RecordType>();
6266 llvm::SmallPtrSet<MemberKind*, 1> Results;
6267
6268 if (!RT)
6269 return Results;
6270 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00006271 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00006272 return Results;
6273
Alp Tokerb6cc5922014-05-03 03:45:55 +00006274 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00006275 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00006276 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00006277
6278 // We just need to include all members of the right kind turned up by the
6279 // filter, at this point.
6280 if (S.LookupQualifiedName(R, RT->getDecl()))
6281 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6282 NamedDecl *decl = (*I)->getUnderlyingDecl();
6283 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
6284 Results.insert(FK);
6285 }
6286 return Results;
6287}
6288
Richard Smith2868a732014-02-28 01:36:39 +00006289/// Check if we could call '.c_str()' on an object.
6290///
6291/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
6292/// allow the call, or if it would be ambiguous).
6293bool Sema::hasCStrMethod(const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006294 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
6295
Richard Smith2868a732014-02-28 01:36:39 +00006296 MethodSet Results =
6297 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
6298 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6299 MI != ME; ++MI)
6300 if ((*MI)->getMinRequiredArguments() == 0)
6301 return true;
6302 return false;
6303}
6304
Richard Smith55ce3522012-06-25 20:30:08 +00006305// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006306// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00006307// Returns true when a c_str() conversion method is found.
6308bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00006309 const analyze_printf::ArgType &AT, const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006310 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
Richard Smith55ce3522012-06-25 20:30:08 +00006311
6312 MethodSet Results =
6313 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
6314
6315 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6316 MI != ME; ++MI) {
6317 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00006318 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00006319 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00006320 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00006321 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00006322 S.Diag(E->getLocStart(), diag::note_printf_c_str)
6323 << "c_str()"
6324 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
6325 return true;
6326 }
6327 }
6328
6329 return false;
6330}
6331
Ted Kremenekab278de2010-01-28 23:39:18 +00006332bool
Ted Kremenek02087932010-07-16 02:11:22 +00006333CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00006334 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00006335 const char *startSpecifier,
6336 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006337 using namespace analyze_format_string;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006338 using namespace analyze_printf;
6339
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006340 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00006341
Ted Kremenek6cd69422010-07-19 22:01:06 +00006342 if (FS.consumesDataArgument()) {
6343 if (atFirstArg) {
6344 atFirstArg = false;
6345 usesPositionalArgs = FS.usesPositionalArg();
6346 }
6347 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006348 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6349 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006350 return false;
6351 }
Ted Kremenek5739de72010-01-29 01:06:55 +00006352 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006353
Ted Kremenekd1668192010-02-27 01:41:03 +00006354 // First check if the field width, precision, and conversion specifier
6355 // have matching data arguments.
6356 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
6357 startSpecifier, specifierLen)) {
6358 return false;
6359 }
6360
6361 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
6362 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006363 return false;
6364 }
6365
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006366 if (!CS.consumesDataArgument()) {
6367 // FIXME: Technically specifying a precision or field width here
6368 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00006369 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006370 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006371
Ted Kremenek4a49d982010-02-26 19:18:41 +00006372 // Consume the argument.
6373 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00006374 if (argIndex < NumDataArgs) {
6375 // The check to see if the argIndex is valid will come later.
6376 // We set the bit here because we may exit early from this
6377 // function if we encounter some other error.
6378 CoveredArgs.set(argIndex);
6379 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00006380
Dimitry Andric6b5ed342015-02-19 22:32:33 +00006381 // FreeBSD kernel extensions.
6382 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6383 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6384 // We need at least two arguments.
6385 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6386 return false;
6387
6388 // Claim the second argument.
6389 CoveredArgs.set(argIndex + 1);
6390
6391 // Type check the first argument (int for %b, pointer for %D)
6392 const Expr *Ex = getDataArg(argIndex);
6393 const analyze_printf::ArgType &AT =
6394 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6395 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6396 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6397 EmitFormatDiagnostic(
6398 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6399 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6400 << false << Ex->getSourceRange(),
6401 Ex->getLocStart(), /*IsStringLocation*/false,
6402 getSpecifierRange(startSpecifier, specifierLen));
6403
6404 // Type check the second argument (char * for both %b and %D)
6405 Ex = getDataArg(argIndex + 1);
6406 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6407 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6408 EmitFormatDiagnostic(
6409 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6410 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6411 << false << Ex->getSourceRange(),
6412 Ex->getLocStart(), /*IsStringLocation*/false,
6413 getSpecifierRange(startSpecifier, specifierLen));
6414
6415 return true;
6416 }
6417
Ted Kremenek4a49d982010-02-26 19:18:41 +00006418 // Check for using an Objective-C specific conversion specifier
6419 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006420 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00006421 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6422 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00006423 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006424
Mehdi Amini06d367c2016-10-24 20:39:34 +00006425 // %P can only be used with os_log.
6426 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6427 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6428 specifierLen);
6429 }
6430
6431 // %n is not allowed with os_log.
6432 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6433 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6434 getLocationOfByte(CS.getStart()),
6435 /*IsStringLocation*/ false,
6436 getSpecifierRange(startSpecifier, specifierLen));
6437
6438 return true;
6439 }
6440
6441 // Only scalars are allowed for os_trace.
6442 if (FSType == Sema::FST_OSTrace &&
6443 (CS.getKind() == ConversionSpecifier::PArg ||
6444 CS.getKind() == ConversionSpecifier::sArg ||
6445 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6446 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6447 specifierLen);
6448 }
6449
6450 // Check for use of public/private annotation outside of os_log().
6451 if (FSType != Sema::FST_OSLog) {
6452 if (FS.isPublic().isSet()) {
6453 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6454 << "public",
6455 getLocationOfByte(FS.isPublic().getPosition()),
6456 /*IsStringLocation*/ false,
6457 getSpecifierRange(startSpecifier, specifierLen));
6458 }
6459 if (FS.isPrivate().isSet()) {
6460 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6461 << "private",
6462 getLocationOfByte(FS.isPrivate().getPosition()),
6463 /*IsStringLocation*/ false,
6464 getSpecifierRange(startSpecifier, specifierLen));
6465 }
6466 }
6467
Tom Careb49ec692010-06-17 19:00:27 +00006468 // Check for invalid use of field width
6469 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00006470 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00006471 startSpecifier, specifierLen);
6472 }
6473
6474 // Check for invalid use of precision
6475 if (!FS.hasValidPrecision()) {
6476 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6477 startSpecifier, specifierLen);
6478 }
6479
Mehdi Amini06d367c2016-10-24 20:39:34 +00006480 // Precision is mandatory for %P specifier.
6481 if (CS.getKind() == ConversionSpecifier::PArg &&
6482 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6483 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6484 getLocationOfByte(startSpecifier),
6485 /*IsStringLocation*/ false,
6486 getSpecifierRange(startSpecifier, specifierLen));
6487 }
6488
Tom Careb49ec692010-06-17 19:00:27 +00006489 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00006490 if (!FS.hasValidThousandsGroupingPrefix())
6491 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006492 if (!FS.hasValidLeadingZeros())
6493 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6494 if (!FS.hasValidPlusPrefix())
6495 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00006496 if (!FS.hasValidSpacePrefix())
6497 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006498 if (!FS.hasValidAlternativeForm())
6499 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6500 if (!FS.hasValidLeftJustified())
6501 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6502
6503 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00006504 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6505 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6506 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006507 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6508 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6509 startSpecifier, specifierLen);
6510
6511 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006512 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006513 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6514 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006515 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006516 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006517 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006518 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6519 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00006520
Jordan Rose92303592012-09-08 04:00:03 +00006521 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6522 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6523
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006524 // The remaining checks depend on the data arguments.
6525 if (HasVAListArg)
6526 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006527
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006528 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006529 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006530
Jordan Rose58bbe422012-07-19 18:10:08 +00006531 const Expr *Arg = getDataArg(argIndex);
6532 if (!Arg)
6533 return true;
6534
6535 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00006536}
6537
Jordan Roseaee34382012-09-05 22:56:26 +00006538static bool requiresParensToAddCast(const Expr *E) {
6539 // FIXME: We should have a general way to reason about operator
6540 // precedence and whether parens are actually needed here.
6541 // Take care of a few common cases where they aren't.
6542 const Expr *Inside = E->IgnoreImpCasts();
6543 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6544 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6545
6546 switch (Inside->getStmtClass()) {
6547 case Stmt::ArraySubscriptExprClass:
6548 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006549 case Stmt::CharacterLiteralClass:
6550 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006551 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006552 case Stmt::FloatingLiteralClass:
6553 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006554 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006555 case Stmt::ObjCArrayLiteralClass:
6556 case Stmt::ObjCBoolLiteralExprClass:
6557 case Stmt::ObjCBoxedExprClass:
6558 case Stmt::ObjCDictionaryLiteralClass:
6559 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006560 case Stmt::ObjCIvarRefExprClass:
6561 case Stmt::ObjCMessageExprClass:
6562 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006563 case Stmt::ObjCStringLiteralClass:
6564 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006565 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006566 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006567 case Stmt::UnaryOperatorClass:
6568 return false;
6569 default:
6570 return true;
6571 }
6572}
6573
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006574static std::pair<QualType, StringRef>
6575shouldNotPrintDirectly(const ASTContext &Context,
6576 QualType IntendedTy,
6577 const Expr *E) {
6578 // Use a 'while' to peel off layers of typedefs.
6579 QualType TyTy = IntendedTy;
6580 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6581 StringRef Name = UserTy->getDecl()->getName();
6582 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Saleem Abdulrasoola01ed932017-10-17 17:39:32 +00006583 .Case("CFIndex", Context.getNSIntegerType())
6584 .Case("NSInteger", Context.getNSIntegerType())
6585 .Case("NSUInteger", Context.getNSUIntegerType())
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006586 .Case("SInt32", Context.IntTy)
6587 .Case("UInt32", Context.UnsignedIntTy)
6588 .Default(QualType());
6589
6590 if (!CastTy.isNull())
6591 return std::make_pair(CastTy, Name);
6592
6593 TyTy = UserTy->desugar();
6594 }
6595
6596 // Strip parens if necessary.
6597 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6598 return shouldNotPrintDirectly(Context,
6599 PE->getSubExpr()->getType(),
6600 PE->getSubExpr());
6601
6602 // If this is a conditional expression, then its result type is constructed
6603 // via usual arithmetic conversions and thus there might be no necessary
6604 // typedef sugar there. Recurse to operands to check for NSInteger &
6605 // Co. usage condition.
6606 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6607 QualType TrueTy, FalseTy;
6608 StringRef TrueName, FalseName;
6609
6610 std::tie(TrueTy, TrueName) =
6611 shouldNotPrintDirectly(Context,
6612 CO->getTrueExpr()->getType(),
6613 CO->getTrueExpr());
6614 std::tie(FalseTy, FalseName) =
6615 shouldNotPrintDirectly(Context,
6616 CO->getFalseExpr()->getType(),
6617 CO->getFalseExpr());
6618
6619 if (TrueTy == FalseTy)
6620 return std::make_pair(TrueTy, TrueName);
6621 else if (TrueTy.isNull())
6622 return std::make_pair(FalseTy, FalseName);
6623 else if (FalseTy.isNull())
6624 return std::make_pair(TrueTy, TrueName);
6625 }
6626
6627 return std::make_pair(QualType(), StringRef());
6628}
6629
Richard Smith55ce3522012-06-25 20:30:08 +00006630bool
6631CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6632 const char *StartSpecifier,
6633 unsigned SpecifierLen,
6634 const Expr *E) {
6635 using namespace analyze_format_string;
6636 using namespace analyze_printf;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006637
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006638 // Now type check the data expression that matches the
6639 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006640 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00006641 if (!AT.isValid())
6642 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00006643
Jordan Rose598ec092012-12-05 18:44:40 +00006644 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00006645 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6646 ExprTy = TET->getUnderlyingExpr()->getType();
6647 }
6648
Seth Cantrellb4802962015-03-04 03:12:10 +00006649 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6650
6651 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00006652 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006653 }
Jordan Rose98709982012-06-04 22:48:57 +00006654
Jordan Rose22b74712012-09-05 22:56:19 +00006655 // Look through argument promotions for our error message's reported type.
6656 // This includes the integral and floating promotions, but excludes array
6657 // and function pointer decay; seeing that an argument intended to be a
6658 // string has type 'char [6]' is probably more confusing than 'char *'.
6659 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6660 if (ICE->getCastKind() == CK_IntegralCast ||
6661 ICE->getCastKind() == CK_FloatingCast) {
6662 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006663 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006664
6665 // Check if we didn't match because of an implicit cast from a 'char'
6666 // or 'short' to an 'int'. This is done because printf is a varargs
6667 // function.
6668 if (ICE->getType() == S.Context.IntTy ||
6669 ICE->getType() == S.Context.UnsignedIntTy) {
6670 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006671 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006672 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006673 }
Jordan Rose98709982012-06-04 22:48:57 +00006674 }
Jordan Rose598ec092012-12-05 18:44:40 +00006675 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6676 // Special case for 'a', which has type 'int' in C.
6677 // Note, however, that we do /not/ want to treat multibyte constants like
6678 // 'MooV' as characters! This form is deprecated but still exists.
6679 if (ExprTy == S.Context.IntTy)
6680 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6681 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006682 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006683
Jordan Rosebc53ed12014-05-31 04:12:14 +00006684 // Look through enums to their underlying type.
6685 bool IsEnum = false;
6686 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6687 ExprTy = EnumTy->getDecl()->getIntegerType();
6688 IsEnum = true;
6689 }
6690
Jordan Rose0e5badd2012-12-05 18:44:49 +00006691 // %C in an Objective-C context prints a unichar, not a wchar_t.
6692 // If the argument is an integer of some kind, believe the %C and suggest
6693 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006694 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006695 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006696 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6697 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6698 !ExprTy->isCharType()) {
6699 // 'unichar' is defined as a typedef of unsigned short, but we should
6700 // prefer using the typedef if it is visible.
6701 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006702
6703 // While we are here, check if the value is an IntegerLiteral that happens
6704 // to be within the valid range.
6705 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6706 const llvm::APInt &V = IL->getValue();
6707 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6708 return true;
6709 }
6710
Jordan Rose0e5badd2012-12-05 18:44:49 +00006711 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6712 Sema::LookupOrdinaryName);
6713 if (S.LookupName(Result, S.getCurScope())) {
6714 NamedDecl *ND = Result.getFoundDecl();
6715 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6716 if (TD->getUnderlyingType() == IntendedTy)
6717 IntendedTy = S.Context.getTypedefType(TD);
6718 }
6719 }
6720 }
6721
6722 // Special-case some of Darwin's platform-independence types by suggesting
6723 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006724 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006725 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006726 QualType CastTy;
6727 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6728 if (!CastTy.isNull()) {
6729 IntendedTy = CastTy;
6730 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006731 }
6732 }
6733
Jordan Rose22b74712012-09-05 22:56:19 +00006734 // We may be able to offer a FixItHint if it is a supported type.
6735 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006736 bool success =
6737 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006738
Jordan Rose22b74712012-09-05 22:56:19 +00006739 if (success) {
6740 // Get the fix string from the fixed format specifier
6741 SmallString<16> buf;
6742 llvm::raw_svector_ostream os(buf);
6743 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006744
Jordan Roseaee34382012-09-05 22:56:26 +00006745 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6746
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006747 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00006748 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6749 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6750 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6751 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00006752 // In this case, the specifier is wrong and should be changed to match
6753 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006754 EmitFormatDiagnostic(S.PDiag(diag)
6755 << AT.getRepresentativeTypeName(S.Context)
6756 << IntendedTy << IsEnum << E->getSourceRange(),
6757 E->getLocStart(),
6758 /*IsStringLocation*/ false, SpecRange,
6759 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006760 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006761 // The canonical type for formatting this value is different from the
6762 // actual type of the expression. (This occurs, for example, with Darwin's
6763 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6764 // should be printed as 'long' for 64-bit compatibility.)
6765 // Rather than emitting a normal format/argument mismatch, we want to
6766 // add a cast to the recommended type (and correct the format string
6767 // if necessary).
6768 SmallString<16> CastBuf;
6769 llvm::raw_svector_ostream CastFix(CastBuf);
6770 CastFix << "(";
6771 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6772 CastFix << ")";
6773
6774 SmallVector<FixItHint,4> Hints;
Alexander Shaposhnikov1788a9b2017-09-22 18:36:06 +00006775 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
Jordan Roseaee34382012-09-05 22:56:26 +00006776 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6777
6778 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6779 // If there's already a cast present, just replace it.
6780 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6781 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6782
6783 } else if (!requiresParensToAddCast(E)) {
6784 // If the expression has high enough precedence,
6785 // just write the C-style cast.
6786 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6787 CastFix.str()));
6788 } else {
6789 // Otherwise, add parens around the expression as well as the cast.
6790 CastFix << "(";
6791 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6792 CastFix.str()));
6793
Alp Tokerb6cc5922014-05-03 03:45:55 +00006794 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006795 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6796 }
6797
Jordan Rose0e5badd2012-12-05 18:44:49 +00006798 if (ShouldNotPrintDirectly) {
6799 // The expression has a type that should not be printed directly.
6800 // We extract the name from the typedef because we don't want to show
6801 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006802 StringRef Name;
6803 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6804 Name = TypedefTy->getDecl()->getName();
6805 else
6806 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006807 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006808 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006809 << E->getSourceRange(),
6810 E->getLocStart(), /*IsStringLocation=*/false,
6811 SpecRange, Hints);
6812 } else {
6813 // In this case, the expression could be printed using a different
6814 // specifier, but we've decided that the specifier is probably correct
6815 // and we should cast instead. Just use the normal warning message.
6816 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006817 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6818 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006819 << E->getSourceRange(),
6820 E->getLocStart(), /*IsStringLocation*/false,
6821 SpecRange, Hints);
6822 }
Jordan Roseaee34382012-09-05 22:56:26 +00006823 }
Jordan Rose22b74712012-09-05 22:56:19 +00006824 } else {
6825 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6826 SpecifierLen);
6827 // Since the warning for passing non-POD types to variadic functions
6828 // was deferred until now, we emit a warning for non-POD
6829 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006830 switch (S.isValidVarArgType(ExprTy)) {
6831 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006832 case Sema::VAK_ValidInCXX11: {
6833 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6834 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6835 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6836 }
Richard Smithd7293d72013-08-05 18:49:43 +00006837
Seth Cantrellb4802962015-03-04 03:12:10 +00006838 EmitFormatDiagnostic(
6839 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6840 << IsEnum << CSR << E->getSourceRange(),
6841 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6842 break;
6843 }
Richard Smithd7293d72013-08-05 18:49:43 +00006844 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006845 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006846 EmitFormatDiagnostic(
6847 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006848 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006849 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006850 << CallType
6851 << AT.getRepresentativeTypeName(S.Context)
6852 << CSR
6853 << E->getSourceRange(),
6854 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006855 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006856 break;
6857
6858 case Sema::VAK_Invalid:
6859 if (ExprTy->isObjCObjectType())
6860 EmitFormatDiagnostic(
6861 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6862 << S.getLangOpts().CPlusPlus11
6863 << ExprTy
6864 << CallType
6865 << AT.getRepresentativeTypeName(S.Context)
6866 << CSR
6867 << E->getSourceRange(),
6868 E->getLocStart(), /*IsStringLocation*/false, CSR);
6869 else
6870 // FIXME: If this is an initializer list, suggest removing the braces
6871 // or inserting a cast to the target type.
6872 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6873 << isa<InitListExpr>(E) << ExprTy << CallType
6874 << AT.getRepresentativeTypeName(S.Context)
6875 << E->getSourceRange();
6876 break;
6877 }
6878
6879 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6880 "format string specifier index out of range");
6881 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006882 }
6883
Ted Kremenekab278de2010-01-28 23:39:18 +00006884 return true;
6885}
6886
Ted Kremenek02087932010-07-16 02:11:22 +00006887//===--- CHECK: Scanf format string checking ------------------------------===//
6888
6889namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006890
Ted Kremenek02087932010-07-16 02:11:22 +00006891class CheckScanfHandler : public CheckFormatHandler {
6892public:
Stephen Hines648c3692016-09-16 01:07:04 +00006893 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006894 const Expr *origFormatExpr, Sema::FormatStringType type,
6895 unsigned firstDataArg, unsigned numDataArgs,
6896 const char *beg, bool hasVAListArg,
6897 ArrayRef<const Expr *> Args, unsigned formatIdx,
6898 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006899 llvm::SmallBitVector &CheckedVarArgs,
6900 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006901 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6902 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6903 inFunctionCall, CallType, CheckedVarArgs,
6904 UncoveredArg) {}
6905
Ted Kremenek02087932010-07-16 02:11:22 +00006906 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6907 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006908 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006909
6910 bool HandleInvalidScanfConversionSpecifier(
6911 const analyze_scanf::ScanfSpecifier &FS,
6912 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006913 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006914
Craig Toppere14c0f82014-03-12 04:55:44 +00006915 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006916};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006917
6918} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006919
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006920void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6921 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006922 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6923 getLocationOfByte(end), /*IsStringLocation*/true,
6924 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006925}
6926
Ted Kremenekce815422010-07-19 21:25:57 +00006927bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6928 const analyze_scanf::ScanfSpecifier &FS,
6929 const char *startSpecifier,
6930 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006931 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006932 FS.getConversionSpecifier();
6933
6934 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6935 getLocationOfByte(CS.getStart()),
6936 startSpecifier, specifierLen,
6937 CS.getStart(), CS.getLength());
6938}
6939
Ted Kremenek02087932010-07-16 02:11:22 +00006940bool CheckScanfHandler::HandleScanfSpecifier(
6941 const analyze_scanf::ScanfSpecifier &FS,
6942 const char *startSpecifier,
6943 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006944 using namespace analyze_scanf;
6945 using namespace analyze_format_string;
6946
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006947 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006948
Ted Kremenek6cd69422010-07-19 22:01:06 +00006949 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6950 // be used to decide if we are using positional arguments consistently.
6951 if (FS.consumesDataArgument()) {
6952 if (atFirstArg) {
6953 atFirstArg = false;
6954 usesPositionalArgs = FS.usesPositionalArg();
6955 }
6956 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006957 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6958 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006959 return false;
6960 }
Ted Kremenek02087932010-07-16 02:11:22 +00006961 }
6962
6963 // Check if the field with is non-zero.
6964 const OptionalAmount &Amt = FS.getFieldWidth();
6965 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6966 if (Amt.getConstantAmount() == 0) {
6967 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6968 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006969 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6970 getLocationOfByte(Amt.getStart()),
6971 /*IsStringLocation*/true, R,
6972 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006973 }
6974 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006975
Ted Kremenek02087932010-07-16 02:11:22 +00006976 if (!FS.consumesDataArgument()) {
6977 // FIXME: Technically specifying a precision or field width here
6978 // makes no sense. Worth issuing a warning at some point.
6979 return true;
6980 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006981
Ted Kremenek02087932010-07-16 02:11:22 +00006982 // Consume the argument.
6983 unsigned argIndex = FS.getArgIndex();
6984 if (argIndex < NumDataArgs) {
6985 // The check to see if the argIndex is valid will come later.
6986 // We set the bit here because we may exit early from this
6987 // function if we encounter some other error.
6988 CoveredArgs.set(argIndex);
6989 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006990
Ted Kremenek4407ea42010-07-20 20:04:47 +00006991 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006992 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006993 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6994 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006995 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006996 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006997 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006998 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6999 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007000
Jordan Rose92303592012-09-08 04:00:03 +00007001 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7002 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7003
Ted Kremenek02087932010-07-16 02:11:22 +00007004 // The remaining checks depend on the data arguments.
7005 if (HasVAListArg)
7006 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00007007
Ted Kremenek6adb7e32010-07-26 19:45:42 +00007008 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00007009 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00007010
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007011 // Check that the argument type matches the format specifier.
7012 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00007013 if (!Ex)
7014 return true;
7015
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00007016 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00007017
7018 if (!AT.isValid()) {
7019 return true;
7020 }
7021
Seth Cantrellb4802962015-03-04 03:12:10 +00007022 analyze_format_string::ArgType::MatchKind match =
7023 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00007024 if (match == analyze_format_string::ArgType::Match) {
7025 return true;
7026 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007027
Seth Cantrell79340072015-03-04 05:58:08 +00007028 ScanfSpecifier fixedFS = FS;
7029 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
7030 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007031
Seth Cantrell79340072015-03-04 05:58:08 +00007032 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
7033 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
7034 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
7035 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007036
Seth Cantrell79340072015-03-04 05:58:08 +00007037 if (success) {
7038 // Get the fix string from the fixed format specifier.
7039 SmallString<128> buf;
7040 llvm::raw_svector_ostream os(buf);
7041 fixedFS.toString(os);
7042
7043 EmitFormatDiagnostic(
7044 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
7045 << Ex->getType() << false << Ex->getSourceRange(),
7046 Ex->getLocStart(),
7047 /*IsStringLocation*/ false,
7048 getSpecifierRange(startSpecifier, specifierLen),
7049 FixItHint::CreateReplacement(
7050 getSpecifierRange(startSpecifier, specifierLen), os.str()));
7051 } else {
7052 EmitFormatDiagnostic(S.PDiag(diag)
7053 << AT.getRepresentativeTypeName(S.Context)
7054 << Ex->getType() << false << Ex->getSourceRange(),
7055 Ex->getLocStart(),
7056 /*IsStringLocation*/ false,
7057 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007058 }
7059
Ted Kremenek02087932010-07-16 02:11:22 +00007060 return true;
7061}
7062
Stephen Hines648c3692016-09-16 01:07:04 +00007063static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007064 const Expr *OrigFormatExpr,
7065 ArrayRef<const Expr *> Args,
7066 bool HasVAListArg, unsigned format_idx,
7067 unsigned firstDataArg,
7068 Sema::FormatStringType Type,
7069 bool inFunctionCall,
7070 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007071 llvm::SmallBitVector &CheckedVarArgs,
7072 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00007073 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00007074 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007075 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007076 S, inFunctionCall, Args[format_idx],
7077 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00007078 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00007079 return;
7080 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007081
Ted Kremenekab278de2010-01-28 23:39:18 +00007082 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007083 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00007084 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007085 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007086 const ConstantArrayType *T =
7087 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007088 assert(T && "String literal not of constant array type!");
7089 size_t TypeSize = T->getSize().getZExtValue();
7090 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00007091 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007092
7093 // Emit a warning if the string literal is truncated and does not contain an
7094 // embedded null character.
7095 if (TypeSize <= StrRef.size() &&
7096 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
7097 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007098 S, inFunctionCall, Args[format_idx],
7099 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007100 FExpr->getLocStart(),
7101 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
7102 return;
7103 }
7104
Ted Kremenekab278de2010-01-28 23:39:18 +00007105 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00007106 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007107 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007108 S, inFunctionCall, Args[format_idx],
7109 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00007110 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00007111 return;
7112 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007113
7114 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00007115 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
7116 Type == Sema::FST_OSTrace) {
7117 CheckPrintfHandler H(
7118 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
7119 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
7120 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
7121 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007122
Hans Wennborg23926bd2011-12-15 10:25:47 +00007123 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007124 S.getLangOpts(),
7125 S.Context.getTargetInfo(),
7126 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00007127 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007128 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00007129 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
7130 numDataArgs, Str, HasVAListArg, Args, format_idx,
7131 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007132
Hans Wennborg23926bd2011-12-15 10:25:47 +00007133 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007134 S.getLangOpts(),
7135 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00007136 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00007137 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00007138}
7139
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00007140bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
7141 // Str - The format string. NOTE: this is NOT null-terminated!
7142 StringRef StrRef = FExpr->getString();
7143 const char *Str = StrRef.data();
7144 // Account for cases where the string literal is truncated in a declaration.
7145 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
7146 assert(T && "String literal not of constant array type!");
7147 size_t TypeSize = T->getSize().getZExtValue();
7148 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
7149 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
7150 getLangOpts(),
7151 Context.getTargetInfo());
7152}
7153
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007154//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
7155
7156// Returns the related absolute value function that is larger, of 0 if one
7157// does not exist.
7158static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
7159 switch (AbsFunction) {
7160 default:
7161 return 0;
7162
7163 case Builtin::BI__builtin_abs:
7164 return Builtin::BI__builtin_labs;
7165 case Builtin::BI__builtin_labs:
7166 return Builtin::BI__builtin_llabs;
7167 case Builtin::BI__builtin_llabs:
7168 return 0;
7169
7170 case Builtin::BI__builtin_fabsf:
7171 return Builtin::BI__builtin_fabs;
7172 case Builtin::BI__builtin_fabs:
7173 return Builtin::BI__builtin_fabsl;
7174 case Builtin::BI__builtin_fabsl:
7175 return 0;
7176
7177 case Builtin::BI__builtin_cabsf:
7178 return Builtin::BI__builtin_cabs;
7179 case Builtin::BI__builtin_cabs:
7180 return Builtin::BI__builtin_cabsl;
7181 case Builtin::BI__builtin_cabsl:
7182 return 0;
7183
7184 case Builtin::BIabs:
7185 return Builtin::BIlabs;
7186 case Builtin::BIlabs:
7187 return Builtin::BIllabs;
7188 case Builtin::BIllabs:
7189 return 0;
7190
7191 case Builtin::BIfabsf:
7192 return Builtin::BIfabs;
7193 case Builtin::BIfabs:
7194 return Builtin::BIfabsl;
7195 case Builtin::BIfabsl:
7196 return 0;
7197
7198 case Builtin::BIcabsf:
7199 return Builtin::BIcabs;
7200 case Builtin::BIcabs:
7201 return Builtin::BIcabsl;
7202 case Builtin::BIcabsl:
7203 return 0;
7204 }
7205}
7206
7207// Returns the argument type of the absolute value function.
7208static QualType getAbsoluteValueArgumentType(ASTContext &Context,
7209 unsigned AbsType) {
7210 if (AbsType == 0)
7211 return QualType();
7212
7213 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
7214 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
7215 if (Error != ASTContext::GE_None)
7216 return QualType();
7217
7218 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
7219 if (!FT)
7220 return QualType();
7221
7222 if (FT->getNumParams() != 1)
7223 return QualType();
7224
7225 return FT->getParamType(0);
7226}
7227
7228// Returns the best absolute value function, or zero, based on type and
7229// current absolute value function.
7230static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
7231 unsigned AbsFunctionKind) {
7232 unsigned BestKind = 0;
7233 uint64_t ArgSize = Context.getTypeSize(ArgType);
7234 for (unsigned Kind = AbsFunctionKind; Kind != 0;
7235 Kind = getLargerAbsoluteValueFunction(Kind)) {
7236 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
7237 if (Context.getTypeSize(ParamType) >= ArgSize) {
7238 if (BestKind == 0)
7239 BestKind = Kind;
7240 else if (Context.hasSameType(ParamType, ArgType)) {
7241 BestKind = Kind;
7242 break;
7243 }
7244 }
7245 }
7246 return BestKind;
7247}
7248
7249enum AbsoluteValueKind {
7250 AVK_Integer,
7251 AVK_Floating,
7252 AVK_Complex
7253};
7254
7255static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
7256 if (T->isIntegralOrEnumerationType())
7257 return AVK_Integer;
7258 if (T->isRealFloatingType())
7259 return AVK_Floating;
7260 if (T->isAnyComplexType())
7261 return AVK_Complex;
7262
7263 llvm_unreachable("Type not integer, floating, or complex");
7264}
7265
7266// Changes the absolute value function to a different type. Preserves whether
7267// the function is a builtin.
7268static unsigned changeAbsFunction(unsigned AbsKind,
7269 AbsoluteValueKind ValueKind) {
7270 switch (ValueKind) {
7271 case AVK_Integer:
7272 switch (AbsKind) {
7273 default:
7274 return 0;
7275 case Builtin::BI__builtin_fabsf:
7276 case Builtin::BI__builtin_fabs:
7277 case Builtin::BI__builtin_fabsl:
7278 case Builtin::BI__builtin_cabsf:
7279 case Builtin::BI__builtin_cabs:
7280 case Builtin::BI__builtin_cabsl:
7281 return Builtin::BI__builtin_abs;
7282 case Builtin::BIfabsf:
7283 case Builtin::BIfabs:
7284 case Builtin::BIfabsl:
7285 case Builtin::BIcabsf:
7286 case Builtin::BIcabs:
7287 case Builtin::BIcabsl:
7288 return Builtin::BIabs;
7289 }
7290 case AVK_Floating:
7291 switch (AbsKind) {
7292 default:
7293 return 0;
7294 case Builtin::BI__builtin_abs:
7295 case Builtin::BI__builtin_labs:
7296 case Builtin::BI__builtin_llabs:
7297 case Builtin::BI__builtin_cabsf:
7298 case Builtin::BI__builtin_cabs:
7299 case Builtin::BI__builtin_cabsl:
7300 return Builtin::BI__builtin_fabsf;
7301 case Builtin::BIabs:
7302 case Builtin::BIlabs:
7303 case Builtin::BIllabs:
7304 case Builtin::BIcabsf:
7305 case Builtin::BIcabs:
7306 case Builtin::BIcabsl:
7307 return Builtin::BIfabsf;
7308 }
7309 case AVK_Complex:
7310 switch (AbsKind) {
7311 default:
7312 return 0;
7313 case Builtin::BI__builtin_abs:
7314 case Builtin::BI__builtin_labs:
7315 case Builtin::BI__builtin_llabs:
7316 case Builtin::BI__builtin_fabsf:
7317 case Builtin::BI__builtin_fabs:
7318 case Builtin::BI__builtin_fabsl:
7319 return Builtin::BI__builtin_cabsf;
7320 case Builtin::BIabs:
7321 case Builtin::BIlabs:
7322 case Builtin::BIllabs:
7323 case Builtin::BIfabsf:
7324 case Builtin::BIfabs:
7325 case Builtin::BIfabsl:
7326 return Builtin::BIcabsf;
7327 }
7328 }
7329 llvm_unreachable("Unable to convert function");
7330}
7331
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00007332static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007333 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
7334 if (!FnInfo)
7335 return 0;
7336
7337 switch (FDecl->getBuiltinID()) {
7338 default:
7339 return 0;
7340 case Builtin::BI__builtin_abs:
7341 case Builtin::BI__builtin_fabs:
7342 case Builtin::BI__builtin_fabsf:
7343 case Builtin::BI__builtin_fabsl:
7344 case Builtin::BI__builtin_labs:
7345 case Builtin::BI__builtin_llabs:
7346 case Builtin::BI__builtin_cabs:
7347 case Builtin::BI__builtin_cabsf:
7348 case Builtin::BI__builtin_cabsl:
7349 case Builtin::BIabs:
7350 case Builtin::BIlabs:
7351 case Builtin::BIllabs:
7352 case Builtin::BIfabs:
7353 case Builtin::BIfabsf:
7354 case Builtin::BIfabsl:
7355 case Builtin::BIcabs:
7356 case Builtin::BIcabsf:
7357 case Builtin::BIcabsl:
7358 return FDecl->getBuiltinID();
7359 }
7360 llvm_unreachable("Unknown Builtin type");
7361}
7362
7363// If the replacement is valid, emit a note with replacement function.
7364// Additionally, suggest including the proper header if not already included.
7365static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00007366 unsigned AbsKind, QualType ArgType) {
7367 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007368 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00007369 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007370 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
7371 FunctionName = "std::abs";
7372 if (ArgType->isIntegralOrEnumerationType()) {
7373 HeaderName = "cstdlib";
7374 } else if (ArgType->isRealFloatingType()) {
7375 HeaderName = "cmath";
7376 } else {
7377 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007378 }
Richard Trieubeffb832014-04-15 23:47:53 +00007379
7380 // Lookup all std::abs
7381 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00007382 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00007383 R.suppressDiagnostics();
7384 S.LookupQualifiedName(R, Std);
7385
7386 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007387 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007388 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
7389 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
7390 } else {
7391 FDecl = dyn_cast<FunctionDecl>(I);
7392 }
7393 if (!FDecl)
7394 continue;
7395
7396 // Found std::abs(), check that they are the right ones.
7397 if (FDecl->getNumParams() != 1)
7398 continue;
7399
7400 // Check that the parameter type can handle the argument.
7401 QualType ParamType = FDecl->getParamDecl(0)->getType();
7402 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
7403 S.Context.getTypeSize(ArgType) <=
7404 S.Context.getTypeSize(ParamType)) {
7405 // Found a function, don't need the header hint.
7406 EmitHeaderHint = false;
7407 break;
7408 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007409 }
Richard Trieubeffb832014-04-15 23:47:53 +00007410 }
7411 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00007412 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00007413 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7414
7415 if (HeaderName) {
7416 DeclarationName DN(&S.Context.Idents.get(FunctionName));
7417 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7418 R.suppressDiagnostics();
7419 S.LookupName(R, S.getCurScope());
7420
7421 if (R.isSingleResult()) {
7422 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7423 if (FD && FD->getBuiltinID() == AbsKind) {
7424 EmitHeaderHint = false;
7425 } else {
7426 return;
7427 }
7428 } else if (!R.empty()) {
7429 return;
7430 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007431 }
7432 }
7433
7434 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00007435 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007436
Richard Trieubeffb832014-04-15 23:47:53 +00007437 if (!HeaderName)
7438 return;
7439
7440 if (!EmitHeaderHint)
7441 return;
7442
Alp Toker5d96e0a2014-07-11 20:53:51 +00007443 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7444 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00007445}
7446
Richard Trieua7f30b12016-12-06 01:42:28 +00007447template <std::size_t StrLen>
7448static bool IsStdFunction(const FunctionDecl *FDecl,
7449 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00007450 if (!FDecl)
7451 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007452 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00007453 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007454 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00007455 return false;
7456
7457 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007458}
7459
7460// Warn when using the wrong abs() function.
7461void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00007462 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007463 if (Call->getNumArgs() != 1)
7464 return;
7465
7466 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00007467 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00007468 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007469 return;
7470
7471 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7472 QualType ParamType = Call->getArg(0)->getType();
7473
Alp Toker5d96e0a2014-07-11 20:53:51 +00007474 // Unsigned types cannot be negative. Suggest removing the absolute value
7475 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007476 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00007477 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00007478 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007479 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7480 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00007481 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007482 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7483 return;
7484 }
7485
David Majnemer7f77eb92015-11-15 03:04:34 +00007486 // Taking the absolute value of a pointer is very suspicious, they probably
7487 // wanted to index into an array, dereference a pointer, call a function, etc.
7488 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7489 unsigned DiagType = 0;
7490 if (ArgType->isFunctionType())
7491 DiagType = 1;
7492 else if (ArgType->isArrayType())
7493 DiagType = 2;
7494
7495 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7496 return;
7497 }
7498
Richard Trieubeffb832014-04-15 23:47:53 +00007499 // std::abs has overloads which prevent most of the absolute value problems
7500 // from occurring.
7501 if (IsStdAbs)
7502 return;
7503
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007504 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7505 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7506
7507 // The argument and parameter are the same kind. Check if they are the right
7508 // size.
7509 if (ArgValueKind == ParamValueKind) {
7510 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7511 return;
7512
7513 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7514 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7515 << FDecl << ArgType << ParamType;
7516
7517 if (NewAbsKind == 0)
7518 return;
7519
7520 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007521 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007522 return;
7523 }
7524
7525 // ArgValueKind != ParamValueKind
7526 // The wrong type of absolute value function was used. Attempt to find the
7527 // proper one.
7528 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7529 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7530 if (NewAbsKind == 0)
7531 return;
7532
7533 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7534 << FDecl << ParamValueKind << ArgValueKind;
7535
7536 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007537 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007538}
7539
Richard Trieu67c00712016-12-05 23:41:46 +00007540//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00007541void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7542 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00007543 if (!Call || !FDecl) return;
7544
7545 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00007546 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007547 if (Call->getExprLoc().isMacroID()) return;
7548
7549 // Only care about the one template argument, two function parameter std::max
7550 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00007551 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007552 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7553 if (!ArgList) return;
7554 if (ArgList->size() != 1) return;
7555
7556 // Check that template type argument is unsigned integer.
7557 const auto& TA = ArgList->get(0);
7558 if (TA.getKind() != TemplateArgument::Type) return;
7559 QualType ArgType = TA.getAsType();
7560 if (!ArgType->isUnsignedIntegerType()) return;
7561
7562 // See if either argument is a literal zero.
7563 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7564 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7565 if (!MTE) return false;
7566 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7567 if (!Num) return false;
7568 if (Num->getValue() != 0) return false;
7569 return true;
7570 };
7571
7572 const Expr *FirstArg = Call->getArg(0);
7573 const Expr *SecondArg = Call->getArg(1);
7574 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7575 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7576
7577 // Only warn when exactly one argument is zero.
7578 if (IsFirstArgZero == IsSecondArgZero) return;
7579
7580 SourceRange FirstRange = FirstArg->getSourceRange();
7581 SourceRange SecondRange = SecondArg->getSourceRange();
7582
7583 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7584
7585 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7586 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7587
7588 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7589 SourceRange RemovalRange;
7590 if (IsFirstArgZero) {
7591 RemovalRange = SourceRange(FirstRange.getBegin(),
7592 SecondRange.getBegin().getLocWithOffset(-1));
7593 } else {
7594 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7595 SecondRange.getEnd());
7596 }
7597
7598 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7599 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7600 << FixItHint::CreateRemoval(RemovalRange);
7601}
7602
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007603//===--- CHECK: Standard memory functions ---------------------------------===//
7604
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007605/// Takes the expression passed to the size_t parameter of functions
Nico Weber0e6daef2013-12-26 23:38:39 +00007606/// such as memcmp, strncat, etc and warns if it's a comparison.
7607///
7608/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7609static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7610 IdentifierInfo *FnName,
7611 SourceLocation FnLoc,
7612 SourceLocation RParenLoc) {
7613 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7614 if (!Size)
7615 return false;
7616
Richard Smithc70f1d62017-12-14 15:16:18 +00007617 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
7618 if (!Size->isComparisonOp() && !Size->isLogicalOp())
Nico Weber0e6daef2013-12-26 23:38:39 +00007619 return false;
7620
Nico Weber0e6daef2013-12-26 23:38:39 +00007621 SourceRange SizeRange = Size->getSourceRange();
7622 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7623 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00007624 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007625 << FnName << FixItHint::CreateInsertion(
7626 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00007627 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00007628 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00007629 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00007630 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7631 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00007632
7633 return true;
7634}
7635
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007636/// Determine whether the given type is or contains a dynamic class type
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007637/// (e.g., whether it has a vtable).
7638static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7639 bool &IsContained) {
7640 // Look through array types while ignoring qualifiers.
7641 const Type *Ty = T->getBaseElementTypeUnsafe();
7642 IsContained = false;
7643
7644 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7645 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00007646 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007647 return nullptr;
7648
7649 if (RD->isDynamicClass())
7650 return RD;
7651
7652 // Check all the fields. If any bases were dynamic, the class is dynamic.
7653 // It's impossible for a class to transitively contain itself by value, so
7654 // infinite recursion is impossible.
7655 for (auto *FD : RD->fields()) {
7656 bool SubContained;
7657 if (const CXXRecordDecl *ContainedRD =
7658 getContainedDynamicClass(FD->getType(), SubContained)) {
7659 IsContained = true;
7660 return ContainedRD;
7661 }
7662 }
7663
7664 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007665}
7666
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007667/// If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007668/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007669static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007670 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007671 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007672 if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007673 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007674
Craig Topperc3ec1492014-05-26 06:22:03 +00007675 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007676}
7677
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007678/// If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007679static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007680 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7681 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007682 if (SizeOf->getKind() == UETT_SizeOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007683 return SizeOf->getTypeOfArgument();
7684
7685 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007686}
7687
Akira Hatanaka2be04412018-04-17 19:13:41 +00007688namespace {
7689
7690struct SearchNonTrivialToInitializeField
7691 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
7692 using Super =
7693 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
7694
7695 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
7696
7697 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
7698 SourceLocation SL) {
7699 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7700 asDerived().visitArray(PDIK, AT, SL);
7701 return;
7702 }
7703
7704 Super::visitWithKind(PDIK, FT, SL);
7705 }
7706
7707 void visitARCStrong(QualType FT, SourceLocation SL) {
7708 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7709 }
7710 void visitARCWeak(QualType FT, SourceLocation SL) {
7711 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7712 }
7713 void visitStruct(QualType FT, SourceLocation SL) {
7714 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7715 visit(FD->getType(), FD->getLocation());
7716 }
7717 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
7718 const ArrayType *AT, SourceLocation SL) {
7719 visit(getContext().getBaseElementType(AT), SL);
7720 }
7721 void visitTrivial(QualType FT, SourceLocation SL) {}
7722
7723 static void diag(QualType RT, const Expr *E, Sema &S) {
7724 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
7725 }
7726
7727 ASTContext &getContext() { return S.getASTContext(); }
7728
7729 const Expr *E;
7730 Sema &S;
7731};
7732
7733struct SearchNonTrivialToCopyField
7734 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
7735 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
7736
7737 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
7738
7739 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
7740 SourceLocation SL) {
7741 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7742 asDerived().visitArray(PCK, AT, SL);
7743 return;
7744 }
7745
7746 Super::visitWithKind(PCK, FT, SL);
7747 }
7748
7749 void visitARCStrong(QualType FT, SourceLocation SL) {
7750 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7751 }
7752 void visitARCWeak(QualType FT, SourceLocation SL) {
7753 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7754 }
7755 void visitStruct(QualType FT, SourceLocation SL) {
7756 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7757 visit(FD->getType(), FD->getLocation());
7758 }
7759 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
7760 SourceLocation SL) {
7761 visit(getContext().getBaseElementType(AT), SL);
7762 }
7763 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
7764 SourceLocation SL) {}
7765 void visitTrivial(QualType FT, SourceLocation SL) {}
7766 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
7767
7768 static void diag(QualType RT, const Expr *E, Sema &S) {
7769 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
7770 }
7771
7772 ASTContext &getContext() { return S.getASTContext(); }
7773
7774 const Expr *E;
7775 Sema &S;
7776};
7777
7778}
7779
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007780/// Check for dangerous or invalid arguments to memset().
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007781///
Chandler Carruthac687262011-06-03 06:23:57 +00007782/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007783/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7784/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007785///
7786/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007787void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007788 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007789 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007790 assert(BId != 0);
7791
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007792 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007793 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007794 unsigned ExpectedNumArgs =
7795 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007796 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007797 return;
7798
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007799 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007800 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007801 unsigned LenArg =
7802 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007803 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007804
Nico Weber0e6daef2013-12-26 23:38:39 +00007805 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7806 Call->getLocStart(), Call->getRParenLoc()))
7807 return;
7808
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007809 // We have special checking when the length is a sizeof expression.
7810 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7811 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7812 llvm::FoldingSetNodeID SizeOfArgID;
7813
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007814 // Although widely used, 'bzero' is not a standard function. Be more strict
7815 // with the argument types before allowing diagnostics and only allow the
7816 // form bzero(ptr, sizeof(...)).
7817 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7818 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7819 return;
7820
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007821 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7822 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007823 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007824
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007825 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007826 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007827 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007828 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007829
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007830 // Never warn about void type pointers. This can be used to suppress
7831 // false positives.
7832 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007833 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007834
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007835 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7836 // actually comparing the expressions for equality. Because computing the
7837 // expression IDs can be expensive, we only do this if the diagnostic is
7838 // enabled.
7839 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007840 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7841 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007842 // We only compute IDs for expressions if the warning is enabled, and
7843 // cache the sizeof arg's ID.
7844 if (SizeOfArgID == llvm::FoldingSetNodeID())
7845 SizeOfArg->Profile(SizeOfArgID, Context, true);
7846 llvm::FoldingSetNodeID DestID;
7847 Dest->Profile(DestID, Context, true);
7848 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007849 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7850 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007851 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007852 StringRef ReadableName = FnName->getName();
7853
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007854 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007855 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007856 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007857 if (!PointeeTy->isIncompleteType() &&
7858 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007859 ActionIdx = 2; // If the pointee's size is sizeof(char),
7860 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007861
7862 // If the function is defined as a builtin macro, do not show macro
7863 // expansion.
7864 SourceLocation SL = SizeOfArg->getExprLoc();
7865 SourceRange DSR = Dest->getSourceRange();
7866 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007867 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007868
7869 if (SM.isMacroArgExpansion(SL)) {
7870 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7871 SL = SM.getSpellingLoc(SL);
7872 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7873 SM.getSpellingLoc(DSR.getEnd()));
7874 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7875 SM.getSpellingLoc(SSR.getEnd()));
7876 }
7877
Anna Zaksd08d9152012-05-30 23:14:52 +00007878 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007879 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007880 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007881 << PointeeTy
7882 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007883 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007884 << SSR);
7885 DiagRuntimeBehavior(SL, SizeOfArg,
7886 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7887 << ActionIdx
7888 << SSR);
7889
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007890 break;
7891 }
7892 }
7893
7894 // Also check for cases where the sizeof argument is the exact same
7895 // type as the memory argument, and where it points to a user-defined
7896 // record type.
7897 if (SizeOfArgTy != QualType()) {
7898 if (PointeeTy->isRecordType() &&
7899 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7900 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7901 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7902 << FnName << SizeOfArgTy << ArgIdx
7903 << PointeeTy << Dest->getSourceRange()
7904 << LenExpr->getSourceRange());
7905 break;
7906 }
Nico Weberc5e73862011-06-14 16:14:58 +00007907 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00007908 } else if (DestTy->isArrayType()) {
7909 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00007910 }
Nico Weberc5e73862011-06-14 16:14:58 +00007911
Nico Weberc44b35e2015-03-21 17:37:46 +00007912 if (PointeeTy == QualType())
7913 continue;
Anna Zaks22122702012-01-17 00:37:07 +00007914
Nico Weberc44b35e2015-03-21 17:37:46 +00007915 // Always complain about dynamic classes.
7916 bool IsContained;
7917 if (const CXXRecordDecl *ContainedRD =
7918 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00007919
Nico Weberc44b35e2015-03-21 17:37:46 +00007920 unsigned OperationType = 0;
7921 // "overwritten" if we're warning about the destination for any call
7922 // but memcmp; otherwise a verb appropriate to the call.
7923 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7924 if (BId == Builtin::BImemcpy)
7925 OperationType = 1;
7926 else if(BId == Builtin::BImemmove)
7927 OperationType = 2;
7928 else if (BId == Builtin::BImemcmp)
7929 OperationType = 3;
7930 }
7931
John McCall31168b02011-06-15 23:02:42 +00007932 DiagRuntimeBehavior(
7933 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007934 PDiag(diag::warn_dyn_class_memaccess)
7935 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7936 << FnName << IsContained << ContainedRD << OperationType
7937 << Call->getCallee()->getSourceRange());
7938 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7939 BId != Builtin::BImemset)
7940 DiagRuntimeBehavior(
7941 Dest->getExprLoc(), Dest,
7942 PDiag(diag::warn_arc_object_memaccess)
7943 << ArgIdx << FnName << PointeeTy
7944 << Call->getCallee()->getSourceRange());
Akira Hatanaka2be04412018-04-17 19:13:41 +00007945 else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
7946 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
7947 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
7948 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
7949 PDiag(diag::warn_cstruct_memaccess)
7950 << ArgIdx << FnName << PointeeTy << 0);
7951 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
7952 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
7953 RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
7954 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
7955 PDiag(diag::warn_cstruct_memaccess)
7956 << ArgIdx << FnName << PointeeTy << 1);
7957 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
7958 } else {
7959 continue;
7960 }
7961 } else
Nico Weberc44b35e2015-03-21 17:37:46 +00007962 continue;
7963
7964 DiagRuntimeBehavior(
7965 Dest->getExprLoc(), Dest,
7966 PDiag(diag::note_bad_memaccess_silence)
7967 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7968 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007969 }
7970}
7971
Ted Kremenek6865f772011-08-18 20:55:45 +00007972// A little helper routine: ignore addition and subtraction of integer literals.
7973// This intentionally does not ignore all integer constant expressions because
7974// we don't want to remove sizeof().
7975static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7976 Ex = Ex->IgnoreParenCasts();
7977
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007978 while (true) {
Ted Kremenek6865f772011-08-18 20:55:45 +00007979 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7980 if (!BO || !BO->isAdditiveOp())
7981 break;
7982
7983 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7984 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7985
7986 if (isa<IntegerLiteral>(RHS))
7987 Ex = LHS;
7988 else if (isa<IntegerLiteral>(LHS))
7989 Ex = RHS;
7990 else
7991 break;
7992 }
7993
7994 return Ex;
7995}
7996
Anna Zaks13b08572012-08-08 21:42:23 +00007997static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7998 ASTContext &Context) {
7999 // Only handle constant-sized or VLAs, but not flexible members.
8000 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
8001 // Only issue the FIXIT for arrays of size > 1.
8002 if (CAT->getSize().getSExtValue() <= 1)
8003 return false;
8004 } else if (!Ty->isVariableArrayType()) {
8005 return false;
8006 }
8007 return true;
8008}
8009
Ted Kremenek6865f772011-08-18 20:55:45 +00008010// Warn if the user has made the 'size' argument to strlcpy or strlcat
8011// be the size of the source, instead of the destination.
8012void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
8013 IdentifierInfo *FnName) {
8014
8015 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00008016 unsigned NumArgs = Call->getNumArgs();
8017 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00008018 return;
8019
8020 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
8021 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00008022 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00008023
8024 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
8025 Call->getLocStart(), Call->getRParenLoc()))
8026 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00008027
8028 // Look for 'strlcpy(dst, x, sizeof(x))'
8029 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
8030 CompareWithSrc = Ex;
8031 else {
8032 // Look for 'strlcpy(dst, x, strlen(x))'
8033 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00008034 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
8035 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00008036 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
8037 }
8038 }
8039
8040 if (!CompareWithSrc)
8041 return;
8042
8043 // Determine if the argument to sizeof/strlen is equal to the source
8044 // argument. In principle there's all kinds of things you could do
8045 // here, for instance creating an == expression and evaluating it with
8046 // EvaluateAsBooleanCondition, but this uses a more direct technique:
8047 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
8048 if (!SrcArgDRE)
8049 return;
8050
8051 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
8052 if (!CompareWithSrcDRE ||
8053 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
8054 return;
8055
8056 const Expr *OriginalSizeArg = Call->getArg(2);
8057 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
8058 << OriginalSizeArg->getSourceRange() << FnName;
8059
8060 // Output a FIXIT hint if the destination is an array (rather than a
8061 // pointer to an array). This could be enhanced to handle some
8062 // pointers if we know the actual size, like if DstArg is 'array+2'
8063 // we could say 'sizeof(array)-2'.
8064 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00008065 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00008066 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00008067
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008068 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00008069 llvm::raw_svector_ostream OS(sizeString);
8070 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008071 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00008072 OS << ")";
8073
8074 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
8075 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
8076 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00008077}
8078
Anna Zaks314cd092012-02-01 19:08:57 +00008079/// Check if two expressions refer to the same declaration.
8080static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
8081 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
8082 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
8083 return D1->getDecl() == D2->getDecl();
8084 return false;
8085}
8086
8087static const Expr *getStrlenExprArg(const Expr *E) {
8088 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8089 const FunctionDecl *FD = CE->getDirectCallee();
8090 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00008091 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00008092 return CE->getArg(0)->IgnoreParenCasts();
8093 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008094 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00008095}
8096
8097// Warn on anti-patterns as the 'size' argument to strncat.
8098// The correct size argument should look like following:
8099// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
8100void Sema::CheckStrncatArguments(const CallExpr *CE,
8101 IdentifierInfo *FnName) {
8102 // Don't crash if the user has the wrong number of arguments.
8103 if (CE->getNumArgs() < 3)
8104 return;
8105 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
8106 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
8107 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
8108
Nico Weber0e6daef2013-12-26 23:38:39 +00008109 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
8110 CE->getRParenLoc()))
8111 return;
8112
Anna Zaks314cd092012-02-01 19:08:57 +00008113 // Identify common expressions, which are wrongly used as the size argument
8114 // to strncat and may lead to buffer overflows.
8115 unsigned PatternType = 0;
8116 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
8117 // - sizeof(dst)
8118 if (referToTheSameDecl(SizeOfArg, DstArg))
8119 PatternType = 1;
8120 // - sizeof(src)
8121 else if (referToTheSameDecl(SizeOfArg, SrcArg))
8122 PatternType = 2;
8123 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
8124 if (BE->getOpcode() == BO_Sub) {
8125 const Expr *L = BE->getLHS()->IgnoreParenCasts();
8126 const Expr *R = BE->getRHS()->IgnoreParenCasts();
8127 // - sizeof(dst) - strlen(dst)
8128 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
8129 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
8130 PatternType = 1;
8131 // - sizeof(src) - (anything)
8132 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
8133 PatternType = 2;
8134 }
8135 }
8136
8137 if (PatternType == 0)
8138 return;
8139
Anna Zaks5069aa32012-02-03 01:27:37 +00008140 // Generate the diagnostic.
8141 SourceLocation SL = LenArg->getLocStart();
8142 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00008143 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00008144
8145 // If the function is defined as a builtin macro, do not show macro expansion.
8146 if (SM.isMacroArgExpansion(SL)) {
8147 SL = SM.getSpellingLoc(SL);
8148 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
8149 SM.getSpellingLoc(SR.getEnd()));
8150 }
8151
Anna Zaks13b08572012-08-08 21:42:23 +00008152 // Check if the destination is an array (rather than a pointer to an array).
8153 QualType DstTy = DstArg->getType();
8154 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
8155 Context);
8156 if (!isKnownSizeArray) {
8157 if (PatternType == 1)
8158 Diag(SL, diag::warn_strncat_wrong_size) << SR;
8159 else
8160 Diag(SL, diag::warn_strncat_src_size) << SR;
8161 return;
8162 }
8163
Anna Zaks314cd092012-02-01 19:08:57 +00008164 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00008165 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00008166 else
Anna Zaks5069aa32012-02-03 01:27:37 +00008167 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00008168
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008169 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00008170 llvm::raw_svector_ostream OS(sizeString);
8171 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008172 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00008173 OS << ") - ";
8174 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008175 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00008176 OS << ") - 1";
8177
Anna Zaks5069aa32012-02-03 01:27:37 +00008178 Diag(SL, diag::note_strncat_wrong_size)
8179 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00008180}
8181
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008182//===--- CHECK: Return Address of Stack Variable --------------------------===//
8183
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008184static const Expr *EvalVal(const Expr *E,
8185 SmallVectorImpl<const DeclRefExpr *> &refVars,
8186 const Decl *ParentDecl);
8187static const Expr *EvalAddr(const Expr *E,
8188 SmallVectorImpl<const DeclRefExpr *> &refVars,
8189 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008190
8191/// CheckReturnStackAddr - Check if a return statement returns the address
8192/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008193static void
8194CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
8195 SourceLocation ReturnLoc) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008196 const Expr *stackE = nullptr;
8197 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008198
8199 // Perform checking for returned stack addresses, local blocks,
8200 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00008201 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008202 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008203 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00008204 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008205 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008206 }
8207
Craig Topperc3ec1492014-05-26 06:22:03 +00008208 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008209 return; // Nothing suspicious was found.
8210
Simon Pilgrim750bde62017-03-31 11:00:53 +00008211 // Parameters are initialized in the calling scope, so taking the address
Richard Trieu81b6c562016-08-05 23:24:47 +00008212 // of a parameter reference doesn't need a warning.
8213 for (auto *DRE : refVars)
8214 if (isa<ParmVarDecl>(DRE->getDecl()))
8215 return;
8216
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008217 SourceLocation diagLoc;
8218 SourceRange diagRange;
8219 if (refVars.empty()) {
8220 diagLoc = stackE->getLocStart();
8221 diagRange = stackE->getSourceRange();
8222 } else {
8223 // We followed through a reference variable. 'stackE' contains the
8224 // problematic expression but we will warn at the return statement pointing
8225 // at the reference variable. We will later display the "trail" of
8226 // reference variables using notes.
8227 diagLoc = refVars[0]->getLocStart();
8228 diagRange = refVars[0]->getSourceRange();
8229 }
8230
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008231 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
8232 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00008233 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008234 << DR->getDecl()->getDeclName() << diagRange;
8235 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008236 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008237 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008238 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008239 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00008240 // If there is an LValue->RValue conversion, then the value of the
8241 // reference type is used, not the reference.
8242 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
8243 if (ICE->getCastKind() == CK_LValueToRValue) {
8244 return;
8245 }
8246 }
Craig Topperda7b27f2015-11-17 05:40:09 +00008247 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
8248 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008249 }
8250
8251 // Display the "trail" of reference variables that we followed until we
8252 // found the problematic expression using notes.
8253 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008254 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008255 // If this var binds to another reference var, show the range of the next
8256 // var, otherwise the var binds to the problematic expression, in which case
8257 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008258 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
8259 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008260 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
8261 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008262 }
8263}
8264
8265/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
8266/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008267/// to a location on the stack, a local block, an address of a label, or a
8268/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008269/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008270/// encounter a subexpression that (1) clearly does not lead to one of the
8271/// above problematic expressions (2) is something we cannot determine leads to
8272/// a problematic expression based on such local checking.
8273///
8274/// Both EvalAddr and EvalVal follow through reference variables to evaluate
8275/// the expression that they point to. Such variables are added to the
8276/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008277///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00008278/// EvalAddr processes expressions that are pointers that are used as
8279/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008280/// At the base case of the recursion is a check for the above problematic
8281/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008282///
8283/// This implementation handles:
8284///
8285/// * pointer-to-pointer casts
8286/// * implicit conversions from array references to pointers
8287/// * taking the address of fields
8288/// * arbitrary interplay between "&" and "*" operators
8289/// * pointer arithmetic from an address of a stack variable
8290/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008291static const Expr *EvalAddr(const Expr *E,
8292 SmallVectorImpl<const DeclRefExpr *> &refVars,
8293 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008294 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00008295 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008296
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008297 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00008298 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00008299 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00008300 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00008301 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00008302
Peter Collingbourne91147592011-04-15 00:35:48 +00008303 E = E->IgnoreParens();
8304
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008305 // Our "symbolic interpreter" is just a dispatch off the currently
8306 // viewed AST node. We then recursively traverse the AST by calling
8307 // EvalAddr and EvalVal appropriately.
8308 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008309 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008310 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008311
Richard Smith40f08eb2014-01-30 22:05:38 +00008312 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00008313 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00008314 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00008315
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008316 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008317 // If this is a reference variable, follow through to the expression that
8318 // it points to.
8319 if (V->hasLocalStorage() &&
8320 V->getType()->isReferenceType() && V->hasInit()) {
8321 // Add the reference variable to the "trail".
8322 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008323 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008324 }
8325
Craig Topperc3ec1492014-05-26 06:22:03 +00008326 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008327 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008328
Chris Lattner934edb22007-12-28 05:31:15 +00008329 case Stmt::UnaryOperatorClass: {
8330 // The only unary operator that make sense to handle here
8331 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008332 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008333
John McCalle3027922010-08-25 11:45:40 +00008334 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008335 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008336 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008337 }
Mike Stump11289f42009-09-09 15:08:12 +00008338
Chris Lattner934edb22007-12-28 05:31:15 +00008339 case Stmt::BinaryOperatorClass: {
8340 // Handle pointer arithmetic. All other binary operators are not valid
8341 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008342 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00008343 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00008344
John McCalle3027922010-08-25 11:45:40 +00008345 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00008346 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008347
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008348 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00008349
8350 // Determine which argument is the real pointer base. It could be
8351 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008352 if (!Base->getType()->isPointerType())
8353 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00008354
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008355 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008356 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00008357 }
Steve Naroff2752a172008-09-10 19:17:48 +00008358
Chris Lattner934edb22007-12-28 05:31:15 +00008359 // For conditional operators we need to see if either the LHS or RHS are
8360 // valid DeclRefExpr*s. If one of them is valid, we return it.
8361 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008362 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008363
Chris Lattner934edb22007-12-28 05:31:15 +00008364 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008365 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008366 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008367 // In C++, we can have a throw-expression, which has 'void' type.
8368 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008369 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008370 return LHS;
8371 }
Chris Lattner934edb22007-12-28 05:31:15 +00008372
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008373 // In C++, we can have a throw-expression, which has 'void' type.
8374 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00008375 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008376
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008377 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00008378 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008379
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008380 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00008381 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008382 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00008383 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008384
8385 case Stmt::AddrLabelExprClass:
8386 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00008387
John McCall28fc7092011-11-10 05:35:25 +00008388 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008389 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8390 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00008391
Ted Kremenekc3b4c522008-08-07 00:49:01 +00008392 // For casts, we need to handle conversions from arrays to
8393 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00008394 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00008395 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00008396 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00008397 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00008398 case Stmt::CXXStaticCastExprClass:
8399 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00008400 case Stmt::CXXConstCastExprClass:
8401 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008402 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00008403 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00008404 case CK_LValueToRValue:
8405 case CK_NoOp:
8406 case CK_BaseToDerived:
8407 case CK_DerivedToBase:
8408 case CK_UncheckedDerivedToBase:
8409 case CK_Dynamic:
8410 case CK_CPointerToObjCPointerCast:
8411 case CK_BlockPointerToObjCPointerCast:
8412 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008413 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00008414
8415 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008416 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00008417
Richard Trieudadefde2014-07-02 04:39:38 +00008418 case CK_BitCast:
8419 if (SubExpr->getType()->isAnyPointerType() ||
8420 SubExpr->getType()->isBlockPointerType() ||
8421 SubExpr->getType()->isObjCQualifiedIdType())
8422 return EvalAddr(SubExpr, refVars, ParentDecl);
8423 else
8424 return nullptr;
8425
Eli Friedman8195ad72012-02-23 23:04:32 +00008426 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00008427 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00008428 }
Chris Lattner934edb22007-12-28 05:31:15 +00008429 }
Mike Stump11289f42009-09-09 15:08:12 +00008430
Douglas Gregorfe314812011-06-21 17:03:29 +00008431 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008432 if (const Expr *Result =
8433 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8434 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00008435 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00008436 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008437
Chris Lattner934edb22007-12-28 05:31:15 +00008438 // Everything else: we simply don't reason about them.
8439 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00008440 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00008441 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008442}
Mike Stump11289f42009-09-09 15:08:12 +00008443
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008444/// EvalVal - This function is complements EvalAddr in the mutual recursion.
8445/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008446static const Expr *EvalVal(const Expr *E,
8447 SmallVectorImpl<const DeclRefExpr *> &refVars,
8448 const Decl *ParentDecl) {
8449 do {
8450 // We should only be called for evaluating non-pointer expressions, or
8451 // expressions with a pointer type that are not used as references but
8452 // instead
8453 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00008454
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008455 // Our "symbolic interpreter" is just a dispatch off the currently
8456 // viewed AST node. We then recursively traverse the AST by calling
8457 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00008458
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008459 E = E->IgnoreParens();
8460 switch (E->getStmtClass()) {
8461 case Stmt::ImplicitCastExprClass: {
8462 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
8463 if (IE->getValueKind() == VK_LValue) {
8464 E = IE->getSubExpr();
8465 continue;
8466 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008467 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008468 }
Richard Smith40f08eb2014-01-30 22:05:38 +00008469
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008470 case Stmt::ExprWithCleanupsClass:
8471 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8472 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008473
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008474 case Stmt::DeclRefExprClass: {
8475 // When we hit a DeclRefExpr we are looking at code that refers to a
8476 // variable's name. If it's not a reference variable we check if it has
8477 // local storage within the function, and if so, return the expression.
8478 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8479
8480 // If we leave the immediate function, the lifetime isn't about to end.
8481 if (DR->refersToEnclosingVariableOrCapture())
8482 return nullptr;
8483
8484 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
8485 // Check if it refers to itself, e.g. "int& i = i;".
8486 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008487 return DR;
8488
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008489 if (V->hasLocalStorage()) {
8490 if (!V->getType()->isReferenceType())
8491 return DR;
8492
8493 // Reference variable, follow through to the expression that
8494 // it points to.
8495 if (V->hasInit()) {
8496 // Add the reference variable to the "trail".
8497 refVars.push_back(DR);
8498 return EvalVal(V->getInit(), refVars, V);
8499 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008500 }
8501 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008502
8503 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008504 }
Mike Stump11289f42009-09-09 15:08:12 +00008505
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008506 case Stmt::UnaryOperatorClass: {
8507 // The only unary operator that make sense to handle here
8508 // is Deref. All others don't resolve to a "name." This includes
8509 // handling all sorts of rvalues passed to a unary operator.
8510 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008511
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008512 if (U->getOpcode() == UO_Deref)
8513 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00008514
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008515 return nullptr;
8516 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008517
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008518 case Stmt::ArraySubscriptExprClass: {
8519 // Array subscripts are potential references to data on the stack. We
8520 // retrieve the DeclRefExpr* for the array variable if it indeed
8521 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00008522 const auto *ASE = cast<ArraySubscriptExpr>(E);
8523 if (ASE->isTypeDependent())
8524 return nullptr;
8525 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008526 }
Mike Stump11289f42009-09-09 15:08:12 +00008527
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008528 case Stmt::OMPArraySectionExprClass: {
8529 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8530 ParentDecl);
8531 }
Mike Stump11289f42009-09-09 15:08:12 +00008532
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008533 case Stmt::ConditionalOperatorClass: {
8534 // For conditional operators we need to see if either the LHS or RHS are
8535 // non-NULL Expr's. If one is non-NULL, we return it.
8536 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008537
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008538 // Handle the GNU extension for missing LHS.
8539 if (const Expr *LHSExpr = C->getLHS()) {
8540 // In C++, we can have a throw-expression, which has 'void' type.
8541 if (!LHSExpr->getType()->isVoidType())
8542 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8543 return LHS;
8544 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008545
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008546 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008547 if (C->getRHS()->getType()->isVoidType())
8548 return nullptr;
8549
8550 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008551 }
8552
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008553 // Accesses to members are potential references to data on the stack.
8554 case Stmt::MemberExprClass: {
8555 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00008556
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008557 // Check for indirect access. We only want direct field accesses.
8558 if (M->isArrow())
8559 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008560
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008561 // Check whether the member type is itself a reference, in which case
8562 // we're not going to refer to the member, but to what the member refers
8563 // to.
8564 if (M->getMemberDecl()->getType()->isReferenceType())
8565 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008566
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008567 return EvalVal(M->getBase(), refVars, ParentDecl);
8568 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00008569
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008570 case Stmt::MaterializeTemporaryExprClass:
8571 if (const Expr *Result =
8572 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8573 refVars, ParentDecl))
8574 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008575 return E;
8576
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008577 default:
8578 // Check that we don't return or take the address of a reference to a
8579 // temporary. This is only useful in C++.
8580 if (!E->isTypeDependent() && E->isRValue())
8581 return E;
8582
8583 // Everything else: we simply don't reason about them.
8584 return nullptr;
8585 }
8586 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008587}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008588
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008589void
8590Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8591 SourceLocation ReturnLoc,
8592 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00008593 const AttrVec *Attrs,
8594 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008595 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8596
8597 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00008598 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8599 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00008600 CheckNonNullExpr(*this, RetValExp))
8601 Diag(ReturnLoc, diag::warn_null_ret)
8602 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00008603
8604 // C++11 [basic.stc.dynamic.allocation]p4:
8605 // If an allocation function declared with a non-throwing
8606 // exception-specification fails to allocate storage, it shall return
8607 // a null pointer. Any other allocation function that fails to allocate
8608 // storage shall indicate failure only by throwing an exception [...]
8609 if (FD) {
8610 OverloadedOperatorKind Op = FD->getOverloadedOperator();
8611 if (Op == OO_New || Op == OO_Array_New) {
8612 const FunctionProtoType *Proto
8613 = FD->getType()->castAs<FunctionProtoType>();
Richard Smitheaf11ad2018-05-03 03:58:32 +00008614 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
Artyom Skrobov9f213442014-01-24 11:10:39 +00008615 CheckNonNullExpr(*this, RetValExp))
8616 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8617 << FD << getLangOpts().CPlusPlus11;
8618 }
8619 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008620}
8621
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008622//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8623
8624/// Check for comparisons of floating point operands using != and ==.
8625/// Issue a warning if these are no self-comparisons, as they are not likely
8626/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00008627void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00008628 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8629 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008630
8631 // Special case: check for x == x (which is OK).
8632 // Do not emit warnings for such cases.
8633 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8634 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8635 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00008636 return;
Mike Stump11289f42009-09-09 15:08:12 +00008637
Ted Kremenekeda40e22007-11-29 00:59:04 +00008638 // Special case: check for comparisons against literals that can be exactly
8639 // represented by APFloat. In such cases, do not emit a warning. This
8640 // is a heuristic: often comparison against such literals are used to
8641 // detect if a value in a variable has not changed. This clearly can
8642 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00008643 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8644 if (FLL->isExact())
8645 return;
8646 } else
8647 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8648 if (FLR->isExact())
8649 return;
Mike Stump11289f42009-09-09 15:08:12 +00008650
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008651 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00008652 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008653 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008654 return;
Mike Stump11289f42009-09-09 15:08:12 +00008655
David Blaikie1f4ff152012-07-16 20:47:22 +00008656 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008657 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008658 return;
Mike Stump11289f42009-09-09 15:08:12 +00008659
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008660 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00008661 Diag(Loc, diag::warn_floatingpoint_eq)
8662 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008663}
John McCallca01b222010-01-04 23:21:16 +00008664
John McCall70aa5392010-01-06 05:24:50 +00008665//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8666//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00008667
John McCall70aa5392010-01-06 05:24:50 +00008668namespace {
John McCallca01b222010-01-04 23:21:16 +00008669
John McCall70aa5392010-01-06 05:24:50 +00008670/// Structure recording the 'active' range of an integer-valued
8671/// expression.
8672struct IntRange {
8673 /// The number of bits active in the int.
8674 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00008675
John McCall70aa5392010-01-06 05:24:50 +00008676 /// True if the int is known not to have negative values.
8677 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00008678
John McCall70aa5392010-01-06 05:24:50 +00008679 IntRange(unsigned Width, bool NonNegative)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008680 : Width(Width), NonNegative(NonNegative) {}
John McCallca01b222010-01-04 23:21:16 +00008681
John McCall817d4af2010-11-10 23:38:19 +00008682 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00008683 static IntRange forBoolType() {
8684 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00008685 }
8686
John McCall817d4af2010-11-10 23:38:19 +00008687 /// Returns the range of an opaque value of the given integral type.
8688 static IntRange forValueOfType(ASTContext &C, QualType T) {
8689 return forValueOfCanonicalType(C,
8690 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00008691 }
8692
John McCall817d4af2010-11-10 23:38:19 +00008693 /// Returns the range of an opaque value of a canonical integral type.
8694 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00008695 assert(T->isCanonicalUnqualified());
8696
8697 if (const VectorType *VT = dyn_cast<VectorType>(T))
8698 T = VT->getElementType().getTypePtr();
8699 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8700 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008701 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8702 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00008703
Roman Lebedevca1aaac2017-10-21 16:44:03 +00008704 if (!C.getLangOpts().CPlusPlus) {
8705 // For enum types in C code, use the underlying datatype.
8706 if (const EnumType *ET = dyn_cast<EnumType>(T))
8707 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8708 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8709 // For enum types in C++, use the known bit width of the enumerators.
David Majnemer6a426652013-06-07 22:07:20 +00008710 EnumDecl *Enum = ET->getDecl();
Richard Smith371e9e8a2017-12-06 03:00:51 +00008711 // In C++11, enums can have a fixed underlying type. Use this type to
8712 // compute the range.
8713 if (Enum->isFixed()) {
Erich Keane69dbbb02017-09-21 19:58:55 +00008714 return IntRange(C.getIntWidth(QualType(T, 0)),
8715 !ET->isSignedIntegerOrEnumerationType());
Richard Smith371e9e8a2017-12-06 03:00:51 +00008716 }
John McCall18a2c2c2010-11-09 22:22:12 +00008717
David Majnemer6a426652013-06-07 22:07:20 +00008718 unsigned NumPositive = Enum->getNumPositiveBits();
8719 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00008720
David Majnemer6a426652013-06-07 22:07:20 +00008721 if (NumNegative == 0)
8722 return IntRange(NumPositive, true/*NonNegative*/);
8723 else
8724 return IntRange(std::max(NumPositive + 1, NumNegative),
8725 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00008726 }
John McCall70aa5392010-01-06 05:24:50 +00008727
8728 const BuiltinType *BT = cast<BuiltinType>(T);
8729 assert(BT->isInteger());
8730
8731 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8732 }
8733
John McCall817d4af2010-11-10 23:38:19 +00008734 /// Returns the "target" range of a canonical integral type, i.e.
8735 /// the range of values expressible in the type.
8736 ///
8737 /// This matches forValueOfCanonicalType except that enums have the
8738 /// full range of their type, not the range of their enumerators.
8739 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8740 assert(T->isCanonicalUnqualified());
8741
8742 if (const VectorType *VT = dyn_cast<VectorType>(T))
8743 T = VT->getElementType().getTypePtr();
8744 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8745 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008746 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8747 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008748 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00008749 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008750
8751 const BuiltinType *BT = cast<BuiltinType>(T);
8752 assert(BT->isInteger());
8753
8754 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8755 }
8756
8757 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00008758 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00008759 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00008760 L.NonNegative && R.NonNegative);
8761 }
8762
John McCall817d4af2010-11-10 23:38:19 +00008763 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008764 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008765 return IntRange(std::min(L.Width, R.Width),
8766 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008767 }
8768};
8769
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008770} // namespace
8771
8772static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
8773 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008774 if (value.isSigned() && value.isNegative())
8775 return IntRange(value.getMinSignedBits(), false);
8776
8777 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008778 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008779
8780 // isNonNegative() just checks the sign bit without considering
8781 // signedness.
8782 return IntRange(value.getActiveBits(), true);
8783}
8784
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008785static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8786 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008787 if (result.isInt())
8788 return GetValueRange(C, result.getInt(), MaxWidth);
8789
8790 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008791 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8792 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8793 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8794 R = IntRange::join(R, El);
8795 }
John McCall70aa5392010-01-06 05:24:50 +00008796 return R;
8797 }
8798
8799 if (result.isComplexInt()) {
8800 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8801 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8802 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008803 }
8804
8805 // This can happen with lossless casts to intptr_t of "based" lvalues.
8806 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008807 // FIXME: The only reason we need to pass the type in here is to get
8808 // the sign right on this one case. It would be nice if APValue
8809 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008810 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008811 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008812}
John McCall70aa5392010-01-06 05:24:50 +00008813
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008814static QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008815 QualType Ty = E->getType();
8816 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8817 Ty = AtomicRHS->getValueType();
8818 return Ty;
8819}
8820
John McCall70aa5392010-01-06 05:24:50 +00008821/// Pseudo-evaluate the given integer expression, estimating the
8822/// range of values it might take.
8823///
8824/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008825static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008826 E = E->IgnoreParens();
8827
8828 // Try a full evaluation first.
8829 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008830 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008831 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008832
8833 // I think we only want to look through implicit casts here; if the
8834 // user has an explicit widening cast, we should treat the value as
8835 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008836 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00008837 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00008838 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8839
Eli Friedmane6d33952013-07-08 20:20:06 +00008840 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00008841
George Burgess IVdf1ed002016-01-13 01:52:39 +00008842 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8843 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00008844
John McCall70aa5392010-01-06 05:24:50 +00008845 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00008846 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00008847 return OutputTypeRange;
8848
8849 IntRange SubRange
8850 = GetExprRange(C, CE->getSubExpr(),
8851 std::min(MaxWidth, OutputTypeRange.Width));
8852
8853 // Bail out if the subexpr's range is as wide as the cast type.
8854 if (SubRange.Width >= OutputTypeRange.Width)
8855 return OutputTypeRange;
8856
8857 // Otherwise, we take the smaller width, and we're non-negative if
8858 // either the output type or the subexpr is.
8859 return IntRange(SubRange.Width,
8860 SubRange.NonNegative || OutputTypeRange.NonNegative);
8861 }
8862
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008863 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008864 // If we can fold the condition, just take that operand.
8865 bool CondResult;
8866 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8867 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8868 : CO->getFalseExpr(),
8869 MaxWidth);
8870
8871 // Otherwise, conservatively merge.
8872 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8873 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8874 return IntRange::join(L, R);
8875 }
8876
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008877 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008878 switch (BO->getOpcode()) {
Richard Smithc70f1d62017-12-14 15:16:18 +00008879 case BO_Cmp:
8880 llvm_unreachable("builtin <=> should have class type");
John McCall70aa5392010-01-06 05:24:50 +00008881
8882 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00008883 case BO_LAnd:
8884 case BO_LOr:
8885 case BO_LT:
8886 case BO_GT:
8887 case BO_LE:
8888 case BO_GE:
8889 case BO_EQ:
8890 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00008891 return IntRange::forBoolType();
8892
John McCallc3688382011-07-13 06:35:24 +00008893 // The type of the assignments is the type of the LHS, so the RHS
8894 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00008895 case BO_MulAssign:
8896 case BO_DivAssign:
8897 case BO_RemAssign:
8898 case BO_AddAssign:
8899 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00008900 case BO_XorAssign:
8901 case BO_OrAssign:
8902 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00008903 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00008904
John McCallc3688382011-07-13 06:35:24 +00008905 // Simple assignments just pass through the RHS, which will have
8906 // been coerced to the LHS type.
8907 case BO_Assign:
8908 // TODO: bitfields?
8909 return GetExprRange(C, BO->getRHS(), MaxWidth);
8910
John McCall70aa5392010-01-06 05:24:50 +00008911 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008912 case BO_PtrMemD:
8913 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00008914 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008915
John McCall2ce81ad2010-01-06 22:07:33 +00008916 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00008917 case BO_And:
8918 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00008919 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8920 GetExprRange(C, BO->getRHS(), MaxWidth));
8921
John McCall70aa5392010-01-06 05:24:50 +00008922 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00008923 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00008924 // ...except that we want to treat '1 << (blah)' as logically
8925 // positive. It's an important idiom.
8926 if (IntegerLiteral *I
8927 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8928 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008929 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00008930 return IntRange(R.Width, /*NonNegative*/ true);
8931 }
8932 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008933 LLVM_FALLTHROUGH;
John McCall1bff9932010-04-07 01:14:35 +00008934
John McCalle3027922010-08-25 11:45:40 +00008935 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00008936 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008937
John McCall2ce81ad2010-01-06 22:07:33 +00008938 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00008939 case BO_Shr:
8940 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00008941 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8942
8943 // If the shift amount is a positive constant, drop the width by
8944 // that much.
8945 llvm::APSInt shift;
8946 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8947 shift.isNonNegative()) {
8948 unsigned zext = shift.getZExtValue();
8949 if (zext >= L.Width)
8950 L.Width = (L.NonNegative ? 0 : 1);
8951 else
8952 L.Width -= zext;
8953 }
8954
8955 return L;
8956 }
8957
8958 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008959 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008960 return GetExprRange(C, BO->getRHS(), MaxWidth);
8961
John McCall2ce81ad2010-01-06 22:07:33 +00008962 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008963 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008964 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008965 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008966 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008967
John McCall51431812011-07-14 22:39:48 +00008968 // The width of a division result is mostly determined by the size
8969 // of the LHS.
8970 case BO_Div: {
8971 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008972 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008973 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8974
8975 // If the divisor is constant, use that.
8976 llvm::APSInt divisor;
8977 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8978 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8979 if (log2 >= L.Width)
8980 L.Width = (L.NonNegative ? 0 : 1);
8981 else
8982 L.Width = std::min(L.Width - log2, MaxWidth);
8983 return L;
8984 }
8985
8986 // Otherwise, just use the LHS's width.
8987 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8988 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8989 }
8990
8991 // The result of a remainder can't be larger than the result of
8992 // either side.
8993 case BO_Rem: {
8994 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008995 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008996 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8997 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8998
8999 IntRange meet = IntRange::meet(L, R);
9000 meet.Width = std::min(meet.Width, MaxWidth);
9001 return meet;
9002 }
9003
9004 // The default behavior is okay for these.
9005 case BO_Mul:
9006 case BO_Add:
9007 case BO_Xor:
9008 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00009009 break;
9010 }
9011
John McCall51431812011-07-14 22:39:48 +00009012 // The default case is to treat the operation as if it were closed
9013 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00009014 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9015 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
9016 return IntRange::join(L, R);
9017 }
9018
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009019 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00009020 switch (UO->getOpcode()) {
9021 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00009022 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00009023 return IntRange::forBoolType();
9024
9025 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00009026 case UO_Deref:
9027 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00009028 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009029
9030 default:
9031 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
9032 }
9033 }
9034
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009035 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00009036 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
9037
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009038 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00009039 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00009040 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00009041
Eli Friedmane6d33952013-07-08 20:20:06 +00009042 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009043}
John McCall263a48b2010-01-04 23:31:57 +00009044
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009045static IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00009046 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00009047}
9048
John McCall263a48b2010-01-04 23:31:57 +00009049/// Checks whether the given value, which currently has the given
9050/// source semantics, has the same value when coerced through the
9051/// target semantics.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009052static bool IsSameFloatAfterCast(const llvm::APFloat &value,
9053 const llvm::fltSemantics &Src,
9054 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00009055 llvm::APFloat truncated = value;
9056
9057 bool ignored;
9058 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
9059 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
9060
9061 return truncated.bitwiseIsEqual(value);
9062}
9063
9064/// Checks whether the given value, which currently has the given
9065/// source semantics, has the same value when coerced through the
9066/// target semantics.
9067///
9068/// The value might be a vector of floats (or a complex number).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009069static bool IsSameFloatAfterCast(const APValue &value,
9070 const llvm::fltSemantics &Src,
9071 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00009072 if (value.isFloat())
9073 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
9074
9075 if (value.isVector()) {
9076 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
9077 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
9078 return false;
9079 return true;
9080 }
9081
9082 assert(value.isComplexFloat());
9083 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
9084 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
9085}
9086
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009087static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009088
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009089static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00009090 // Suppress cases where we are comparing against an enum constant.
9091 if (const DeclRefExpr *DR =
9092 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
9093 if (isa<EnumConstantDecl>(DR->getDecl()))
Roman Lebedev6de129e2017-10-15 20:13:17 +00009094 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00009095
9096 // Suppress cases where the '0' value is expanded from a macro.
9097 if (E->getLocStart().isMacroID())
Roman Lebedev6de129e2017-10-15 20:13:17 +00009098 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00009099
Roman Lebedev6de129e2017-10-15 20:13:17 +00009100 return false;
9101}
9102
Richard Smith692f66ab2017-12-06 19:23:19 +00009103static bool isKnownToHaveUnsignedValue(Expr *E) {
9104 return E->getType()->isIntegerType() &&
Roman Lebedev6de129e2017-10-15 20:13:17 +00009105 (!E->getType()->isSignedIntegerType() ||
9106 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
9107}
9108
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009109namespace {
Richard Smitha5370fb2017-12-08 22:57:11 +00009110/// The promoted range of values of a type. In general this has the
9111/// following structure:
9112///
9113/// |-----------| . . . |-----------|
9114/// ^ ^ ^ ^
9115/// Min HoleMin HoleMax Max
9116///
9117/// ... where there is only a hole if a signed type is promoted to unsigned
9118/// (in which case Min and Max are the smallest and largest representable
9119/// values).
9120struct PromotedRange {
9121 // Min, or HoleMax if there is a hole.
9122 llvm::APSInt PromotedMin;
9123 // Max, or HoleMin if there is a hole.
9124 llvm::APSInt PromotedMax;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009125
Richard Smitha5370fb2017-12-08 22:57:11 +00009126 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
9127 if (R.Width == 0)
9128 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
9129 else if (R.Width >= BitWidth && !Unsigned) {
9130 // Promotion made the type *narrower*. This happens when promoting
9131 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
9132 // Treat all values of 'signed int' as being in range for now.
9133 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
9134 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
9135 } else {
9136 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
9137 .extOrTrunc(BitWidth);
9138 PromotedMin.setIsUnsigned(Unsigned);
9139
9140 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
9141 .extOrTrunc(BitWidth);
9142 PromotedMax.setIsUnsigned(Unsigned);
9143 }
9144 }
9145
9146 // Determine whether this range is contiguous (has no hole).
9147 bool isContiguous() const { return PromotedMin <= PromotedMax; }
9148
9149 // Where a constant value is within the range.
9150 enum ComparisonResult {
9151 LT = 0x1,
9152 LE = 0x2,
9153 GT = 0x4,
9154 GE = 0x8,
9155 EQ = 0x10,
9156 NE = 0x20,
9157 InRangeFlag = 0x40,
9158
9159 Less = LE | LT | NE,
9160 Min = LE | InRangeFlag,
9161 InRange = InRangeFlag,
9162 Max = GE | InRangeFlag,
9163 Greater = GE | GT | NE,
9164
9165 OnlyValue = LE | GE | EQ | InRangeFlag,
9166 InHole = NE
9167 };
9168
9169 ComparisonResult compare(const llvm::APSInt &Value) const {
9170 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
9171 Value.isUnsigned() == PromotedMin.isUnsigned());
9172 if (!isContiguous()) {
9173 assert(Value.isUnsigned() && "discontiguous range for signed compare");
9174 if (Value.isMinValue()) return Min;
9175 if (Value.isMaxValue()) return Max;
9176 if (Value >= PromotedMin) return InRange;
9177 if (Value <= PromotedMax) return InRange;
9178 return InHole;
9179 }
9180
9181 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
9182 case -1: return Less;
9183 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
9184 case 1:
9185 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
9186 case -1: return InRange;
9187 case 0: return Max;
9188 case 1: return Greater;
9189 }
9190 }
9191
9192 llvm_unreachable("impossible compare result");
9193 }
9194
Richard Smithc70f1d62017-12-14 15:16:18 +00009195 static llvm::Optional<StringRef>
9196 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
9197 if (Op == BO_Cmp) {
9198 ComparisonResult LTFlag = LT, GTFlag = GT;
9199 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
9200
9201 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
9202 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
9203 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
9204 return llvm::None;
9205 }
9206
Richard Smitha5370fb2017-12-08 22:57:11 +00009207 ComparisonResult TrueFlag, FalseFlag;
9208 if (Op == BO_EQ) {
9209 TrueFlag = EQ;
9210 FalseFlag = NE;
9211 } else if (Op == BO_NE) {
9212 TrueFlag = NE;
9213 FalseFlag = EQ;
9214 } else {
9215 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
9216 TrueFlag = LT;
9217 FalseFlag = GE;
9218 } else {
9219 TrueFlag = GT;
9220 FalseFlag = LE;
9221 }
9222 if (Op == BO_GE || Op == BO_LE)
9223 std::swap(TrueFlag, FalseFlag);
9224 }
9225 if (R & TrueFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00009226 return StringRef("true");
Richard Smitha5370fb2017-12-08 22:57:11 +00009227 if (R & FalseFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00009228 return StringRef("false");
Richard Smitha5370fb2017-12-08 22:57:11 +00009229 return llvm::None;
9230 }
Roman Lebedev6de129e2017-10-15 20:13:17 +00009231};
John McCallcc7e5bf2010-05-06 08:58:33 +00009232}
9233
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009234static bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00009235 // Strip off implicit integral promotions.
9236 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00009237 if (ICE->getCastKind() != CK_IntegralCast &&
9238 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00009239 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00009240 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00009241 }
9242
9243 return E->getType()->isEnumeralType();
9244}
9245
Richard Smith692f66ab2017-12-06 19:23:19 +00009246static int classifyConstantValue(Expr *Constant) {
9247 // The values of this enumeration are used in the diagnostics
9248 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
9249 enum ConstantValueKind {
9250 Miscellaneous = 0,
9251 LiteralTrue,
9252 LiteralFalse
9253 };
9254 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
9255 return BL->getValue() ? ConstantValueKind::LiteralTrue
9256 : ConstantValueKind::LiteralFalse;
9257 return ConstantValueKind::Miscellaneous;
9258}
9259
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009260static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
9261 Expr *Constant, Expr *Other,
9262 const llvm::APSInt &Value,
9263 bool RhsConstant) {
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009264 if (S.inTemplateInstantiation())
9265 return false;
9266
Richard Smitha5370fb2017-12-08 22:57:11 +00009267 Expr *OriginalOther = Other;
9268
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009269 Constant = Constant->IgnoreParenImpCasts();
9270 Other = Other->IgnoreParenImpCasts();
9271
Richard Smitha5370fb2017-12-08 22:57:11 +00009272 // Suppress warnings on tautological comparisons between values of the same
9273 // enumeration type. There are only two ways we could warn on this:
9274 // - If the constant is outside the range of representable values of
9275 // the enumeration. In such a case, we should warn about the cast
9276 // to enumeration type, not about the comparison.
9277 // - If the constant is the maximum / minimum in-range value. For an
9278 // enumeratin type, such comparisons can be meaningful and useful.
9279 if (Constant->getType()->isEnumeralType() &&
9280 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
9281 return false;
9282
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009283 // TODO: Investigate using GetExprRange() to get tighter bounds
9284 // on the bit ranges.
9285 QualType OtherT = Other->getType();
9286 if (const auto *AT = OtherT->getAs<AtomicType>())
9287 OtherT = AT->getValueType();
9288 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
9289
9290 // Whether we're treating Other as being a bool because of the form of
9291 // expression despite it having another type (typically 'int' in C).
9292 bool OtherIsBooleanDespiteType =
9293 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
9294 if (OtherIsBooleanDespiteType)
9295 OtherRange = IntRange::forBoolType();
9296
Richard Smitha5370fb2017-12-08 22:57:11 +00009297 // Determine the promoted range of the other type and see if a comparison of
9298 // the constant against that range is tautological.
9299 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
9300 Value.isUnsigned());
9301 auto Cmp = OtherPromotedRange.compare(Value);
9302 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
9303 if (!Result)
9304 return false;
Hans Wennborg5791ce72017-12-08 16:54:08 +00009305
Richard Smitha5370fb2017-12-08 22:57:11 +00009306 // Suppress the diagnostic for an in-range comparison if the constant comes
9307 // from a macro or enumerator. We don't want to diagnose
9308 //
9309 // some_long_value <= INT_MAX
9310 //
9311 // when sizeof(int) == sizeof(long).
9312 bool InRange = Cmp & PromotedRange::InRangeFlag;
9313 if (InRange && IsEnumConstOrFromMacro(S, Constant))
9314 return false;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009315
9316 // If this is a comparison to an enum constant, include that
9317 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00009318 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009319 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
9320 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
9321
Richard Smitha5370fb2017-12-08 22:57:11 +00009322 // Should be enough for uint128 (39 decimal digits)
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009323 SmallString<64> PrettySourceValue;
9324 llvm::raw_svector_ostream OS(PrettySourceValue);
9325 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00009326 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009327 else
9328 OS << Value;
9329
Richard Smitha5370fb2017-12-08 22:57:11 +00009330 // FIXME: We use a somewhat different formatting for the in-range cases and
9331 // cases involving boolean values for historical reasons. We should pick a
9332 // consistent way of presenting these diagnostics.
9333 if (!InRange || Other->isKnownToHaveBooleanValue()) {
9334 S.DiagRuntimeBehavior(
9335 E->getOperatorLoc(), E,
9336 S.PDiag(!InRange ? diag::warn_out_of_range_compare
9337 : diag::warn_tautological_bool_compare)
9338 << OS.str() << classifyConstantValue(Constant)
9339 << OtherT << OtherIsBooleanDespiteType << *Result
9340 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
9341 } else {
9342 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
9343 ? (HasEnumType(OriginalOther)
9344 ? diag::warn_unsigned_enum_always_true_comparison
9345 : diag::warn_unsigned_always_true_comparison)
9346 : diag::warn_tautological_constant_compare;
Roman Lebedev6de129e2017-10-15 20:13:17 +00009347
Richard Smitha5370fb2017-12-08 22:57:11 +00009348 S.Diag(E->getOperatorLoc(), Diag)
9349 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
9350 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
9351 }
9352
9353 return true;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009354}
9355
John McCallcc7e5bf2010-05-06 08:58:33 +00009356/// Analyze the operands of the given comparison. Implements the
9357/// fallback case from AnalyzeComparison.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009358static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00009359 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9360 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009361}
John McCall263a48b2010-01-04 23:31:57 +00009362
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009363/// Implements -Wsign-compare.
John McCallca01b222010-01-04 23:21:16 +00009364///
Richard Trieu82402a02011-09-15 21:56:47 +00009365/// \param E the binary operator to check for warnings
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009366static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009367 // The type the comparison is being performed in.
9368 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00009369
9370 // Only analyze comparison operators where both sides have been converted to
9371 // the same type.
9372 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
9373 return AnalyzeImpConvsInComparison(S, E);
9374
9375 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00009376 if (E->isValueDependent())
9377 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00009378
Roman Lebedev6de129e2017-10-15 20:13:17 +00009379 Expr *LHS = E->getLHS();
9380 Expr *RHS = E->getRHS();
9381
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009382 if (T->isIntegralType(S.Context)) {
9383 llvm::APSInt RHSValue;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009384 llvm::APSInt LHSValue;
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009385
Roman Lebedev6de129e2017-10-15 20:13:17 +00009386 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
9387 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
Roman Lebedevbd1fc222017-10-12 20:16:51 +00009388
Roman Lebedev6de129e2017-10-15 20:13:17 +00009389 // We don't care about expressions whose result is a constant.
9390 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
9391 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6f405db2017-10-12 22:03:20 +00009392
Roman Lebedev6de129e2017-10-15 20:13:17 +00009393 // We only care about expressions where just one side is literal
9394 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
9395 // Is the constant on the RHS or LHS?
9396 const bool RhsConstant = IsRHSIntegralLiteral;
9397 Expr *Const = RhsConstant ? RHS : LHS;
9398 Expr *Other = RhsConstant ? LHS : RHS;
9399 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
9400
9401 // Check whether an integer constant comparison results in a value
9402 // of 'true' or 'false'.
Roman Lebedev6de129e2017-10-15 20:13:17 +00009403 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
9404 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00009405 }
9406 }
9407
9408 if (!T->hasUnsignedIntegerRepresentation()) {
9409 // We don't do anything special if this isn't an unsigned integral
9410 // comparison: we're only interested in integral comparisons, and
9411 // signed comparisons only happen in cases we don't care to warn about.
Roman Lebedev6f405db2017-10-12 22:03:20 +00009412 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00009413 }
9414
9415 LHS = LHS->IgnoreParenImpCasts();
9416 RHS = RHS->IgnoreParenImpCasts();
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009417
Alex Lorenzb57409f2018-02-07 20:45:39 +00009418 if (!S.getLangOpts().CPlusPlus) {
9419 // Avoid warning about comparison of integers with different signs when
9420 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
9421 // the type of `E`.
9422 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
9423 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9424 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
9425 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9426 }
9427
John McCallcc7e5bf2010-05-06 08:58:33 +00009428 // Check to see if one of the (unmodified) operands is of different
9429 // signedness.
9430 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00009431 if (LHS->getType()->hasSignedIntegerRepresentation()) {
9432 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00009433 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00009434 signedOperand = LHS;
9435 unsignedOperand = RHS;
9436 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
9437 signedOperand = RHS;
9438 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00009439 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00009440 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00009441 }
9442
John McCallcc7e5bf2010-05-06 08:58:33 +00009443 // Otherwise, calculate the effective range of the signed operand.
9444 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00009445
John McCallcc7e5bf2010-05-06 08:58:33 +00009446 // Go ahead and analyze implicit conversions in the operands. Note
9447 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00009448 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
9449 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00009450
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009451 // If the signed range is non-negative, -Wsign-compare won't fire.
John McCallcc7e5bf2010-05-06 08:58:33 +00009452 if (signedRange.NonNegative)
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009453 return;
John McCallca01b222010-01-04 23:21:16 +00009454
9455 // For (in)equality comparisons, if the unsigned operand is a
9456 // constant which cannot collide with a overflowed signed operand,
9457 // then reinterpreting the signed operand as unsigned will not
9458 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00009459 if (E->isEqualityOp()) {
9460 unsigned comparisonWidth = S.Context.getIntWidth(T);
9461 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00009462
John McCallcc7e5bf2010-05-06 08:58:33 +00009463 // We should never be unable to prove that the unsigned operand is
9464 // non-negative.
9465 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
9466
9467 if (unsignedRange.Width < comparisonWidth)
9468 return;
9469 }
9470
Douglas Gregorbfb4a212012-05-01 01:53:49 +00009471 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9472 S.PDiag(diag::warn_mixed_sign_comparison)
9473 << LHS->getType() << RHS->getType()
9474 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00009475}
9476
John McCall1f425642010-11-11 03:21:53 +00009477/// Analyzes an attempt to assign the given value to a bitfield.
9478///
9479/// Returns true if there was something fishy about the attempt.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009480static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9481 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00009482 assert(Bitfield->isBitField());
9483 if (Bitfield->isInvalidDecl())
9484 return false;
9485
John McCalldeebbcf2010-11-11 05:33:51 +00009486 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00009487 QualType BitfieldType = Bitfield->getType();
9488 if (BitfieldType->isBooleanType())
9489 return false;
9490
9491 if (BitfieldType->isEnumeralType()) {
9492 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9493 // If the underlying enum type was not explicitly specified as an unsigned
9494 // type and the enum contain only positive values, MSVC++ will cause an
9495 // inconsistency by storing this as a signed type.
9496 if (S.getLangOpts().CPlusPlus11 &&
9497 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9498 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9499 BitfieldEnumDecl->getNumNegativeBits() == 0) {
9500 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9501 << BitfieldEnumDecl->getNameAsString();
9502 }
9503 }
9504
John McCalldeebbcf2010-11-11 05:33:51 +00009505 if (Bitfield->getType()->isBooleanType())
9506 return false;
9507
Douglas Gregor789adec2011-02-04 13:09:01 +00009508 // Ignore value- or type-dependent expressions.
9509 if (Bitfield->getBitWidth()->isValueDependent() ||
9510 Bitfield->getBitWidth()->isTypeDependent() ||
9511 Init->isValueDependent() ||
9512 Init->isTypeDependent())
9513 return false;
9514
John McCall1f425642010-11-11 03:21:53 +00009515 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00009516 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00009517
Richard Smith5fab0c92011-12-28 19:48:30 +00009518 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009519 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9520 Expr::SE_AllowSideEffects)) {
9521 // The RHS is not constant. If the RHS has an enum type, make sure the
9522 // bitfield is wide enough to hold all the values of the enum without
9523 // truncation.
9524 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9525 EnumDecl *ED = EnumTy->getDecl();
9526 bool SignedBitfield = BitfieldType->isSignedIntegerType();
9527
9528 // Enum types are implicitly signed on Windows, so check if there are any
9529 // negative enumerators to see if the enum was intended to be signed or
9530 // not.
9531 bool SignedEnum = ED->getNumNegativeBits() > 0;
9532
9533 // Check for surprising sign changes when assigning enum values to a
9534 // bitfield of different signedness. If the bitfield is signed and we
9535 // have exactly the right number of bits to store this unsigned enum,
9536 // suggest changing the enum to an unsigned type. This typically happens
9537 // on Windows where unfixed enums always use an underlying type of 'int'.
9538 unsigned DiagID = 0;
9539 if (SignedEnum && !SignedBitfield) {
9540 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9541 } else if (SignedBitfield && !SignedEnum &&
9542 ED->getNumPositiveBits() == FieldWidth) {
9543 DiagID = diag::warn_signed_bitfield_enum_conversion;
9544 }
9545
9546 if (DiagID) {
9547 S.Diag(InitLoc, DiagID) << Bitfield << ED;
9548 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9549 SourceRange TypeRange =
9550 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9551 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9552 << SignedEnum << TypeRange;
9553 }
9554
9555 // Compute the required bitwidth. If the enum has negative values, we need
9556 // one more bit than the normal number of positive bits to represent the
9557 // sign bit.
9558 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9559 ED->getNumNegativeBits())
9560 : ED->getNumPositiveBits();
9561
9562 // Check the bitwidth.
9563 if (BitsNeeded > FieldWidth) {
9564 Expr *WidthExpr = Bitfield->getBitWidth();
9565 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9566 << Bitfield << ED;
9567 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9568 << BitsNeeded << ED << WidthExpr->getSourceRange();
9569 }
9570 }
9571
John McCall1f425642010-11-11 03:21:53 +00009572 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009573 }
John McCall1f425642010-11-11 03:21:53 +00009574
John McCall1f425642010-11-11 03:21:53 +00009575 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00009576
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009577 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00009578 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009579 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9580 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00009581
John McCall1f425642010-11-11 03:21:53 +00009582 if (OriginalWidth <= FieldWidth)
9583 return false;
9584
Eli Friedmanc267a322012-01-26 23:11:39 +00009585 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00009586 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00009587 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00009588
Eli Friedmanc267a322012-01-26 23:11:39 +00009589 // Check whether the stored value is equal to the original value.
9590 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00009591 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00009592 return false;
9593
Eli Friedmanc267a322012-01-26 23:11:39 +00009594 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00009595 // therefore don't strictly fit into a signed bitfield of width 1.
9596 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00009597 return false;
9598
John McCall1f425642010-11-11 03:21:53 +00009599 std::string PrettyValue = Value.toString(10);
9600 std::string PrettyTrunc = TruncatedValue.toString(10);
9601
9602 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9603 << PrettyValue << PrettyTrunc << OriginalInit->getType()
9604 << Init->getSourceRange();
9605
9606 return true;
9607}
9608
John McCalld2a53122010-11-09 23:24:47 +00009609/// Analyze the given simple or compound assignment for warning-worthy
9610/// operations.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009611static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00009612 // Just recurse on the LHS.
9613 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9614
9615 // We want to recurse on the RHS as normal unless we're assigning to
9616 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00009617 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009618 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00009619 E->getOperatorLoc())) {
9620 // Recurse, ignoring any implicit conversions on the RHS.
9621 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9622 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00009623 }
9624 }
9625
9626 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9627}
9628
John McCall263a48b2010-01-04 23:31:57 +00009629/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009630static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9631 SourceLocation CContext, unsigned diag,
9632 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009633 if (pruneControlFlow) {
9634 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9635 S.PDiag(diag)
9636 << SourceType << T << E->getSourceRange()
9637 << SourceRange(CContext));
9638 return;
9639 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00009640 S.Diag(E->getExprLoc(), diag)
9641 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9642}
9643
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009644/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009645static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
9646 SourceLocation CContext,
9647 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009648 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009649}
9650
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +00009651/// Analyze the given compound assignment for the possible losing of
9652/// floating-point precision.
9653static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
9654 assert(isa<CompoundAssignOperator>(E) &&
9655 "Must be compound assignment operation");
9656 // Recurse on the LHS and RHS in here
9657 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9658 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9659
9660 // Now check the outermost expression
9661 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
9662 const auto *RBT = cast<CompoundAssignOperator>(E)
9663 ->getComputationResultType()
9664 ->getAs<BuiltinType>();
9665
9666 // If both source and target are floating points.
9667 if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint())
9668 // Builtin FP kinds are ordered by increasing FP rank.
9669 if (ResultBT->getKind() < RBT->getKind())
9670 // We don't want to warn for system macro.
9671 if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
9672 // warn about dropping FP rank.
9673 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(),
9674 E->getOperatorLoc(),
9675 diag::warn_impcast_float_result_precision);
9676}
Richard Trieube234c32016-04-21 21:04:55 +00009677
9678/// Diagnose an implicit cast from a floating point value to an integer value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009679static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9680 SourceLocation CContext) {
Richard Trieube234c32016-04-21 21:04:55 +00009681 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00009682 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00009683
9684 Expr *InnerE = E->IgnoreParenImpCasts();
9685 // We also want to warn on, e.g., "int i = -1.234"
9686 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9687 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9688 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9689
9690 const bool IsLiteral =
9691 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9692
9693 llvm::APFloat Value(0.0);
9694 bool IsConstant =
9695 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9696 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00009697 return DiagnoseImpCast(S, E, T, CContext,
9698 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00009699 }
9700
Chandler Carruth016ef402011-04-10 08:36:24 +00009701 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00009702
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00009703 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9704 T->hasUnsignedIntegerRepresentation());
Erich Keanea4c48c62018-05-08 21:26:21 +00009705 llvm::APFloat::opStatus Result = Value.convertToInteger(
9706 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
9707
9708 if (Result == llvm::APFloat::opOK && isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00009709 if (IsLiteral) return;
9710 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9711 PruneWarnings);
9712 }
9713
Erich Keanea4c48c62018-05-08 21:26:21 +00009714 // Conversion of a floating-point value to a non-bool integer where the
9715 // integral part cannot be represented by the integer type is undefined.
9716 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
9717 return DiagnoseImpCast(
9718 S, E, T, CContext,
9719 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
Richard Trieua2b8fe62018-05-14 23:21:48 +00009720 : diag::warn_impcast_float_to_integer_out_of_range,
9721 PruneWarnings);
Erich Keanea4c48c62018-05-08 21:26:21 +00009722
Richard Trieube234c32016-04-21 21:04:55 +00009723 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00009724 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00009725 // Warn on floating point literal to integer.
9726 DiagID = diag::warn_impcast_literal_float_to_integer;
9727 } else if (IntegerValue == 0) {
9728 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
9729 return DiagnoseImpCast(S, E, T, CContext,
9730 diag::warn_impcast_float_integer, PruneWarnings);
9731 }
9732 // Warn on non-zero to zero conversion.
9733 DiagID = diag::warn_impcast_float_to_integer_zero;
9734 } else {
9735 if (IntegerValue.isUnsigned()) {
9736 if (!IntegerValue.isMaxValue()) {
9737 return DiagnoseImpCast(S, E, T, CContext,
9738 diag::warn_impcast_float_integer, PruneWarnings);
9739 }
9740 } else { // IntegerValue.isSigned()
9741 if (!IntegerValue.isMaxSignedValue() &&
9742 !IntegerValue.isMinSignedValue()) {
9743 return DiagnoseImpCast(S, E, T, CContext,
9744 diag::warn_impcast_float_integer, PruneWarnings);
9745 }
9746 }
9747 // Warn on evaluatable floating point expression to integer conversion.
9748 DiagID = diag::warn_impcast_float_to_integer;
9749 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009750
Eli Friedman07185912013-08-29 23:44:43 +00009751 // FIXME: Force the precision of the source value down so we don't print
9752 // digits which are usually useless (we don't really care here if we
9753 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9754 // would automatically print the shortest representation, but it's a bit
9755 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00009756 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00009757 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9758 precision = (precision * 59 + 195) / 196;
9759 Value.toString(PrettySourceValue, precision);
9760
David Blaikie9b88cc02012-05-15 17:18:27 +00009761 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00009762 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00009763 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00009764 else
David Blaikie9b88cc02012-05-15 17:18:27 +00009765 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00009766
Richard Trieube234c32016-04-21 21:04:55 +00009767 if (PruneWarnings) {
9768 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9769 S.PDiag(DiagID)
9770 << E->getType() << T.getUnqualifiedType()
9771 << PrettySourceValue << PrettyTargetValue
9772 << E->getSourceRange() << SourceRange(CContext));
9773 } else {
9774 S.Diag(E->getExprLoc(), DiagID)
9775 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9776 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9777 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009778}
9779
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009780static std::string PrettyPrintInRange(const llvm::APSInt &Value,
9781 IntRange Range) {
John McCall18a2c2c2010-11-09 22:22:12 +00009782 if (!Range.Width) return "0";
9783
9784 llvm::APSInt ValueInRange = Value;
9785 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00009786 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00009787 return ValueInRange.toString(10);
9788}
9789
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009790static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009791 if (!isa<ImplicitCastExpr>(Ex))
9792 return false;
9793
9794 Expr *InnerE = Ex->IgnoreParenImpCasts();
9795 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9796 const Type *Source =
9797 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9798 if (Target->isDependentType())
9799 return false;
9800
9801 const BuiltinType *FloatCandidateBT =
9802 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9803 const Type *BoolCandidateType = ToBool ? Target : Source;
9804
9805 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9806 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9807}
9808
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009809static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9810 SourceLocation CC) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009811 unsigned NumArgs = TheCall->getNumArgs();
9812 for (unsigned i = 0; i < NumArgs; ++i) {
9813 Expr *CurrA = TheCall->getArg(i);
9814 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9815 continue;
9816
9817 bool IsSwapped = ((i > 0) &&
9818 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9819 IsSwapped |= ((i < (NumArgs - 1)) &&
9820 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9821 if (IsSwapped) {
9822 // Warn on this floating-point to bool conversion.
9823 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9824 CurrA->getType(), CC,
9825 diag::warn_impcast_floating_point_to_bool);
9826 }
9827 }
9828}
9829
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009830static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
9831 SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009832 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9833 E->getExprLoc()))
9834 return;
9835
Richard Trieu09d6b802016-01-08 23:35:06 +00009836 // Don't warn on functions which have return type nullptr_t.
9837 if (isa<CallExpr>(E))
9838 return;
9839
Richard Trieu5b993502014-10-15 03:42:06 +00009840 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9841 const Expr::NullPointerConstantKind NullKind =
9842 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9843 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9844 return;
9845
9846 // Return if target type is a safe conversion.
9847 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9848 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9849 return;
9850
9851 SourceLocation Loc = E->getSourceRange().getBegin();
9852
Richard Trieu0a5e1662016-02-13 00:58:53 +00009853 // Venture through the macro stacks to get to the source of macro arguments.
9854 // The new location is a better location than the complete location that was
9855 // passed in.
George Karpenkov441e8fd2018-02-09 23:30:07 +00009856 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
9857 CC = S.SourceMgr.getTopMacroCallerLoc(CC);
Richard Trieu0a5e1662016-02-13 00:58:53 +00009858
Richard Trieu5b993502014-10-15 03:42:06 +00009859 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00009860 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9861 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9862 Loc, S.SourceMgr, S.getLangOpts());
9863 if (MacroName == "NULL")
Richard Smithb5f81712018-04-30 05:25:48 +00009864 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
Richard Trieu5b993502014-10-15 03:42:06 +00009865 }
9866
9867 // Only warn if the null and context location are in the same macro expansion.
9868 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9869 return;
9870
9871 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009872 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
Richard Trieu5b993502014-10-15 03:42:06 +00009873 << FixItHint::CreateReplacement(Loc,
9874 S.getFixItZeroLiteralForType(T, Loc));
9875}
9876
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009877static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9878 ObjCArrayLiteral *ArrayLiteral);
9879
9880static void
9881checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9882 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00009883
9884/// Check a single element within a collection literal against the
9885/// target element type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009886static void checkObjCCollectionLiteralElement(Sema &S,
9887 QualType TargetElementType,
9888 Expr *Element,
9889 unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009890 // Skip a bitcast to 'id' or qualified 'id'.
9891 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9892 if (ICE->getCastKind() == CK_BitCast &&
9893 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9894 Element = ICE->getSubExpr();
9895 }
9896
9897 QualType ElementType = Element->getType();
9898 ExprResult ElementResult(Element);
9899 if (ElementType->getAs<ObjCObjectPointerType>() &&
9900 S.CheckSingleAssignmentConstraints(TargetElementType,
9901 ElementResult,
9902 false, false)
9903 != Sema::Compatible) {
9904 S.Diag(Element->getLocStart(),
9905 diag::warn_objc_collection_literal_element)
9906 << ElementType << ElementKind << TargetElementType
9907 << Element->getSourceRange();
9908 }
9909
9910 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9911 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9912 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9913 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9914}
9915
9916/// Check an Objective-C array literal being converted to the given
9917/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009918static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9919 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009920 if (!S.NSArrayDecl)
9921 return;
9922
9923 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9924 if (!TargetObjCPtr)
9925 return;
9926
9927 if (TargetObjCPtr->isUnspecialized() ||
9928 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9929 != S.NSArrayDecl->getCanonicalDecl())
9930 return;
9931
9932 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9933 if (TypeArgs.size() != 1)
9934 return;
9935
9936 QualType TargetElementType = TypeArgs[0];
9937 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9938 checkObjCCollectionLiteralElement(S, TargetElementType,
9939 ArrayLiteral->getElement(I),
9940 0);
9941 }
9942}
9943
9944/// Check an Objective-C dictionary literal being converted to the given
9945/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009946static void
9947checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9948 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009949 if (!S.NSDictionaryDecl)
9950 return;
9951
9952 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9953 if (!TargetObjCPtr)
9954 return;
9955
9956 if (TargetObjCPtr->isUnspecialized() ||
9957 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9958 != S.NSDictionaryDecl->getCanonicalDecl())
9959 return;
9960
9961 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9962 if (TypeArgs.size() != 2)
9963 return;
9964
9965 QualType TargetKeyType = TypeArgs[0];
9966 QualType TargetObjectType = TypeArgs[1];
9967 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9968 auto Element = DictionaryLiteral->getKeyValueElement(I);
9969 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9970 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9971 }
9972}
9973
Richard Trieufc404c72016-02-05 23:02:38 +00009974// Helper function to filter out cases for constant width constant conversion.
9975// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009976static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9977 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00009978 // If initializing from a constant, and the constant starts with '0',
9979 // then it is a binary, octal, or hexadecimal. Allow these constants
9980 // to fill all the bits, even if there is a sign change.
9981 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9982 const char FirstLiteralCharacter =
9983 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9984 if (FirstLiteralCharacter == '0')
9985 return false;
9986 }
9987
9988 // If the CC location points to a '{', and the type is char, then assume
9989 // assume it is an array initialization.
9990 if (CC.isValid() && T->isCharType()) {
9991 const char FirstContextCharacter =
9992 S.getSourceManager().getCharacterData(CC)[0];
9993 if (FirstContextCharacter == '{')
9994 return false;
9995 }
9996
9997 return true;
9998}
9999
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010000static void
10001CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
10002 bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010003 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +000010004
John McCallcc7e5bf2010-05-06 08:58:33 +000010005 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
10006 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
10007 if (Source == Target) return;
10008 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +000010009
Chandler Carruthc22845a2011-07-26 05:40:03 +000010010 // If the conversion context location is invalid don't complain. We also
10011 // don't want to emit a warning if the issue occurs from the expansion of
10012 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
10013 // delay this check as long as possible. Once we detect we are in that
10014 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010015 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +000010016 return;
10017
Richard Trieu021baa32011-09-23 20:10:00 +000010018 // Diagnose implicit casts to bool.
10019 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
10020 if (isa<StringLiteral>(E))
10021 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +000010022 // and expressions, for instance, assert(0 && "error here"), are
10023 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +000010024 return DiagnoseImpCast(S, E, T, CC,
10025 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +000010026 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
10027 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
10028 // This covers the literal expressions that evaluate to Objective-C
10029 // objects.
10030 return DiagnoseImpCast(S, E, T, CC,
10031 diag::warn_impcast_objective_c_literal_to_bool);
10032 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010033 if (Source->isPointerType() || Source->canDecayToPointerType()) {
10034 // Warn on pointer to bool conversion that is always true.
10035 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
10036 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +000010037 }
Richard Trieu021baa32011-09-23 20:10:00 +000010038 }
John McCall263a48b2010-01-04 23:31:57 +000010039
Douglas Gregor5054cb02015-07-07 03:58:22 +000010040 // Check implicit casts from Objective-C collection literals to specialized
10041 // collection types, e.g., NSArray<NSString *> *.
10042 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
10043 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
10044 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
10045 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
10046
John McCall263a48b2010-01-04 23:31:57 +000010047 // Strip vector types.
10048 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010049 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010050 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010051 return;
John McCallacf0ee52010-10-08 02:01:28 +000010052 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010053 }
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010054
Chris Lattneree7286f2011-06-14 04:51:15 +000010055 // If the vector cast is cast between two vectors of the same size, it is
10056 // a bitcast, not a conversion.
10057 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
10058 return;
John McCall263a48b2010-01-04 23:31:57 +000010059
10060 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
10061 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
10062 }
Stephen Canon3ba640d2014-04-03 10:33:25 +000010063 if (auto VecTy = dyn_cast<VectorType>(Target))
10064 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +000010065
10066 // Strip complex types.
10067 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010068 if (!isa<ComplexType>(Target)) {
Tim Northover02416372017-08-08 23:18:05 +000010069 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010070 return;
10071
Tim Northover02416372017-08-08 23:18:05 +000010072 return DiagnoseImpCast(S, E, T, CC,
10073 S.getLangOpts().CPlusPlus
10074 ? diag::err_impcast_complex_scalar
10075 : diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010076 }
John McCall263a48b2010-01-04 23:31:57 +000010077
10078 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
10079 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
10080 }
10081
10082 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
10083 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
10084
10085 // If the source is floating point...
10086 if (SourceBT && SourceBT->isFloatingPoint()) {
10087 // ...and the target is floating point...
10088 if (TargetBT && TargetBT->isFloatingPoint()) {
10089 // ...then warn if we're dropping FP rank.
10090
10091 // Builtin FP kinds are ordered by increasing FP rank.
10092 if (SourceBT->getKind() > TargetBT->getKind()) {
10093 // Don't warn about float constants that are precisely
10094 // representable in the target type.
10095 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +000010096 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +000010097 // Value might be a float, a float vector, or a float complex.
10098 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +000010099 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
10100 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +000010101 return;
10102 }
10103
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010104 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010105 return;
10106
John McCallacf0ee52010-10-08 02:01:28 +000010107 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +000010108 }
10109 // ... or possibly if we're increasing rank, too
10110 else if (TargetBT->getKind() > SourceBT->getKind()) {
10111 if (S.SourceMgr.isInSystemMacro(CC))
10112 return;
10113
10114 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +000010115 }
10116 return;
10117 }
10118
Richard Trieube234c32016-04-21 21:04:55 +000010119 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +000010120 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010121 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010122 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +000010123
Richard Trieube234c32016-04-21 21:04:55 +000010124 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +000010125 }
John McCall263a48b2010-01-04 23:31:57 +000010126
Richard Smith54894fd2015-12-30 01:06:52 +000010127 // Detect the case where a call result is converted from floating-point to
10128 // to bool, and the final argument to the call is converted from bool, to
10129 // discover this typo:
10130 //
10131 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
10132 //
10133 // FIXME: This is an incredibly special case; is there some more general
10134 // way to detect this class of misplaced-parentheses bug?
10135 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010136 // Check last argument of function call to see if it is an
10137 // implicit cast from a type matching the type the result
10138 // is being cast to.
10139 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +000010140 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010141 Expr *LastA = CEx->getArg(NumArgs - 1);
10142 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +000010143 if (isa<ImplicitCastExpr>(LastA) &&
10144 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010145 // Warn on this floating-point to bool conversion
10146 DiagnoseImpCast(S, E, T, CC,
10147 diag::warn_impcast_floating_point_to_bool);
10148 }
10149 }
10150 }
John McCall263a48b2010-01-04 23:31:57 +000010151 return;
10152 }
10153
Richard Trieu5b993502014-10-15 03:42:06 +000010154 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +000010155
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010156 S.DiscardMisalignedMemberAddress(Target, E);
10157
David Blaikie9366d2b2012-06-19 21:19:06 +000010158 if (!Source->isIntegerType() || !Target->isIntegerType())
10159 return;
10160
David Blaikie7555b6a2012-05-15 16:56:36 +000010161 // TODO: remove this early return once the false positives for constant->bool
10162 // in templates, macros, etc, are reduced or removed.
10163 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
10164 return;
10165
John McCallcc7e5bf2010-05-06 08:58:33 +000010166 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +000010167 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +000010168
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010169 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +000010170 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010171 // TODO: this should happen for bitfield stores, too.
10172 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +000010173 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010174 if (S.SourceMgr.isInSystemMacro(CC))
10175 return;
10176
John McCall18a2c2c2010-11-09 22:22:12 +000010177 std::string PrettySourceValue = Value.toString(10);
10178 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010179
Ted Kremenek33ba9952011-10-22 02:37:33 +000010180 S.DiagRuntimeBehavior(E->getExprLoc(), E,
10181 S.PDiag(diag::warn_impcast_integer_precision_constant)
10182 << PrettySourceValue << PrettyTargetValue
10183 << E->getType() << T << E->getSourceRange()
10184 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +000010185 return;
10186 }
10187
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010188 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
10189 if (S.SourceMgr.isInSystemMacro(CC))
10190 return;
10191
David Blaikie9455da02012-04-12 22:40:54 +000010192 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +000010193 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
10194 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +000010195 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +000010196 }
10197
Richard Trieudcb55572016-01-29 23:51:16 +000010198 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
10199 SourceRange.NonNegative && Source->isSignedIntegerType()) {
10200 // Warn when doing a signed to signed conversion, warn if the positive
10201 // source value is exactly the width of the target type, which will
10202 // cause a negative value to be stored.
10203
10204 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +000010205 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
10206 !S.SourceMgr.isInSystemMacro(CC)) {
10207 if (isSameWidthConstantConversion(S, E, T, CC)) {
10208 std::string PrettySourceValue = Value.toString(10);
10209 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +000010210
Richard Trieufc404c72016-02-05 23:02:38 +000010211 S.DiagRuntimeBehavior(
10212 E->getExprLoc(), E,
10213 S.PDiag(diag::warn_impcast_integer_precision_constant)
10214 << PrettySourceValue << PrettyTargetValue << E->getType() << T
10215 << E->getSourceRange() << clang::SourceRange(CC));
10216 return;
Richard Trieudcb55572016-01-29 23:51:16 +000010217 }
10218 }
Richard Trieufc404c72016-02-05 23:02:38 +000010219
Richard Trieudcb55572016-01-29 23:51:16 +000010220 // Fall through for non-constants to give a sign conversion warning.
10221 }
10222
John McCallcc7e5bf2010-05-06 08:58:33 +000010223 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
10224 (!TargetRange.NonNegative && SourceRange.NonNegative &&
10225 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010226 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010227 return;
10228
John McCallcc7e5bf2010-05-06 08:58:33 +000010229 unsigned DiagID = diag::warn_impcast_integer_sign;
10230
10231 // Traditionally, gcc has warned about this under -Wsign-compare.
10232 // We also want to warn about it in -Wconversion.
10233 // So if -Wconversion is off, use a completely identical diagnostic
10234 // in the sign-compare group.
10235 // The conditional-checking code will
10236 if (ICContext) {
10237 DiagID = diag::warn_impcast_integer_sign_conditional;
10238 *ICContext = true;
10239 }
10240
John McCallacf0ee52010-10-08 02:01:28 +000010241 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +000010242 }
10243
Douglas Gregora78f1932011-02-22 02:45:07 +000010244 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +000010245 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
10246 // type, to give us better diagnostics.
10247 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000010248 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +000010249 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10250 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
10251 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
10252 SourceType = S.Context.getTypeDeclType(Enum);
10253 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
10254 }
10255 }
10256
Douglas Gregora78f1932011-02-22 02:45:07 +000010257 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
10258 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +000010259 if (SourceEnum->getDecl()->hasNameForLinkage() &&
10260 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010261 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010262 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010263 return;
10264
Douglas Gregor364f7db2011-03-12 00:14:31 +000010265 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +000010266 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010267 }
John McCall263a48b2010-01-04 23:31:57 +000010268}
10269
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010270static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10271 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010272
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010273static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
10274 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010275 E = E->IgnoreParenImpCasts();
10276
10277 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +000010278 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010279
John McCallacf0ee52010-10-08 02:01:28 +000010280 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010281 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000010282 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +000010283}
10284
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010285static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10286 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +000010287 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +000010288
10289 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +000010290 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
10291 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000010292
10293 // If -Wconversion would have warned about either of the candidates
10294 // for a signedness conversion to the context type...
10295 if (!Suspicious) return;
10296
10297 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010298 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +000010299 return;
10300
John McCallcc7e5bf2010-05-06 08:58:33 +000010301 // ...then check whether it would have warned about either of the
10302 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +000010303 if (E->getType() == T) return;
10304
10305 Suspicious = false;
10306 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
10307 E->getType(), CC, &Suspicious);
10308 if (!Suspicious)
10309 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +000010310 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000010311}
10312
Richard Trieu65724892014-11-15 06:37:39 +000010313/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10314/// Input argument E is a logical expression.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010315static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +000010316 if (S.getLangOpts().Bool)
10317 return;
10318 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
10319}
10320
John McCallcc7e5bf2010-05-06 08:58:33 +000010321/// AnalyzeImplicitConversions - Find and report any interesting
10322/// implicit conversions in the given expression. There are a couple
10323/// of competing diagnostics here, -Wconversion and -Wsign-compare.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010324static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
10325 SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +000010326 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +000010327 Expr *E = OrigE->IgnoreParenImpCasts();
10328
Douglas Gregor6e8da6a2011-10-10 17:38:18 +000010329 if (E->isTypeDependent() || E->isValueDependent())
10330 return;
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010331
John McCallcc7e5bf2010-05-06 08:58:33 +000010332 // For conditional operators, we analyze the arguments as if they
10333 // were being fed directly into the output.
10334 if (isa<ConditionalOperator>(E)) {
10335 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +000010336 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010337 return;
10338 }
10339
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010340 // Check implicit argument conversions for function calls.
10341 if (CallExpr *Call = dyn_cast<CallExpr>(E))
10342 CheckImplicitArgumentConversions(S, Call, CC);
10343
John McCallcc7e5bf2010-05-06 08:58:33 +000010344 // Go ahead and check any implicit conversions we might have skipped.
10345 // The non-canonical typecheck is just an optimization;
10346 // CheckImplicitConversion will filter out dead implicit conversions.
10347 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000010348 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010349
10350 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +000010351
10352 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
10353 // The bound subexpressions in a PseudoObjectExpr are not reachable
10354 // as transitive children.
10355 // FIXME: Use a more uniform representation for this.
10356 for (auto *SE : POE->semantics())
10357 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
10358 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +000010359 }
Richard Smithd7bed4d2015-11-22 02:57:17 +000010360
John McCallcc7e5bf2010-05-06 08:58:33 +000010361 // Skip past explicit casts.
10362 if (isa<ExplicitCastExpr>(E)) {
10363 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +000010364 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010365 }
10366
John McCalld2a53122010-11-09 23:24:47 +000010367 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10368 // Do a somewhat different check with comparison operators.
10369 if (BO->isComparisonOp())
10370 return AnalyzeComparison(S, BO);
10371
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010372 // And with simple assignments.
10373 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +000010374 return AnalyzeAssignment(S, BO);
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010375 // And with compound assignments.
10376 if (BO->isAssignmentOp())
10377 return AnalyzeCompoundAssignment(S, BO);
John McCalld2a53122010-11-09 23:24:47 +000010378 }
John McCallcc7e5bf2010-05-06 08:58:33 +000010379
10380 // These break the otherwise-useful invariant below. Fortunately,
10381 // we don't really need to recurse into them, because any internal
10382 // expressions should have been analyzed already when they were
10383 // built into statements.
10384 if (isa<StmtExpr>(E)) return;
10385
10386 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +000010387 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +000010388
10389 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +000010390 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +000010391 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +000010392 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +000010393 for (Stmt *SubStmt : E->children()) {
10394 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +000010395 if (!ChildExpr)
10396 continue;
10397
Richard Trieu955231d2014-01-25 01:10:35 +000010398 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +000010399 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +000010400 // Ignore checking string literals that are in logical and operators.
10401 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +000010402 continue;
10403 AnalyzeImplicitConversions(S, ChildExpr, CC);
10404 }
Richard Trieu791b86e2014-11-19 06:08:18 +000010405
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010406 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +000010407 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
10408 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000010409 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +000010410
10411 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
10412 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000010413 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010414 }
Richard Trieu791b86e2014-11-19 06:08:18 +000010415
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010416 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
10417 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +000010418 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010419}
10420
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000010421/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000010422static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
10423 // Taking into account implicit conversions,
10424 // allow any integer.
10425 if (!E->getType()->isIntegerType()) {
10426 S.Diag(E->getLocStart(),
10427 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
10428 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010429 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000010430 // Potentially emit standard warnings for implicit conversions if enabled
10431 // using -Wconversion.
10432 CheckImplicitConversion(S, E, IntT, E->getLocStart());
10433 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010434}
10435
Richard Trieuc1888e02014-06-28 23:25:37 +000010436// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
10437// Returns true when emitting a warning about taking the address of a reference.
10438static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +000010439 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +000010440 E = E->IgnoreParenImpCasts();
10441
10442 const FunctionDecl *FD = nullptr;
10443
10444 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10445 if (!DRE->getDecl()->getType()->isReferenceType())
10446 return false;
10447 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10448 if (!M->getMemberDecl()->getType()->isReferenceType())
10449 return false;
10450 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +000010451 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +000010452 return false;
10453 FD = Call->getDirectCallee();
10454 } else {
10455 return false;
10456 }
10457
10458 SemaRef.Diag(E->getExprLoc(), PD);
10459
10460 // If possible, point to location of function.
10461 if (FD) {
10462 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
10463 }
10464
10465 return true;
10466}
10467
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010468// Returns true if the SourceLocation is expanded from any macro body.
10469// Returns false if the SourceLocation is invalid, is from not in a macro
10470// expansion, or is from expanded from a top-level macro argument.
10471static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
10472 if (Loc.isInvalid())
10473 return false;
10474
10475 while (Loc.isMacroID()) {
10476 if (SM.isMacroBodyExpansion(Loc))
10477 return true;
10478 Loc = SM.getImmediateMacroCallerLoc(Loc);
10479 }
10480
10481 return false;
10482}
10483
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010484/// Diagnose pointers that are always non-null.
Richard Trieu3bb8b562014-02-26 02:36:06 +000010485/// \param E the expression containing the pointer
10486/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
10487/// compared to a null pointer
10488/// \param IsEqual True when the comparison is equal to a null pointer
10489/// \param Range Extra SourceRange to highlight in the diagnostic
10490void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
10491 Expr::NullPointerConstantKind NullKind,
10492 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +000010493 if (!E)
10494 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010495
10496 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010497 if (E->getExprLoc().isMacroID()) {
10498 const SourceManager &SM = getSourceManager();
10499 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
10500 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +000010501 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010502 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010503 E = E->IgnoreImpCasts();
10504
10505 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10506
Richard Trieuf7432752014-06-06 21:39:26 +000010507 if (isa<CXXThisExpr>(E)) {
10508 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10509 : diag::warn_this_bool_conversion;
10510 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10511 return;
10512 }
10513
Richard Trieu3bb8b562014-02-26 02:36:06 +000010514 bool IsAddressOf = false;
10515
10516 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10517 if (UO->getOpcode() != UO_AddrOf)
10518 return;
10519 IsAddressOf = true;
10520 E = UO->getSubExpr();
10521 }
10522
Richard Trieuc1888e02014-06-28 23:25:37 +000010523 if (IsAddressOf) {
10524 unsigned DiagID = IsCompare
10525 ? diag::warn_address_of_reference_null_compare
10526 : diag::warn_address_of_reference_bool_conversion;
10527 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10528 << IsEqual;
10529 if (CheckForReference(*this, E, PD)) {
10530 return;
10531 }
10532 }
10533
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010534 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10535 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +000010536 std::string Str;
10537 llvm::raw_string_ostream S(Str);
10538 E->printPretty(S, nullptr, getPrintingPolicy());
10539 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10540 : diag::warn_cast_nonnull_to_bool;
10541 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10542 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010543 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +000010544 };
10545
10546 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10547 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10548 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010549 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10550 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010551 return;
10552 }
10553 }
10554 }
10555
Richard Trieu3bb8b562014-02-26 02:36:06 +000010556 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +000010557 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010558 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10559 D = R->getDecl();
10560 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10561 D = M->getMemberDecl();
10562 }
10563
10564 // Weak Decls can be null.
10565 if (!D || D->isWeak())
10566 return;
George Burgess IV850269a2015-12-08 22:02:00 +000010567
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010568 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +000010569 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10570 if (getCurFunction() &&
10571 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010572 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10573 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010574 return;
10575 }
10576
10577 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +000010578 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +000010579 assert(ParamIter != FD->param_end());
10580 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10581
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010582 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10583 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010584 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +000010585 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010586 }
George Burgess IV850269a2015-12-08 22:02:00 +000010587
Joel E. Denny81508102018-03-13 14:51:22 +000010588 for (const ParamIdx &ArgNo : NonNull->args()) {
10589 if (ArgNo.getASTIndex() == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010590 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010591 return;
10592 }
George Burgess IV850269a2015-12-08 22:02:00 +000010593 }
10594 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010595 }
10596 }
George Burgess IV850269a2015-12-08 22:02:00 +000010597 }
10598
Richard Trieu3bb8b562014-02-26 02:36:06 +000010599 QualType T = D->getType();
10600 const bool IsArray = T->isArrayType();
10601 const bool IsFunction = T->isFunctionType();
10602
Richard Trieuc1888e02014-06-28 23:25:37 +000010603 // Address of function is used to silence the function warning.
10604 if (IsAddressOf && IsFunction) {
10605 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010606 }
10607
10608 // Found nothing.
10609 if (!IsAddressOf && !IsFunction && !IsArray)
10610 return;
10611
10612 // Pretty print the expression for the diagnostic.
10613 std::string Str;
10614 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +000010615 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +000010616
10617 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10618 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +000010619 enum {
10620 AddressOf,
10621 FunctionPointer,
10622 ArrayPointer
10623 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010624 if (IsAddressOf)
10625 DiagType = AddressOf;
10626 else if (IsFunction)
10627 DiagType = FunctionPointer;
10628 else if (IsArray)
10629 DiagType = ArrayPointer;
10630 else
10631 llvm_unreachable("Could not determine diagnostic.");
10632 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10633 << Range << IsEqual;
10634
10635 if (!IsFunction)
10636 return;
10637
10638 // Suggest '&' to silence the function warning.
10639 Diag(E->getExprLoc(), diag::note_function_warning_silence)
10640 << FixItHint::CreateInsertion(E->getLocStart(), "&");
10641
10642 // Check to see if '()' fixit should be emitted.
10643 QualType ReturnType;
10644 UnresolvedSet<4> NonTemplateOverloads;
10645 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10646 if (ReturnType.isNull())
10647 return;
10648
10649 if (IsCompare) {
10650 // There are two cases here. If there is null constant, the only suggest
10651 // for a pointer return type. If the null is 0, then suggest if the return
10652 // type is a pointer or an integer type.
10653 if (!ReturnType->isPointerType()) {
10654 if (NullKind == Expr::NPCK_ZeroExpression ||
10655 NullKind == Expr::NPCK_ZeroLiteral) {
10656 if (!ReturnType->isIntegerType())
10657 return;
10658 } else {
10659 return;
10660 }
10661 }
10662 } else { // !IsCompare
10663 // For function to bool, only suggest if the function pointer has bool
10664 // return type.
10665 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10666 return;
10667 }
10668 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +000010669 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +000010670}
10671
John McCallcc7e5bf2010-05-06 08:58:33 +000010672/// Diagnoses "dangerous" implicit conversions within the given
10673/// expression (which is a full expression). Implements -Wconversion
10674/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +000010675///
10676/// \param CC the "context" location of the implicit conversion, i.e.
10677/// the most location of the syntactic entity requiring the implicit
10678/// conversion
10679void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010680 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +000010681 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +000010682 return;
10683
10684 // Don't diagnose for value- or type-dependent expressions.
10685 if (E->isTypeDependent() || E->isValueDependent())
10686 return;
10687
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010688 // Check for array bounds violations in cases where the check isn't triggered
10689 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10690 // ArraySubscriptExpr is on the RHS of a variable initialization.
10691 CheckArrayAccess(E);
10692
John McCallacf0ee52010-10-08 02:01:28 +000010693 // This is not the right CC for (e.g.) a variable initialization.
10694 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010695}
10696
Richard Trieu65724892014-11-15 06:37:39 +000010697/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10698/// Input argument E is a logical expression.
10699void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10700 ::CheckBoolLikeConversion(*this, E, CC);
10701}
10702
Richard Smith9f7df0c2017-06-26 23:19:32 +000010703/// Diagnose when expression is an integer constant expression and its evaluation
10704/// results in integer overflow
10705void Sema::CheckForIntOverflow (Expr *E) {
10706 // Use a work list to deal with nested struct initializers.
10707 SmallVector<Expr *, 2> Exprs(1, E);
10708
10709 do {
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010710 Expr *OriginalE = Exprs.pop_back_val();
10711 Expr *E = OriginalE->IgnoreParenCasts();
Richard Smith9f7df0c2017-06-26 23:19:32 +000010712
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010713 if (isa<BinaryOperator>(E)) {
10714 E->EvaluateForOverflow(Context);
Richard Smith9f7df0c2017-06-26 23:19:32 +000010715 continue;
10716 }
10717
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010718 if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
Richard Smith9f7df0c2017-06-26 23:19:32 +000010719 Exprs.append(InitList->inits().begin(), InitList->inits().end());
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010720 else if (isa<ObjCBoxedExpr>(OriginalE))
10721 E->EvaluateForOverflow(Context);
10722 else if (auto Call = dyn_cast<CallExpr>(E))
10723 Exprs.append(Call->arg_begin(), Call->arg_end());
10724 else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
10725 Exprs.append(Message->arg_begin(), Message->arg_end());
Richard Smith9f7df0c2017-06-26 23:19:32 +000010726 } while (!Exprs.empty());
10727}
10728
Richard Smithc406cb72013-01-17 01:17:56 +000010729namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010730
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010731/// Visitor for expressions which looks for unsequenced operations on the
Richard Smithc406cb72013-01-17 01:17:56 +000010732/// same object.
10733class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010734 using Base = EvaluatedExprVisitor<SequenceChecker>;
Richard Smithe3dbfe02013-06-30 10:40:20 +000010735
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010736 /// A tree of sequenced regions within an expression. Two regions are
Richard Smithc406cb72013-01-17 01:17:56 +000010737 /// unsequenced if one is an ancestor or a descendent of the other. When we
10738 /// finish processing an expression with sequencing, such as a comma
10739 /// expression, we fold its tree nodes into its parent, since they are
10740 /// unsequenced with respect to nodes we will visit later.
10741 class SequenceTree {
10742 struct Value {
10743 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10744 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +000010745 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +000010746 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010747 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +000010748
10749 public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010750 /// A region within an expression which may be sequenced with respect
Richard Smithc406cb72013-01-17 01:17:56 +000010751 /// to some other region.
10752 class Seq {
Richard Smithc406cb72013-01-17 01:17:56 +000010753 friend class SequenceTree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010754
10755 unsigned Index = 0;
10756
10757 explicit Seq(unsigned N) : Index(N) {}
10758
Richard Smithc406cb72013-01-17 01:17:56 +000010759 public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010760 Seq() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010761 };
10762
10763 SequenceTree() { Values.push_back(Value(0)); }
10764 Seq root() const { return Seq(0); }
10765
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010766 /// Create a new sequence of operations, which is an unsequenced
Richard Smithc406cb72013-01-17 01:17:56 +000010767 /// subset of \p Parent. This sequence of operations is sequenced with
10768 /// respect to other children of \p Parent.
10769 Seq allocate(Seq Parent) {
10770 Values.push_back(Value(Parent.Index));
10771 return Seq(Values.size() - 1);
10772 }
10773
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010774 /// Merge a sequence of operations into its parent.
Richard Smithc406cb72013-01-17 01:17:56 +000010775 void merge(Seq S) {
10776 Values[S.Index].Merged = true;
10777 }
10778
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010779 /// Determine whether two operations are unsequenced. This operation
Richard Smithc406cb72013-01-17 01:17:56 +000010780 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10781 /// should have been merged into its parent as appropriate.
10782 bool isUnsequenced(Seq Cur, Seq Old) {
10783 unsigned C = representative(Cur.Index);
10784 unsigned Target = representative(Old.Index);
10785 while (C >= Target) {
10786 if (C == Target)
10787 return true;
10788 C = Values[C].Parent;
10789 }
10790 return false;
10791 }
10792
10793 private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010794 /// Pick a representative for a sequence.
Richard Smithc406cb72013-01-17 01:17:56 +000010795 unsigned representative(unsigned K) {
10796 if (Values[K].Merged)
10797 // Perform path compression as we go.
10798 return Values[K].Parent = representative(Values[K].Parent);
10799 return K;
10800 }
10801 };
10802
10803 /// An object for which we can track unsequenced uses.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010804 using Object = NamedDecl *;
Richard Smithc406cb72013-01-17 01:17:56 +000010805
10806 /// Different flavors of object usage which we track. We only track the
10807 /// least-sequenced usage of each kind.
10808 enum UsageKind {
10809 /// A read of an object. Multiple unsequenced reads are OK.
10810 UK_Use,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010811
Richard Smithc406cb72013-01-17 01:17:56 +000010812 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000010813 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000010814 UK_ModAsValue,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010815
Richard Smithc406cb72013-01-17 01:17:56 +000010816 /// A modification of an object which is not sequenced before the value
10817 /// computation of the expression, such as n++.
10818 UK_ModAsSideEffect,
10819
10820 UK_Count = UK_ModAsSideEffect + 1
10821 };
10822
10823 struct Usage {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010824 Expr *Use = nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010825 SequenceTree::Seq Seq;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010826
10827 Usage() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010828 };
10829
10830 struct UsageInfo {
Richard Smithc406cb72013-01-17 01:17:56 +000010831 Usage Uses[UK_Count];
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010832
Richard Smithc406cb72013-01-17 01:17:56 +000010833 /// Have we issued a diagnostic for this variable already?
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010834 bool Diagnosed = false;
10835
10836 UsageInfo() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010837 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010838 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
Richard Smithc406cb72013-01-17 01:17:56 +000010839
10840 Sema &SemaRef;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010841
Richard Smithc406cb72013-01-17 01:17:56 +000010842 /// Sequenced regions within the expression.
10843 SequenceTree Tree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010844
Richard Smithc406cb72013-01-17 01:17:56 +000010845 /// Declaration modifications and references which we have seen.
10846 UsageInfoMap UsageMap;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010847
Richard Smithc406cb72013-01-17 01:17:56 +000010848 /// The region we are currently within.
10849 SequenceTree::Seq Region;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010850
Richard Smithc406cb72013-01-17 01:17:56 +000010851 /// Filled in with declarations which were modified as a side-effect
10852 /// (that is, post-increment operations).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010853 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
10854
Richard Smithd33f5202013-01-17 23:18:09 +000010855 /// Expressions to check later. We defer checking these to reduce
10856 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010857 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000010858
10859 /// RAII object wrapping the visitation of a sequenced subexpression of an
10860 /// expression. At the end of this process, the side-effects of the evaluation
10861 /// become sequenced with respect to the value computation of the result, so
10862 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10863 /// UK_ModAsValue.
10864 struct SequencedSubexpression {
10865 SequencedSubexpression(SequenceChecker &Self)
10866 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10867 Self.ModAsSideEffect = &ModAsSideEffect;
10868 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010869
Richard Smithc406cb72013-01-17 01:17:56 +000010870 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000010871 for (auto &M : llvm::reverse(ModAsSideEffect)) {
10872 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000010873 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000010874 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10875 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000010876 }
10877 Self.ModAsSideEffect = OldModAsSideEffect;
10878 }
10879
10880 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010881 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010882 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000010883 };
10884
Richard Smith40238f02013-06-20 22:21:56 +000010885 /// RAII object wrapping the visitation of a subexpression which we might
10886 /// choose to evaluate as a constant. If any subexpression is evaluated and
10887 /// found to be non-constant, this allows us to suppress the evaluation of
10888 /// the outer expression.
10889 class EvaluationTracker {
10890 public:
10891 EvaluationTracker(SequenceChecker &Self)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010892 : Self(Self), Prev(Self.EvalTracker) {
Richard Smith40238f02013-06-20 22:21:56 +000010893 Self.EvalTracker = this;
10894 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010895
Richard Smith40238f02013-06-20 22:21:56 +000010896 ~EvaluationTracker() {
10897 Self.EvalTracker = Prev;
10898 if (Prev)
10899 Prev->EvalOK &= EvalOK;
10900 }
10901
10902 bool evaluate(const Expr *E, bool &Result) {
10903 if (!EvalOK || E->isValueDependent())
10904 return false;
10905 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10906 return EvalOK;
10907 }
10908
10909 private:
10910 SequenceChecker &Self;
10911 EvaluationTracker *Prev;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010912 bool EvalOK = true;
10913 } *EvalTracker = nullptr;
Richard Smith40238f02013-06-20 22:21:56 +000010914
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010915 /// Find the object which is produced by the specified expression,
Richard Smithc406cb72013-01-17 01:17:56 +000010916 /// if any.
10917 Object getObject(Expr *E, bool Mod) const {
10918 E = E->IgnoreParenCasts();
10919 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10920 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10921 return getObject(UO->getSubExpr(), Mod);
10922 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10923 if (BO->getOpcode() == BO_Comma)
10924 return getObject(BO->getRHS(), Mod);
10925 if (Mod && BO->isAssignmentOp())
10926 return getObject(BO->getLHS(), Mod);
10927 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10928 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10929 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10930 return ME->getMemberDecl();
10931 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10932 // FIXME: If this is a reference, map through to its value.
10933 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000010934 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010935 }
10936
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010937 /// Note that an object was modified or used by an expression.
Richard Smithc406cb72013-01-17 01:17:56 +000010938 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10939 Usage &U = UI.Uses[UK];
10940 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10941 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10942 ModAsSideEffect->push_back(std::make_pair(O, U));
10943 U.Use = Ref;
10944 U.Seq = Region;
10945 }
10946 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010947
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010948 /// Check whether a modification or use conflicts with a prior usage.
Richard Smithc406cb72013-01-17 01:17:56 +000010949 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10950 bool IsModMod) {
10951 if (UI.Diagnosed)
10952 return;
10953
10954 const Usage &U = UI.Uses[OtherKind];
10955 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10956 return;
10957
10958 Expr *Mod = U.Use;
10959 Expr *ModOrUse = Ref;
10960 if (OtherKind == UK_Use)
10961 std::swap(Mod, ModOrUse);
10962
10963 SemaRef.Diag(Mod->getExprLoc(),
10964 IsModMod ? diag::warn_unsequenced_mod_mod
10965 : diag::warn_unsequenced_mod_use)
10966 << O << SourceRange(ModOrUse->getExprLoc());
10967 UI.Diagnosed = true;
10968 }
10969
10970 void notePreUse(Object O, Expr *Use) {
10971 UsageInfo &U = UsageMap[O];
10972 // Uses conflict with other modifications.
10973 checkUsage(O, U, Use, UK_ModAsValue, false);
10974 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010975
Richard Smithc406cb72013-01-17 01:17:56 +000010976 void notePostUse(Object O, Expr *Use) {
10977 UsageInfo &U = UsageMap[O];
10978 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10979 addUsage(U, O, Use, UK_Use);
10980 }
10981
10982 void notePreMod(Object O, Expr *Mod) {
10983 UsageInfo &U = UsageMap[O];
10984 // Modifications conflict with other modifications and with uses.
10985 checkUsage(O, U, Mod, UK_ModAsValue, true);
10986 checkUsage(O, U, Mod, UK_Use, false);
10987 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010988
Richard Smithc406cb72013-01-17 01:17:56 +000010989 void notePostMod(Object O, Expr *Use, UsageKind UK) {
10990 UsageInfo &U = UsageMap[O];
10991 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10992 addUsage(U, O, Use, UK);
10993 }
10994
10995public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010996 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010997 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
Richard Smithc406cb72013-01-17 01:17:56 +000010998 Visit(E);
10999 }
11000
11001 void VisitStmt(Stmt *S) {
11002 // Skip all statements which aren't expressions for now.
11003 }
11004
11005 void VisitExpr(Expr *E) {
11006 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000011007 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000011008 }
11009
11010 void VisitCastExpr(CastExpr *E) {
11011 Object O = Object();
11012 if (E->getCastKind() == CK_LValueToRValue)
11013 O = getObject(E->getSubExpr(), false);
11014
11015 if (O)
11016 notePreUse(O, E);
11017 VisitExpr(E);
11018 if (O)
11019 notePostUse(O, E);
11020 }
11021
11022 void VisitBinComma(BinaryOperator *BO) {
11023 // C++11 [expr.comma]p1:
11024 // Every value computation and side effect associated with the left
11025 // expression is sequenced before every value computation and side
11026 // effect associated with the right expression.
11027 SequenceTree::Seq LHS = Tree.allocate(Region);
11028 SequenceTree::Seq RHS = Tree.allocate(Region);
11029 SequenceTree::Seq OldRegion = Region;
11030
11031 {
11032 SequencedSubexpression SeqLHS(*this);
11033 Region = LHS;
11034 Visit(BO->getLHS());
11035 }
11036
11037 Region = RHS;
11038 Visit(BO->getRHS());
11039
11040 Region = OldRegion;
11041
11042 // Forget that LHS and RHS are sequenced. They are both unsequenced
11043 // with respect to other stuff.
11044 Tree.merge(LHS);
11045 Tree.merge(RHS);
11046 }
11047
11048 void VisitBinAssign(BinaryOperator *BO) {
11049 // The modification is sequenced after the value computation of the LHS
11050 // and RHS, so check it before inspecting the operands and update the
11051 // map afterwards.
11052 Object O = getObject(BO->getLHS(), true);
11053 if (!O)
11054 return VisitExpr(BO);
11055
11056 notePreMod(O, BO);
11057
11058 // C++11 [expr.ass]p7:
11059 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
11060 // only once.
11061 //
11062 // Therefore, for a compound assignment operator, O is considered used
11063 // everywhere except within the evaluation of E1 itself.
11064 if (isa<CompoundAssignOperator>(BO))
11065 notePreUse(O, BO);
11066
11067 Visit(BO->getLHS());
11068
11069 if (isa<CompoundAssignOperator>(BO))
11070 notePostUse(O, BO);
11071
11072 Visit(BO->getRHS());
11073
Richard Smith83e37bee2013-06-26 23:16:51 +000011074 // C++11 [expr.ass]p1:
11075 // the assignment is sequenced [...] before the value computation of the
11076 // assignment expression.
11077 // C11 6.5.16/3 has no such rule.
11078 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11079 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000011080 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011081
Richard Smithc406cb72013-01-17 01:17:56 +000011082 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
11083 VisitBinAssign(CAO);
11084 }
11085
11086 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11087 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11088 void VisitUnaryPreIncDec(UnaryOperator *UO) {
11089 Object O = getObject(UO->getSubExpr(), true);
11090 if (!O)
11091 return VisitExpr(UO);
11092
11093 notePreMod(O, UO);
11094 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000011095 // C++11 [expr.pre.incr]p1:
11096 // the expression ++x is equivalent to x+=1
11097 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11098 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000011099 }
11100
11101 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11102 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11103 void VisitUnaryPostIncDec(UnaryOperator *UO) {
11104 Object O = getObject(UO->getSubExpr(), true);
11105 if (!O)
11106 return VisitExpr(UO);
11107
11108 notePreMod(O, UO);
11109 Visit(UO->getSubExpr());
11110 notePostMod(O, UO, UK_ModAsSideEffect);
11111 }
11112
11113 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
11114 void VisitBinLOr(BinaryOperator *BO) {
11115 // The side-effects of the LHS of an '&&' are sequenced before the
11116 // value computation of the RHS, and hence before the value computation
11117 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
11118 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000011119 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000011120 {
11121 SequencedSubexpression Sequenced(*this);
11122 Visit(BO->getLHS());
11123 }
11124
11125 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011126 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000011127 if (!Result)
11128 Visit(BO->getRHS());
11129 } else {
11130 // Check for unsequenced operations in the RHS, treating it as an
11131 // entirely separate evaluation.
11132 //
11133 // FIXME: If there are operations in the RHS which are unsequenced
11134 // with respect to operations outside the RHS, and those operations
11135 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000011136 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000011137 }
Richard Smithc406cb72013-01-17 01:17:56 +000011138 }
11139 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000011140 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000011141 {
11142 SequencedSubexpression Sequenced(*this);
11143 Visit(BO->getLHS());
11144 }
11145
11146 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011147 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000011148 if (Result)
11149 Visit(BO->getRHS());
11150 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000011151 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000011152 }
Richard Smithc406cb72013-01-17 01:17:56 +000011153 }
11154
11155 // Only visit the condition, unless we can be sure which subexpression will
11156 // be chosen.
11157 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000011158 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000011159 {
11160 SequencedSubexpression Sequenced(*this);
11161 Visit(CO->getCond());
11162 }
Richard Smithc406cb72013-01-17 01:17:56 +000011163
11164 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011165 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000011166 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000011167 else {
Richard Smithd33f5202013-01-17 23:18:09 +000011168 WorkList.push_back(CO->getTrueExpr());
11169 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000011170 }
Richard Smithc406cb72013-01-17 01:17:56 +000011171 }
11172
Richard Smithe3dbfe02013-06-30 10:40:20 +000011173 void VisitCallExpr(CallExpr *CE) {
11174 // C++11 [intro.execution]p15:
11175 // When calling a function [...], every value computation and side effect
11176 // associated with any argument expression, or with the postfix expression
11177 // designating the called function, is sequenced before execution of every
11178 // expression or statement in the body of the function [and thus before
11179 // the value computation of its result].
11180 SequencedSubexpression Sequenced(*this);
11181 Base::VisitCallExpr(CE);
11182
11183 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
11184 }
11185
Richard Smithc406cb72013-01-17 01:17:56 +000011186 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000011187 // This is a call, so all subexpressions are sequenced before the result.
11188 SequencedSubexpression Sequenced(*this);
11189
Richard Smithc406cb72013-01-17 01:17:56 +000011190 if (!CCE->isListInitialization())
11191 return VisitExpr(CCE);
11192
11193 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011194 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000011195 SequenceTree::Seq Parent = Region;
11196 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
11197 E = CCE->arg_end();
11198 I != E; ++I) {
11199 Region = Tree.allocate(Parent);
11200 Elts.push_back(Region);
11201 Visit(*I);
11202 }
11203
11204 // Forget that the initializers are sequenced.
11205 Region = Parent;
11206 for (unsigned I = 0; I < Elts.size(); ++I)
11207 Tree.merge(Elts[I]);
11208 }
11209
11210 void VisitInitListExpr(InitListExpr *ILE) {
11211 if (!SemaRef.getLangOpts().CPlusPlus11)
11212 return VisitExpr(ILE);
11213
11214 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011215 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000011216 SequenceTree::Seq Parent = Region;
11217 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
11218 Expr *E = ILE->getInit(I);
11219 if (!E) continue;
11220 Region = Tree.allocate(Parent);
11221 Elts.push_back(Region);
11222 Visit(E);
11223 }
11224
11225 // Forget that the initializers are sequenced.
11226 Region = Parent;
11227 for (unsigned I = 0; I < Elts.size(); ++I)
11228 Tree.merge(Elts[I]);
11229 }
11230};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011231
11232} // namespace
Richard Smithc406cb72013-01-17 01:17:56 +000011233
11234void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011235 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000011236 WorkList.push_back(E);
11237 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000011238 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000011239 SequenceChecker(*this, Item, WorkList);
11240 }
Richard Smithc406cb72013-01-17 01:17:56 +000011241}
11242
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011243void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
11244 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000011245 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000011246 if (!E->isInstantiationDependent())
11247 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011248 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000011249 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011250 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000011251}
11252
John McCall1f425642010-11-11 03:21:53 +000011253void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
11254 FieldDecl *BitField,
11255 Expr *Init) {
11256 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
11257}
11258
David Majnemer61a5bbf2015-04-07 22:08:51 +000011259static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
11260 SourceLocation Loc) {
11261 if (!PType->isVariablyModifiedType())
11262 return;
11263 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
11264 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
11265 return;
11266 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000011267 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
11268 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
11269 return;
11270 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000011271 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
11272 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
11273 return;
11274 }
11275
11276 const ArrayType *AT = S.Context.getAsArrayType(PType);
11277 if (!AT)
11278 return;
11279
11280 if (AT->getSizeModifier() != ArrayType::Star) {
11281 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
11282 return;
11283 }
11284
11285 S.Diag(Loc, diag::err_array_star_in_function_definition);
11286}
11287
Mike Stump0c2ec772010-01-21 03:59:47 +000011288/// CheckParmsForFunctionDef - Check that the parameters of the given
11289/// function are appropriate for the definition of a function. This
11290/// takes care of any checks that cannot be performed on the
11291/// declaration itself, e.g., that the types of each of the function
11292/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000011293bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000011294 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011295 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000011296 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011297 // C99 6.7.5.3p4: the parameters in a parameter type list in a
11298 // function declarator that is part of a function definition of
11299 // that function shall not have incomplete type.
11300 //
11301 // This is also C++ [dcl.fct]p6.
11302 if (!Param->isInvalidDecl() &&
11303 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011304 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011305 Param->setInvalidDecl();
11306 HasInvalidParm = true;
11307 }
11308
11309 // C99 6.9.1p5: If the declarator includes a parameter type list, the
11310 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000011311 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000011312 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000011313 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000011314 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000011315 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000011316
11317 // C99 6.7.5.3p12:
11318 // If the function declarator is not part of a definition of that
11319 // function, parameters may have incomplete type and may use the [*]
11320 // notation in their sequences of declarator specifiers to specify
11321 // variable length array types.
11322 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000011323 // FIXME: This diagnostic should point the '[*]' if source-location
11324 // information is added for it.
11325 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000011326
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011327 // If the parameter is a c++ class type and it has to be destructed in the
11328 // callee function, declare the destructor so that it can be called by the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000011329 // callee function. Do not perform any direct access check on the dtor here.
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011330 if (!Param->isInvalidDecl()) {
11331 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
11332 if (!ClassDecl->isInvalidDecl() &&
11333 !ClassDecl->hasIrrelevantDestructor() &&
11334 !ClassDecl->isDependentContext() &&
Akira Hatanaka85282972018-05-15 21:00:30 +000011335 ClassDecl->isParamDestroyedInCallee()) {
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011336 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11337 MarkFunctionReferenced(Param->getLocation(), Destructor);
11338 DiagnoseUseOfDecl(Destructor, Param->getLocation());
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000011339 }
11340 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000011341 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011342
11343 // Parameters with the pass_object_size attribute only need to be marked
11344 // constant at function definitions. Because we lack information about
11345 // whether we're on a declaration or definition when we're instantiating the
11346 // attribute, we need to check for constness here.
11347 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
11348 if (!Param->getType().isConstQualified())
11349 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
11350 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000011351 }
11352
11353 return HasInvalidParm;
11354}
John McCall2b5c1b22010-08-12 21:44:57 +000011355
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000011356/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
11357/// or MemberExpr.
11358static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
11359 ASTContext &Context) {
11360 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
11361 return Context.getDeclAlign(DRE->getDecl());
11362
11363 if (const auto *ME = dyn_cast<MemberExpr>(E))
11364 return Context.getDeclAlign(ME->getMemberDecl());
11365
11366 return TypeAlign;
11367}
11368
John McCall2b5c1b22010-08-12 21:44:57 +000011369/// CheckCastAlign - Implements -Wcast-align, which warns when a
11370/// pointer cast increases the alignment requirements.
11371void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
11372 // This is actually a lot of work to potentially be doing on every
11373 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011374 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000011375 return;
11376
11377 // Ignore dependent types.
11378 if (T->isDependentType() || Op->getType()->isDependentType())
11379 return;
11380
11381 // Require that the destination be a pointer type.
11382 const PointerType *DestPtr = T->getAs<PointerType>();
11383 if (!DestPtr) return;
11384
11385 // If the destination has alignment 1, we're done.
11386 QualType DestPointee = DestPtr->getPointeeType();
11387 if (DestPointee->isIncompleteType()) return;
11388 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
11389 if (DestAlign.isOne()) return;
11390
11391 // Require that the source be a pointer type.
11392 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
11393 if (!SrcPtr) return;
11394 QualType SrcPointee = SrcPtr->getPointeeType();
11395
11396 // Whitelist casts from cv void*. We already implicitly
11397 // whitelisted casts to cv void*, since they have alignment 1.
11398 // Also whitelist casts involving incomplete types, which implicitly
11399 // includes 'void'.
11400 if (SrcPointee->isIncompleteType()) return;
11401
11402 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000011403
11404 if (auto *CE = dyn_cast<CastExpr>(Op)) {
11405 if (CE->getCastKind() == CK_ArrayToPointerDecay)
11406 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
11407 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
11408 if (UO->getOpcode() == UO_AddrOf)
11409 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
11410 }
11411
John McCall2b5c1b22010-08-12 21:44:57 +000011412 if (SrcAlign >= DestAlign) return;
11413
11414 Diag(TRange.getBegin(), diag::warn_cast_align)
11415 << Op->getType() << T
11416 << static_cast<unsigned>(SrcAlign.getQuantity())
11417 << static_cast<unsigned>(DestAlign.getQuantity())
11418 << TRange << Op->getSourceRange();
11419}
11420
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011421/// Check whether this array fits the idiom of a size-one tail padded
Chandler Carruth28389f02011-08-05 09:10:50 +000011422/// array member of a struct.
11423///
11424/// We avoid emitting out-of-bounds access warnings for such arrays as they are
11425/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000011426static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000011427 const NamedDecl *ND) {
11428 if (Size != 1 || !ND) return false;
11429
11430 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
11431 if (!FD) return false;
11432
11433 // Don't consider sizes resulting from macro expansions or template argument
11434 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000011435
11436 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011437 while (TInfo) {
11438 TypeLoc TL = TInfo->getTypeLoc();
11439 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000011440 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
11441 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011442 TInfo = TDL->getTypeSourceInfo();
11443 continue;
11444 }
David Blaikie6adc78e2013-02-18 22:06:02 +000011445 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
11446 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000011447 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
11448 return false;
11449 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011450 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000011451 }
Chandler Carruth28389f02011-08-05 09:10:50 +000011452
11453 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000011454 if (!RD) return false;
11455 if (RD->isUnion()) return false;
11456 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11457 if (!CRD->isStandardLayout()) return false;
11458 }
Chandler Carruth28389f02011-08-05 09:10:50 +000011459
Benjamin Kramer8c543672011-08-06 03:04:42 +000011460 // See if this is the last field decl in the record.
11461 const Decl *D = FD;
11462 while ((D = D->getNextDeclInContext()))
11463 if (isa<FieldDecl>(D))
11464 return false;
11465 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000011466}
11467
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011468void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011469 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000011470 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011471 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011472 if (IndexExpr->isValueDependent())
11473 return;
11474
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011475 const Type *EffectiveType =
11476 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011477 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011478 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011479 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011480 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000011481 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000011482
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011483 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000011484 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000011485 return;
Richard Smith13f67182011-12-16 19:31:14 +000011486 if (IndexNegated)
11487 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000011488
Craig Topperc3ec1492014-05-26 06:22:03 +000011489 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000011490 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011491 ND = DRE->getDecl();
Chandler Carruth28389f02011-08-05 09:10:50 +000011492 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011493 ND = ME->getMemberDecl();
Chandler Carruth126b1552011-08-05 08:07:29 +000011494
Ted Kremeneke4b316c2011-02-23 23:06:04 +000011495 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011496 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000011497 if (!size.isStrictlyPositive())
11498 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011499
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011500 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000011501 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011502 // Make sure we're comparing apples to apples when comparing index to size
11503 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
11504 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000011505 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000011506 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011507 if (ptrarith_typesize != array_typesize) {
11508 // There's a cast to a different size type involved
11509 uint64_t ratio = array_typesize / ptrarith_typesize;
11510 // TODO: Be smarter about handling cases where array_typesize is not a
11511 // multiple of ptrarith_typesize
11512 if (ptrarith_typesize * ratio == array_typesize)
11513 size *= llvm::APInt(size.getBitWidth(), ratio);
11514 }
11515 }
11516
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011517 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011518 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011519 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011520 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011521
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011522 // For array subscripting the index must be less than size, but for pointer
11523 // arithmetic also allow the index (offset) to be equal to size since
11524 // computing the next address after the end of the array is legal and
11525 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011526 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000011527 return;
11528
11529 // Also don't warn for arrays of size 1 which are members of some
11530 // structure. These are often used to approximate flexible arrays in C89
11531 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011532 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000011533 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011534
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011535 // Suppress the warning if the subscript expression (as identified by the
11536 // ']' location) and the index expression are both from macro expansions
11537 // within a system header.
11538 if (ASE) {
11539 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11540 ASE->getRBracketLoc());
11541 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11542 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11543 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000011544 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011545 return;
11546 }
11547 }
11548
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011549 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011550 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011551 DiagID = diag::warn_array_index_exceeds_bounds;
11552
11553 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11554 PDiag(DiagID) << index.toString(10, true)
11555 << size.toString(10, true)
11556 << (unsigned)size.getLimitedValue(~0U)
11557 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011558 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011559 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011560 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011561 DiagID = diag::warn_ptr_arith_precedes_bounds;
11562 if (index.isNegative()) index = -index;
11563 }
11564
11565 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11566 PDiag(DiagID) << index.toString(10, true)
11567 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000011568 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000011569
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011570 if (!ND) {
11571 // Try harder to find a NamedDecl to point at in the note.
11572 while (const ArraySubscriptExpr *ASE =
11573 dyn_cast<ArraySubscriptExpr>(BaseExpr))
11574 BaseExpr = ASE->getBase()->IgnoreParenCasts();
11575 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011576 ND = DRE->getDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011577 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011578 ND = ME->getMemberDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011579 }
11580
Chandler Carruth1af88f12011-02-17 21:10:52 +000011581 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011582 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11583 PDiag(diag::note_array_index_out_of_bounds)
11584 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000011585}
11586
Ted Kremenekdf26df72011-03-01 18:41:00 +000011587void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011588 int AllowOnePastEnd = 0;
11589 while (expr) {
11590 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000011591 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011592 case Stmt::ArraySubscriptExprClass: {
11593 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011594 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011595 AllowOnePastEnd > 0);
Aaron Ballman93c6ba12018-04-24 19:21:04 +000011596 expr = ASE->getBase();
11597 break;
11598 }
11599 case Stmt::MemberExprClass: {
11600 expr = cast<MemberExpr>(expr)->getBase();
11601 break;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011602 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000011603 case Stmt::OMPArraySectionExprClass: {
11604 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11605 if (ASE->getLowerBound())
11606 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11607 /*ASE=*/nullptr, AllowOnePastEnd > 0);
11608 return;
11609 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011610 case Stmt::UnaryOperatorClass: {
11611 // Only unwrap the * and & unary operators
11612 const UnaryOperator *UO = cast<UnaryOperator>(expr);
11613 expr = UO->getSubExpr();
11614 switch (UO->getOpcode()) {
11615 case UO_AddrOf:
11616 AllowOnePastEnd++;
11617 break;
11618 case UO_Deref:
11619 AllowOnePastEnd--;
11620 break;
11621 default:
11622 return;
11623 }
11624 break;
11625 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011626 case Stmt::ConditionalOperatorClass: {
11627 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11628 if (const Expr *lhs = cond->getLHS())
11629 CheckArrayAccess(lhs);
11630 if (const Expr *rhs = cond->getRHS())
11631 CheckArrayAccess(rhs);
11632 return;
11633 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000011634 case Stmt::CXXOperatorCallExprClass: {
11635 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11636 for (const auto *Arg : OCE->arguments())
11637 CheckArrayAccess(Arg);
11638 return;
11639 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011640 default:
11641 return;
11642 }
Peter Collingbourne91147592011-04-15 00:35:48 +000011643 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011644}
John McCall31168b02011-06-15 23:02:42 +000011645
11646//===--- CHECK: Objective-C retain cycles ----------------------------------//
11647
11648namespace {
John McCall31168b02011-06-15 23:02:42 +000011649
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011650struct RetainCycleOwner {
11651 VarDecl *Variable = nullptr;
11652 SourceRange Range;
11653 SourceLocation Loc;
11654 bool Indirect = false;
11655
11656 RetainCycleOwner() = default;
11657
11658 void setLocsFrom(Expr *e) {
11659 Loc = e->getExprLoc();
11660 Range = e->getSourceRange();
11661 }
11662};
11663
11664} // namespace
John McCall31168b02011-06-15 23:02:42 +000011665
11666/// Consider whether capturing the given variable can possibly lead to
11667/// a retain cycle.
11668static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000011669 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000011670 // lifetime. In MRR, it's captured strongly if the variable is
11671 // __block and has an appropriate type.
11672 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11673 return false;
11674
11675 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011676 if (ref)
11677 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000011678 return true;
11679}
11680
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011681static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000011682 while (true) {
11683 e = e->IgnoreParens();
11684 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11685 switch (cast->getCastKind()) {
11686 case CK_BitCast:
11687 case CK_LValueBitCast:
11688 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000011689 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000011690 e = cast->getSubExpr();
11691 continue;
11692
John McCall31168b02011-06-15 23:02:42 +000011693 default:
11694 return false;
11695 }
11696 }
11697
11698 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11699 ObjCIvarDecl *ivar = ref->getDecl();
11700 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11701 return false;
11702
11703 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011704 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000011705 return false;
11706
11707 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11708 owner.Indirect = true;
11709 return true;
11710 }
11711
11712 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11713 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11714 if (!var) return false;
11715 return considerVariable(var, ref, owner);
11716 }
11717
John McCall31168b02011-06-15 23:02:42 +000011718 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11719 if (member->isArrow()) return false;
11720
11721 // Don't count this as an indirect ownership.
11722 e = member->getBase();
11723 continue;
11724 }
11725
John McCallfe96e0b2011-11-06 09:01:30 +000011726 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11727 // Only pay attention to pseudo-objects on property references.
11728 ObjCPropertyRefExpr *pre
11729 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11730 ->IgnoreParens());
11731 if (!pre) return false;
11732 if (pre->isImplicitProperty()) return false;
11733 ObjCPropertyDecl *property = pre->getExplicitProperty();
11734 if (!property->isRetaining() &&
11735 !(property->getPropertyIvarDecl() &&
11736 property->getPropertyIvarDecl()->getType()
11737 .getObjCLifetime() == Qualifiers::OCL_Strong))
11738 return false;
11739
11740 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011741 if (pre->isSuperReceiver()) {
11742 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11743 if (!owner.Variable)
11744 return false;
11745 owner.Loc = pre->getLocation();
11746 owner.Range = pre->getSourceRange();
11747 return true;
11748 }
John McCallfe96e0b2011-11-06 09:01:30 +000011749 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11750 ->getSourceExpr());
11751 continue;
11752 }
11753
John McCall31168b02011-06-15 23:02:42 +000011754 // Array ivars?
11755
11756 return false;
11757 }
11758}
11759
11760namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011761
John McCall31168b02011-06-15 23:02:42 +000011762 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011763 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000011764 VarDecl *Variable;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011765 Expr *Capturer = nullptr;
11766 bool VarWillBeReased = false;
11767
11768 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11769 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11770 Context(Context), Variable(variable) {}
John McCall31168b02011-06-15 23:02:42 +000011771
11772 void VisitDeclRefExpr(DeclRefExpr *ref) {
11773 if (ref->getDecl() == Variable && !Capturer)
11774 Capturer = ref;
11775 }
11776
John McCall31168b02011-06-15 23:02:42 +000011777 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11778 if (Capturer) return;
11779 Visit(ref->getBase());
11780 if (Capturer && ref->isFreeIvar())
11781 Capturer = ref;
11782 }
11783
11784 void VisitBlockExpr(BlockExpr *block) {
11785 // Look inside nested blocks
11786 if (block->getBlockDecl()->capturesVariable(Variable))
11787 Visit(block->getBlockDecl()->getBody());
11788 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000011789
11790 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11791 if (Capturer) return;
11792 if (OVE->getSourceExpr())
11793 Visit(OVE->getSourceExpr());
11794 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011795
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011796 void VisitBinaryOperator(BinaryOperator *BinOp) {
11797 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11798 return;
11799 Expr *LHS = BinOp->getLHS();
11800 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11801 if (DRE->getDecl() != Variable)
11802 return;
11803 if (Expr *RHS = BinOp->getRHS()) {
11804 RHS = RHS->IgnoreParenCasts();
11805 llvm::APSInt Value;
11806 VarWillBeReased =
11807 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11808 }
11809 }
11810 }
John McCall31168b02011-06-15 23:02:42 +000011811 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011812
11813} // namespace
John McCall31168b02011-06-15 23:02:42 +000011814
11815/// Check whether the given argument is a block which captures a
11816/// variable.
11817static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11818 assert(owner.Variable && owner.Loc.isValid());
11819
11820 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000011821
11822 // Look through [^{...} copy] and Block_copy(^{...}).
11823 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11824 Selector Cmd = ME->getSelector();
11825 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11826 e = ME->getInstanceReceiver();
11827 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000011828 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000011829 e = e->IgnoreParenCasts();
11830 }
11831 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11832 if (CE->getNumArgs() == 1) {
11833 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000011834 if (Fn) {
11835 const IdentifierInfo *FnI = Fn->getIdentifier();
11836 if (FnI && FnI->isStr("_Block_copy")) {
11837 e = CE->getArg(0)->IgnoreParenCasts();
11838 }
11839 }
Jordan Rose67e887c2012-09-17 17:54:30 +000011840 }
11841 }
11842
John McCall31168b02011-06-15 23:02:42 +000011843 BlockExpr *block = dyn_cast<BlockExpr>(e);
11844 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000011845 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011846
11847 FindCaptureVisitor visitor(S.Context, owner.Variable);
11848 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011849 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000011850}
11851
11852static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11853 RetainCycleOwner &owner) {
11854 assert(capturer);
11855 assert(owner.Variable && owner.Loc.isValid());
11856
11857 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11858 << owner.Variable << capturer->getSourceRange();
11859 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11860 << owner.Indirect << owner.Range;
11861}
11862
11863/// Check for a keyword selector that starts with the word 'add' or
11864/// 'set'.
11865static bool isSetterLikeSelector(Selector sel) {
11866 if (sel.isUnarySelector()) return false;
11867
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011868 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000011869 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011870 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000011871 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011872 else if (str.startswith("add")) {
11873 // Specially whitelist 'addOperationWithBlock:'.
11874 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11875 return false;
11876 str = str.substr(3);
11877 }
John McCall31168b02011-06-15 23:02:42 +000011878 else
11879 return false;
11880
11881 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000011882 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000011883}
11884
Benjamin Kramer3a743452015-03-09 15:03:32 +000011885static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11886 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011887 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11888 Message->getReceiverInterface(),
11889 NSAPI::ClassId_NSMutableArray);
11890 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011891 return None;
11892 }
11893
11894 Selector Sel = Message->getSelector();
11895
11896 Optional<NSAPI::NSArrayMethodKind> MKOpt =
11897 S.NSAPIObj->getNSArrayMethodKind(Sel);
11898 if (!MKOpt) {
11899 return None;
11900 }
11901
11902 NSAPI::NSArrayMethodKind MK = *MKOpt;
11903
11904 switch (MK) {
11905 case NSAPI::NSMutableArr_addObject:
11906 case NSAPI::NSMutableArr_insertObjectAtIndex:
11907 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11908 return 0;
11909 case NSAPI::NSMutableArr_replaceObjectAtIndex:
11910 return 1;
11911
11912 default:
11913 return None;
11914 }
11915
11916 return None;
11917}
11918
11919static
11920Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11921 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011922 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11923 Message->getReceiverInterface(),
11924 NSAPI::ClassId_NSMutableDictionary);
11925 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011926 return None;
11927 }
11928
11929 Selector Sel = Message->getSelector();
11930
11931 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11932 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11933 if (!MKOpt) {
11934 return None;
11935 }
11936
11937 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11938
11939 switch (MK) {
11940 case NSAPI::NSMutableDict_setObjectForKey:
11941 case NSAPI::NSMutableDict_setValueForKey:
11942 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11943 return 0;
11944
11945 default:
11946 return None;
11947 }
11948
11949 return None;
11950}
11951
11952static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011953 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11954 Message->getReceiverInterface(),
11955 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000011956
Alex Denisov5dfac812015-08-06 04:51:14 +000011957 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11958 Message->getReceiverInterface(),
11959 NSAPI::ClassId_NSMutableOrderedSet);
11960 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011961 return None;
11962 }
11963
11964 Selector Sel = Message->getSelector();
11965
11966 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11967 if (!MKOpt) {
11968 return None;
11969 }
11970
11971 NSAPI::NSSetMethodKind MK = *MKOpt;
11972
11973 switch (MK) {
11974 case NSAPI::NSMutableSet_addObject:
11975 case NSAPI::NSOrderedSet_setObjectAtIndex:
11976 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11977 case NSAPI::NSOrderedSet_insertObjectAtIndex:
11978 return 0;
11979 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11980 return 1;
11981 }
11982
11983 return None;
11984}
11985
11986void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11987 if (!Message->isInstanceMessage()) {
11988 return;
11989 }
11990
11991 Optional<int> ArgOpt;
11992
11993 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11994 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11995 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11996 return;
11997 }
11998
11999 int ArgIndex = *ArgOpt;
12000
Alex Denisove1d882c2015-03-04 17:55:52 +000012001 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
12002 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
12003 Arg = OE->getSourceExpr()->IgnoreImpCasts();
12004 }
12005
Alex Denisov5dfac812015-08-06 04:51:14 +000012006 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012007 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012008 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012009 Diag(Message->getSourceRange().getBegin(),
12010 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012011 << ArgRE->getDecl() << StringRef("'super'");
Alex Denisove1d882c2015-03-04 17:55:52 +000012012 }
12013 }
Alex Denisov5dfac812015-08-06 04:51:14 +000012014 } else {
12015 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
12016
12017 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
12018 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
12019 }
12020
12021 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
12022 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
12023 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
12024 ValueDecl *Decl = ReceiverRE->getDecl();
12025 Diag(Message->getSourceRange().getBegin(),
12026 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012027 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012028 if (!ArgRE->isObjCSelfExpr()) {
12029 Diag(Decl->getLocation(),
12030 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000012031 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012032 }
12033 }
12034 }
12035 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
12036 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
12037 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
12038 ObjCIvarDecl *Decl = IvarRE->getDecl();
12039 Diag(Message->getSourceRange().getBegin(),
12040 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012041 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012042 Diag(Decl->getLocation(),
12043 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000012044 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012045 }
Alex Denisove1d882c2015-03-04 17:55:52 +000012046 }
12047 }
12048 }
Alex Denisove1d882c2015-03-04 17:55:52 +000012049}
12050
John McCall31168b02011-06-15 23:02:42 +000012051/// Check a message send to see if it's likely to cause a retain cycle.
12052void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
12053 // Only check instance methods whose selector looks like a setter.
12054 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
12055 return;
12056
12057 // Try to find a variable that the receiver is strongly owned by.
12058 RetainCycleOwner owner;
12059 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012060 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000012061 return;
12062 } else {
12063 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
12064 owner.Variable = getCurMethodDecl()->getSelfDecl();
12065 owner.Loc = msg->getSuperLoc();
12066 owner.Range = msg->getSuperLoc();
12067 }
12068
12069 // Check whether the receiver is captured by any of the arguments.
Alex Lorenz42a97a92017-11-17 20:44:25 +000012070 const ObjCMethodDecl *MD = msg->getMethodDecl();
12071 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
12072 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
12073 // noescape blocks should not be retained by the method.
12074 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
12075 continue;
John McCall31168b02011-06-15 23:02:42 +000012076 return diagnoseRetainCycle(*this, capturer, owner);
Alex Lorenz42a97a92017-11-17 20:44:25 +000012077 }
12078 }
John McCall31168b02011-06-15 23:02:42 +000012079}
12080
12081/// Check a property assign to see if it's likely to cause a retain cycle.
12082void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
12083 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012084 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000012085 return;
12086
12087 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
12088 diagnoseRetainCycle(*this, capturer, owner);
12089}
12090
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012091void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
12092 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000012093 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012094 return;
12095
12096 // Because we don't have an expression for the variable, we have to set the
12097 // location explicitly here.
12098 Owner.Loc = Var->getLocation();
12099 Owner.Range = Var->getSourceRange();
12100
12101 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
12102 diagnoseRetainCycle(*this, Capturer, Owner);
12103}
12104
Ted Kremenek9304da92012-12-21 08:04:28 +000012105static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
12106 Expr *RHS, bool isProperty) {
12107 // Check if RHS is an Objective-C object literal, which also can get
12108 // immediately zapped in a weak reference. Note that we explicitly
12109 // allow ObjCStringLiterals, since those are designed to never really die.
12110 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012111
Ted Kremenek64873352012-12-21 22:46:35 +000012112 // This enum needs to match with the 'select' in
12113 // warn_objc_arc_literal_assign (off-by-1).
12114 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
12115 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
12116 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012117
12118 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000012119 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000012120 << (isProperty ? 0 : 1)
12121 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012122
12123 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000012124}
12125
Ted Kremenekc1f014a2012-12-21 19:45:30 +000012126static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
12127 Qualifiers::ObjCLifetime LT,
12128 Expr *RHS, bool isProperty) {
12129 // Strip off any implicit cast added to get to the one ARC-specific.
12130 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
12131 if (cast->getCastKind() == CK_ARCConsumeObject) {
12132 S.Diag(Loc, diag::warn_arc_retained_assign)
12133 << (LT == Qualifiers::OCL_ExplicitNone)
12134 << (isProperty ? 0 : 1)
12135 << RHS->getSourceRange();
12136 return true;
12137 }
12138 RHS = cast->getSubExpr();
12139 }
12140
12141 if (LT == Qualifiers::OCL_Weak &&
12142 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
12143 return true;
12144
12145 return false;
12146}
12147
Ted Kremenekb36234d2012-12-21 08:04:20 +000012148bool Sema::checkUnsafeAssigns(SourceLocation Loc,
12149 QualType LHS, Expr *RHS) {
12150 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
12151
12152 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
12153 return false;
12154
12155 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
12156 return true;
12157
12158 return false;
12159}
12160
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012161void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
12162 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012163 QualType LHSType;
12164 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000012165 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012166 ObjCPropertyRefExpr *PRE
12167 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
12168 if (PRE && !PRE->isImplicitProperty()) {
12169 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12170 if (PD)
12171 LHSType = PD->getType();
12172 }
12173
12174 if (LHSType.isNull())
12175 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000012176
12177 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
12178
12179 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012180 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000012181 getCurFunction()->markSafeWeakUse(LHS);
12182 }
12183
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012184 if (checkUnsafeAssigns(Loc, LHSType, RHS))
12185 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000012186
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012187 // FIXME. Check for other life times.
12188 if (LT != Qualifiers::OCL_None)
12189 return;
12190
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012191 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012192 if (PRE->isImplicitProperty())
12193 return;
12194 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12195 if (!PD)
12196 return;
12197
Bill Wendling44426052012-12-20 19:22:21 +000012198 unsigned Attributes = PD->getPropertyAttributes();
12199 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012200 // when 'assign' attribute was not explicitly specified
12201 // by user, ignore it and rely on property type itself
12202 // for lifetime info.
12203 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
12204 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
12205 LHSType->isObjCRetainableType())
12206 return;
12207
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012208 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000012209 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012210 Diag(Loc, diag::warn_arc_retained_property_assign)
12211 << RHS->getSourceRange();
12212 return;
12213 }
12214 RHS = cast->getSubExpr();
12215 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012216 }
Bill Wendling44426052012-12-20 19:22:21 +000012217 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000012218 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
12219 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000012220 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012221 }
12222}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012223
12224//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
12225
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012226static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
12227 SourceLocation StmtLoc,
12228 const NullStmt *Body) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012229 // Do not warn if the body is a macro that expands to nothing, e.g:
12230 //
12231 // #define CALL(x)
12232 // if (condition)
12233 // CALL(0);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012234 if (Body->hasLeadingEmptyMacro())
12235 return false;
12236
12237 // Get line numbers of statement and body.
12238 bool StmtLineInvalid;
Hans Wennborg95419752017-11-20 17:38:16 +000012239 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012240 &StmtLineInvalid);
12241 if (StmtLineInvalid)
12242 return false;
12243
12244 bool BodyLineInvalid;
12245 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
12246 &BodyLineInvalid);
12247 if (BodyLineInvalid)
12248 return false;
12249
12250 // Warn if null statement and body are on the same line.
12251 if (StmtLine != BodyLine)
12252 return false;
12253
12254 return true;
12255}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012256
12257void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
12258 const Stmt *Body,
12259 unsigned DiagID) {
12260 // Since this is a syntactic check, don't emit diagnostic for template
12261 // instantiations, this just adds noise.
12262 if (CurrentInstantiationScope)
12263 return;
12264
12265 // The body should be a null statement.
12266 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
12267 if (!NBody)
12268 return;
12269
12270 // Do the usual checks.
12271 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12272 return;
12273
12274 Diag(NBody->getSemiLoc(), DiagID);
12275 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12276}
12277
12278void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
12279 const Stmt *PossibleBody) {
12280 assert(!CurrentInstantiationScope); // Ensured by caller
12281
12282 SourceLocation StmtLoc;
12283 const Stmt *Body;
12284 unsigned DiagID;
12285 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
12286 StmtLoc = FS->getRParenLoc();
12287 Body = FS->getBody();
12288 DiagID = diag::warn_empty_for_body;
12289 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
12290 StmtLoc = WS->getCond()->getSourceRange().getEnd();
12291 Body = WS->getBody();
12292 DiagID = diag::warn_empty_while_body;
12293 } else
12294 return; // Neither `for' nor `while'.
12295
12296 // The body should be a null statement.
12297 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
12298 if (!NBody)
12299 return;
12300
12301 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012302 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012303 return;
12304
12305 // Do the usual checks.
12306 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12307 return;
12308
12309 // `for(...);' and `while(...);' are popular idioms, so in order to keep
12310 // noise level low, emit diagnostics only if for/while is followed by a
12311 // CompoundStmt, e.g.:
12312 // for (int i = 0; i < n; i++);
12313 // {
12314 // a(i);
12315 // }
12316 // or if for/while is followed by a statement with more indentation
12317 // than for/while itself:
12318 // for (int i = 0; i < n; i++);
12319 // a(i);
12320 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
12321 if (!ProbableTypo) {
12322 bool BodyColInvalid;
12323 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
12324 PossibleBody->getLocStart(),
12325 &BodyColInvalid);
12326 if (BodyColInvalid)
12327 return;
12328
12329 bool StmtColInvalid;
12330 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
12331 S->getLocStart(),
12332 &StmtColInvalid);
12333 if (StmtColInvalid)
12334 return;
12335
12336 if (BodyCol > StmtCol)
12337 ProbableTypo = true;
12338 }
12339
12340 if (ProbableTypo) {
12341 Diag(NBody->getSemiLoc(), DiagID);
12342 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12343 }
12344}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012345
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012346//===--- CHECK: Warn on self move with std::move. -------------------------===//
12347
12348/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
12349void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
12350 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012351 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
12352 return;
12353
Richard Smith51ec0cf2017-02-21 01:17:38 +000012354 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012355 return;
12356
12357 // Strip parens and casts away.
12358 LHSExpr = LHSExpr->IgnoreParenImpCasts();
12359 RHSExpr = RHSExpr->IgnoreParenImpCasts();
12360
12361 // Check for a call expression
12362 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
12363 if (!CE || CE->getNumArgs() != 1)
12364 return;
12365
12366 // Check for a call to std::move
Nico Weberb688d132017-09-28 16:16:39 +000012367 if (!CE->isCallToStdMove())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012368 return;
12369
12370 // Get argument from std::move
12371 RHSExpr = CE->getArg(0);
12372
12373 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12374 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12375
12376 // Two DeclRefExpr's, check that the decls are the same.
12377 if (LHSDeclRef && RHSDeclRef) {
12378 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12379 return;
12380 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12381 RHSDeclRef->getDecl()->getCanonicalDecl())
12382 return;
12383
12384 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12385 << LHSExpr->getSourceRange()
12386 << RHSExpr->getSourceRange();
12387 return;
12388 }
12389
12390 // Member variables require a different approach to check for self moves.
12391 // MemberExpr's are the same if every nested MemberExpr refers to the same
12392 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
12393 // the base Expr's are CXXThisExpr's.
12394 const Expr *LHSBase = LHSExpr;
12395 const Expr *RHSBase = RHSExpr;
12396 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
12397 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
12398 if (!LHSME || !RHSME)
12399 return;
12400
12401 while (LHSME && RHSME) {
12402 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
12403 RHSME->getMemberDecl()->getCanonicalDecl())
12404 return;
12405
12406 LHSBase = LHSME->getBase();
12407 RHSBase = RHSME->getBase();
12408 LHSME = dyn_cast<MemberExpr>(LHSBase);
12409 RHSME = dyn_cast<MemberExpr>(RHSBase);
12410 }
12411
12412 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
12413 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
12414 if (LHSDeclRef && RHSDeclRef) {
12415 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12416 return;
12417 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12418 RHSDeclRef->getDecl()->getCanonicalDecl())
12419 return;
12420
12421 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12422 << LHSExpr->getSourceRange()
12423 << RHSExpr->getSourceRange();
12424 return;
12425 }
12426
12427 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
12428 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12429 << LHSExpr->getSourceRange()
12430 << RHSExpr->getSourceRange();
12431}
12432
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012433//===--- Layout compatibility ----------------------------------------------//
12434
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012435static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012436
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012437/// Check if two enumeration types are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012438static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012439 // C++11 [dcl.enum] p8:
12440 // Two enumeration types are layout-compatible if they have the same
12441 // underlying type.
12442 return ED1->isComplete() && ED2->isComplete() &&
12443 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
12444}
12445
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012446/// Check if two fields are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012447static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
12448 FieldDecl *Field2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012449 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
12450 return false;
12451
12452 if (Field1->isBitField() != Field2->isBitField())
12453 return false;
12454
12455 if (Field1->isBitField()) {
12456 // Make sure that the bit-fields are the same length.
12457 unsigned Bits1 = Field1->getBitWidthValue(C);
12458 unsigned Bits2 = Field2->getBitWidthValue(C);
12459
12460 if (Bits1 != Bits2)
12461 return false;
12462 }
12463
12464 return true;
12465}
12466
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012467/// Check if two standard-layout structs are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012468/// (C++11 [class.mem] p17)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012469static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
12470 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012471 // If both records are C++ classes, check that base classes match.
12472 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
12473 // If one of records is a CXXRecordDecl we are in C++ mode,
12474 // thus the other one is a CXXRecordDecl, too.
12475 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
12476 // Check number of base classes.
12477 if (D1CXX->getNumBases() != D2CXX->getNumBases())
12478 return false;
12479
12480 // Check the base classes.
12481 for (CXXRecordDecl::base_class_const_iterator
12482 Base1 = D1CXX->bases_begin(),
12483 BaseEnd1 = D1CXX->bases_end(),
12484 Base2 = D2CXX->bases_begin();
12485 Base1 != BaseEnd1;
12486 ++Base1, ++Base2) {
12487 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
12488 return false;
12489 }
12490 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
12491 // If only RD2 is a C++ class, it should have zero base classes.
12492 if (D2CXX->getNumBases() > 0)
12493 return false;
12494 }
12495
12496 // Check the fields.
12497 RecordDecl::field_iterator Field2 = RD2->field_begin(),
12498 Field2End = RD2->field_end(),
12499 Field1 = RD1->field_begin(),
12500 Field1End = RD1->field_end();
12501 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
12502 if (!isLayoutCompatible(C, *Field1, *Field2))
12503 return false;
12504 }
12505 if (Field1 != Field1End || Field2 != Field2End)
12506 return false;
12507
12508 return true;
12509}
12510
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012511/// Check if two standard-layout unions are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012512/// (C++11 [class.mem] p18)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012513static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
12514 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012515 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012516 for (auto *Field2 : RD2->fields())
12517 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012518
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012519 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012520 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12521 I = UnmatchedFields.begin(),
12522 E = UnmatchedFields.end();
12523
12524 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012525 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012526 bool Result = UnmatchedFields.erase(*I);
12527 (void) Result;
12528 assert(Result);
12529 break;
12530 }
12531 }
12532 if (I == E)
12533 return false;
12534 }
12535
12536 return UnmatchedFields.empty();
12537}
12538
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012539static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
12540 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012541 if (RD1->isUnion() != RD2->isUnion())
12542 return false;
12543
12544 if (RD1->isUnion())
12545 return isLayoutCompatibleUnion(C, RD1, RD2);
12546 else
12547 return isLayoutCompatibleStruct(C, RD1, RD2);
12548}
12549
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012550/// Check if two types are layout-compatible in C++11 sense.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012551static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012552 if (T1.isNull() || T2.isNull())
12553 return false;
12554
12555 // C++11 [basic.types] p11:
12556 // If two types T1 and T2 are the same type, then T1 and T2 are
12557 // layout-compatible types.
12558 if (C.hasSameType(T1, T2))
12559 return true;
12560
12561 T1 = T1.getCanonicalType().getUnqualifiedType();
12562 T2 = T2.getCanonicalType().getUnqualifiedType();
12563
12564 const Type::TypeClass TC1 = T1->getTypeClass();
12565 const Type::TypeClass TC2 = T2->getTypeClass();
12566
12567 if (TC1 != TC2)
12568 return false;
12569
12570 if (TC1 == Type::Enum) {
12571 return isLayoutCompatible(C,
12572 cast<EnumType>(T1)->getDecl(),
12573 cast<EnumType>(T2)->getDecl());
12574 } else if (TC1 == Type::Record) {
12575 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12576 return false;
12577
12578 return isLayoutCompatible(C,
12579 cast<RecordType>(T1)->getDecl(),
12580 cast<RecordType>(T2)->getDecl());
12581 }
12582
12583 return false;
12584}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012585
12586//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12587
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012588/// Given a type tag expression find the type tag itself.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012589///
12590/// \param TypeExpr Type tag expression, as it appears in user's code.
12591///
12592/// \param VD Declaration of an identifier that appears in a type tag.
12593///
12594/// \param MagicValue Type tag magic value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012595static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12596 const ValueDecl **VD, uint64_t *MagicValue) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012597 while(true) {
12598 if (!TypeExpr)
12599 return false;
12600
12601 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12602
12603 switch (TypeExpr->getStmtClass()) {
12604 case Stmt::UnaryOperatorClass: {
12605 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12606 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12607 TypeExpr = UO->getSubExpr();
12608 continue;
12609 }
12610 return false;
12611 }
12612
12613 case Stmt::DeclRefExprClass: {
12614 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12615 *VD = DRE->getDecl();
12616 return true;
12617 }
12618
12619 case Stmt::IntegerLiteralClass: {
12620 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12621 llvm::APInt MagicValueAPInt = IL->getValue();
12622 if (MagicValueAPInt.getActiveBits() <= 64) {
12623 *MagicValue = MagicValueAPInt.getZExtValue();
12624 return true;
12625 } else
12626 return false;
12627 }
12628
12629 case Stmt::BinaryConditionalOperatorClass:
12630 case Stmt::ConditionalOperatorClass: {
12631 const AbstractConditionalOperator *ACO =
12632 cast<AbstractConditionalOperator>(TypeExpr);
12633 bool Result;
12634 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12635 if (Result)
12636 TypeExpr = ACO->getTrueExpr();
12637 else
12638 TypeExpr = ACO->getFalseExpr();
12639 continue;
12640 }
12641 return false;
12642 }
12643
12644 case Stmt::BinaryOperatorClass: {
12645 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12646 if (BO->getOpcode() == BO_Comma) {
12647 TypeExpr = BO->getRHS();
12648 continue;
12649 }
12650 return false;
12651 }
12652
12653 default:
12654 return false;
12655 }
12656 }
12657}
12658
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012659/// Retrieve the C type corresponding to type tag TypeExpr.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012660///
12661/// \param TypeExpr Expression that specifies a type tag.
12662///
12663/// \param MagicValues Registered magic values.
12664///
12665/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12666/// kind.
12667///
12668/// \param TypeInfo Information about the corresponding C type.
12669///
12670/// \returns true if the corresponding C type was found.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012671static bool GetMatchingCType(
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012672 const IdentifierInfo *ArgumentKind,
12673 const Expr *TypeExpr, const ASTContext &Ctx,
12674 const llvm::DenseMap<Sema::TypeTagMagicValue,
12675 Sema::TypeTagData> *MagicValues,
12676 bool &FoundWrongKind,
12677 Sema::TypeTagData &TypeInfo) {
12678 FoundWrongKind = false;
12679
12680 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000012681 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012682
12683 uint64_t MagicValue;
12684
12685 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12686 return false;
12687
12688 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000012689 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012690 if (I->getArgumentKind() != ArgumentKind) {
12691 FoundWrongKind = true;
12692 return false;
12693 }
12694 TypeInfo.Type = I->getMatchingCType();
12695 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12696 TypeInfo.MustBeNull = I->getMustBeNull();
12697 return true;
12698 }
12699 return false;
12700 }
12701
12702 if (!MagicValues)
12703 return false;
12704
12705 llvm::DenseMap<Sema::TypeTagMagicValue,
12706 Sema::TypeTagData>::const_iterator I =
12707 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12708 if (I == MagicValues->end())
12709 return false;
12710
12711 TypeInfo = I->second;
12712 return true;
12713}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012714
12715void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12716 uint64_t MagicValue, QualType Type,
12717 bool LayoutCompatible,
12718 bool MustBeNull) {
12719 if (!TypeTagForDatatypeMagicValues)
12720 TypeTagForDatatypeMagicValues.reset(
12721 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12722
12723 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12724 (*TypeTagForDatatypeMagicValues)[Magic] =
12725 TypeTagData(Type, LayoutCompatible, MustBeNull);
12726}
12727
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012728static bool IsSameCharType(QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012729 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12730 if (!BT1)
12731 return false;
12732
12733 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12734 if (!BT2)
12735 return false;
12736
12737 BuiltinType::Kind T1Kind = BT1->getKind();
12738 BuiltinType::Kind T2Kind = BT2->getKind();
12739
12740 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
12741 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
12742 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12743 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12744}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012745
12746void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012747 const ArrayRef<const Expr *> ExprArgs,
12748 SourceLocation CallSiteLoc) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012749 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12750 bool IsPointerAttr = Attr->getIsPointer();
12751
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012752 // Retrieve the argument representing the 'type_tag'.
Joel E. Denny81508102018-03-13 14:51:22 +000012753 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
12754 if (TypeTagIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012755 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000012756 << 0 << Attr->getTypeTagIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012757 return;
12758 }
Joel E. Denny81508102018-03-13 14:51:22 +000012759 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012760 bool FoundWrongKind;
12761 TypeTagData TypeInfo;
12762 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12763 TypeTagForDatatypeMagicValues.get(),
12764 FoundWrongKind, TypeInfo)) {
12765 if (FoundWrongKind)
12766 Diag(TypeTagExpr->getExprLoc(),
12767 diag::warn_type_tag_for_datatype_wrong_kind)
12768 << TypeTagExpr->getSourceRange();
12769 return;
12770 }
12771
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012772 // Retrieve the argument representing the 'arg_idx'.
Joel E. Denny81508102018-03-13 14:51:22 +000012773 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
12774 if (ArgumentIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012775 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000012776 << 1 << Attr->getArgumentIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012777 return;
12778 }
Joel E. Denny81508102018-03-13 14:51:22 +000012779 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012780 if (IsPointerAttr) {
12781 // Skip implicit cast of pointer to `void *' (as a function argument).
12782 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000012783 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000012784 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012785 ArgumentExpr = ICE->getSubExpr();
12786 }
12787 QualType ArgumentType = ArgumentExpr->getType();
12788
12789 // Passing a `void*' pointer shouldn't trigger a warning.
12790 if (IsPointerAttr && ArgumentType->isVoidPointerType())
12791 return;
12792
12793 if (TypeInfo.MustBeNull) {
12794 // Type tag with matching void type requires a null pointer.
12795 if (!ArgumentExpr->isNullPointerConstant(Context,
12796 Expr::NPC_ValueDependentIsNotNull)) {
12797 Diag(ArgumentExpr->getExprLoc(),
12798 diag::warn_type_safety_null_pointer_required)
12799 << ArgumentKind->getName()
12800 << ArgumentExpr->getSourceRange()
12801 << TypeTagExpr->getSourceRange();
12802 }
12803 return;
12804 }
12805
12806 QualType RequiredType = TypeInfo.Type;
12807 if (IsPointerAttr)
12808 RequiredType = Context.getPointerType(RequiredType);
12809
12810 bool mismatch = false;
12811 if (!TypeInfo.LayoutCompatible) {
12812 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12813
12814 // C++11 [basic.fundamental] p1:
12815 // Plain char, signed char, and unsigned char are three distinct types.
12816 //
12817 // But we treat plain `char' as equivalent to `signed char' or `unsigned
12818 // char' depending on the current char signedness mode.
12819 if (mismatch)
12820 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12821 RequiredType->getPointeeType())) ||
12822 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12823 mismatch = false;
12824 } else
12825 if (IsPointerAttr)
12826 mismatch = !isLayoutCompatible(Context,
12827 ArgumentType->getPointeeType(),
12828 RequiredType->getPointeeType());
12829 else
12830 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12831
12832 if (mismatch)
12833 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000012834 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012835 << TypeInfo.LayoutCompatible << RequiredType
12836 << ArgumentExpr->getSourceRange()
12837 << TypeTagExpr->getSourceRange();
12838}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012839
12840void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12841 CharUnits Alignment) {
12842 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12843}
12844
12845void Sema::DiagnoseMisalignedMembers() {
12846 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000012847 const NamedDecl *ND = m.RD;
12848 if (ND->getName().empty()) {
12849 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12850 ND = TD;
12851 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012852 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000012853 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012854 }
12855 MisalignedMembers.clear();
12856}
12857
12858void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012859 E = E->IgnoreParens();
12860 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012861 return;
12862 if (isa<UnaryOperator>(E) &&
12863 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12864 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12865 if (isa<MemberExpr>(Op)) {
12866 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12867 MisalignedMember(Op));
12868 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012869 (T->isIntegerType() ||
Roger Ferrer Ibanezd80d6c52017-12-07 09:23:50 +000012870 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
12871 Context.getTypeAlignInChars(
12872 T->getPointeeType()) <= MA->Alignment))))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012873 MisalignedMembers.erase(MA);
12874 }
12875 }
12876}
12877
12878void Sema::RefersToMemberWithReducedAlignment(
12879 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000012880 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12881 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012882 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012883 if (!ME)
12884 return;
12885
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000012886 // No need to check expressions with an __unaligned-qualified type.
12887 if (E->getType().getQualifiers().hasUnaligned())
12888 return;
12889
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012890 // For a chain of MemberExpr like "a.b.c.d" this list
12891 // will keep FieldDecl's like [d, c, b].
12892 SmallVector<FieldDecl *, 4> ReverseMemberChain;
12893 const MemberExpr *TopME = nullptr;
12894 bool AnyIsPacked = false;
12895 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012896 QualType BaseType = ME->getBase()->getType();
12897 if (ME->isArrow())
12898 BaseType = BaseType->getPointeeType();
12899 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000012900 if (RD->isInvalidDecl())
12901 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012902
12903 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012904 auto *FD = dyn_cast<FieldDecl>(MD);
12905 // We do not care about non-data members.
12906 if (!FD || FD->isInvalidDecl())
12907 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012908
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012909 AnyIsPacked =
12910 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12911 ReverseMemberChain.push_back(FD);
12912
12913 TopME = ME;
12914 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12915 } while (ME);
12916 assert(TopME && "We did not compute a topmost MemberExpr!");
12917
12918 // Not the scope of this diagnostic.
12919 if (!AnyIsPacked)
12920 return;
12921
12922 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12923 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12924 // TODO: The innermost base of the member expression may be too complicated.
12925 // For now, just disregard these cases. This is left for future
12926 // improvement.
12927 if (!DRE && !isa<CXXThisExpr>(TopBase))
12928 return;
12929
12930 // Alignment expected by the whole expression.
12931 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12932
12933 // No need to do anything else with this case.
12934 if (ExpectedAlignment.isOne())
12935 return;
12936
12937 // Synthesize offset of the whole access.
12938 CharUnits Offset;
12939 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12940 I++) {
12941 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12942 }
12943
12944 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12945 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12946 ReverseMemberChain.back()->getParent()->getTypeForDecl());
12947
12948 // The base expression of the innermost MemberExpr may give
12949 // stronger guarantees than the class containing the member.
12950 if (DRE && !TopME->isArrow()) {
12951 const ValueDecl *VD = DRE->getDecl();
12952 if (!VD->getType()->isReferenceType())
12953 CompleteObjectAlignment =
12954 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12955 }
12956
12957 // Check if the synthesized offset fulfills the alignment.
12958 if (Offset % ExpectedAlignment != 0 ||
12959 // It may fulfill the offset it but the effective alignment may still be
12960 // lower than the expected expression alignment.
12961 CompleteObjectAlignment < ExpectedAlignment) {
12962 // If this happens, we want to determine a sensible culprit of this.
12963 // Intuitively, watching the chain of member expressions from right to
12964 // left, we start with the required alignment (as required by the field
12965 // type) but some packed attribute in that chain has reduced the alignment.
12966 // It may happen that another packed structure increases it again. But if
12967 // we are here such increase has not been enough. So pointing the first
12968 // FieldDecl that either is packed or else its RecordDecl is,
12969 // seems reasonable.
12970 FieldDecl *FD = nullptr;
12971 CharUnits Alignment;
12972 for (FieldDecl *FDI : ReverseMemberChain) {
12973 if (FDI->hasAttr<PackedAttr>() ||
12974 FDI->getParent()->hasAttr<PackedAttr>()) {
12975 FD = FDI;
12976 Alignment = std::min(
12977 Context.getTypeAlignInChars(FD->getType()),
12978 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12979 break;
12980 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012981 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012982 assert(FD && "We did not find a packed FieldDecl!");
12983 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012984 }
12985}
12986
12987void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12988 using namespace std::placeholders;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012989
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012990 RefersToMemberWithReducedAlignment(
12991 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12992 _2, _3, _4));
12993}