blob: 417422d2b4c7ea660bd0dc1d75ff8b3268fd6584 [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
Reid Kleckneraa46ed92018-06-07 21:39:04 +0000854// Emit an error and return true if the current architecture is not in the list
855// of supported architectures.
856static bool
857CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
858 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
859 llvm::Triple::ArchType CurArch =
860 S.getASTContext().getTargetInfo().getTriple().getArch();
861 if (llvm::is_contained(SupportedArchs, CurArch))
862 return false;
863 S.Diag(TheCall->getLocStart(), diag::err_builtin_target_unsupported)
864 << TheCall->getSourceRange();
865 return true;
866}
867
John McCalldadc5752010-08-24 06:29:42 +0000868ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000869Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
870 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000871 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000872
Chris Lattner3be167f2010-10-01 23:23:24 +0000873 // Find out if any arguments are required to be integer constant expressions.
874 unsigned ICEArguments = 0;
875 ASTContext::GetBuiltinTypeError Error;
876 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
877 if (Error != ASTContext::GE_None)
878 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
879
880 // If any arguments are required to be ICE's, check and diagnose.
881 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
882 // Skip arguments not required to be ICE's.
883 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
884
885 llvm::APSInt Result;
886 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
887 return true;
888 ICEArguments &= ~(1 << ArgNo);
889 }
890
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000891 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000892 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000893 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000894 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000895 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000896 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000897 break;
Martin Storsjo022e7822017-07-17 20:49:45 +0000898 case Builtin::BI__builtin_ms_va_start:
Ted Kremeneka174c522008-07-09 17:58:53 +0000899 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000900 case Builtin::BI__builtin_va_start:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000901 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000902 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000903 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000904 case Builtin::BI__va_start: {
905 switch (Context.getTargetInfo().getTriple().getArch()) {
906 case llvm::Triple::arm:
907 case llvm::Triple::thumb:
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +0000908 if (SemaBuiltinVAStartARMMicrosoft(TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000909 return ExprError();
910 break;
911 default:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000912 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000913 return ExprError();
914 break;
915 }
916 break;
917 }
Reid Kleckneraa46ed92018-06-07 21:39:04 +0000918
919 // The acquire, release, and no fence variants are ARM and AArch64 only.
920 case Builtin::BI_interlockedbittestandset_acq:
921 case Builtin::BI_interlockedbittestandset_rel:
922 case Builtin::BI_interlockedbittestandset_nf:
923 case Builtin::BI_interlockedbittestandreset_acq:
924 case Builtin::BI_interlockedbittestandreset_rel:
925 case Builtin::BI_interlockedbittestandreset_nf:
926 if (CheckBuiltinTargetSupport(
927 *this, BuiltinID, TheCall,
928 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
929 return ExprError();
930 break;
931
932 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
933 case Builtin::BI_bittest64:
934 case Builtin::BI_bittestandcomplement64:
935 case Builtin::BI_bittestandreset64:
936 case Builtin::BI_bittestandset64:
937 case Builtin::BI_interlockedbittestandreset64:
938 case Builtin::BI_interlockedbittestandset64:
939 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
940 {llvm::Triple::x86_64, llvm::Triple::arm,
941 llvm::Triple::thumb, llvm::Triple::aarch64}))
942 return ExprError();
943 break;
944
Chris Lattner2da14fb2007-12-20 00:26:33 +0000945 case Builtin::BI__builtin_isgreater:
946 case Builtin::BI__builtin_isgreaterequal:
947 case Builtin::BI__builtin_isless:
948 case Builtin::BI__builtin_islessequal:
949 case Builtin::BI__builtin_islessgreater:
950 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000951 if (SemaBuiltinUnorderedCompare(TheCall))
952 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000953 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000954 case Builtin::BI__builtin_fpclassify:
955 if (SemaBuiltinFPClassification(TheCall, 6))
956 return ExprError();
957 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000958 case Builtin::BI__builtin_isfinite:
959 case Builtin::BI__builtin_isinf:
960 case Builtin::BI__builtin_isinf_sign:
961 case Builtin::BI__builtin_isnan:
962 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000963 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000964 return ExprError();
965 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000966 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000967 return SemaBuiltinShuffleVector(TheCall);
968 // TheCall will be freed by the smart pointer here, but that's fine, since
969 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000970 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000971 if (SemaBuiltinPrefetch(TheCall))
972 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000973 break;
David Majnemer51169932016-10-31 05:37:48 +0000974 case Builtin::BI__builtin_alloca_with_align:
975 if (SemaBuiltinAllocaWithAlign(TheCall))
976 return ExprError();
977 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000978 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000979 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000980 if (SemaBuiltinAssume(TheCall))
981 return ExprError();
982 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000983 case Builtin::BI__builtin_assume_aligned:
984 if (SemaBuiltinAssumeAligned(TheCall))
985 return ExprError();
986 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000987 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000988 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000989 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000990 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000991 case Builtin::BI__builtin_longjmp:
992 if (SemaBuiltinLongjmp(TheCall))
993 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000994 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000995 case Builtin::BI__builtin_setjmp:
996 if (SemaBuiltinSetjmp(TheCall))
997 return ExprError();
998 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000999 case Builtin::BI_setjmp:
1000 case Builtin::BI_setjmpex:
1001 if (checkArgCount(*this, TheCall, 1))
1002 return true;
1003 break;
John McCallbebede42011-02-26 05:39:39 +00001004 case Builtin::BI__builtin_classify_type:
1005 if (checkArgCount(*this, TheCall, 1)) return true;
1006 TheCall->setType(Context.IntTy);
1007 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +00001008 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +00001009 if (checkArgCount(*this, TheCall, 1)) return true;
1010 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +00001011 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001012 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +00001013 case Builtin::BI__sync_fetch_and_add_1:
1014 case Builtin::BI__sync_fetch_and_add_2:
1015 case Builtin::BI__sync_fetch_and_add_4:
1016 case Builtin::BI__sync_fetch_and_add_8:
1017 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001018 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +00001019 case Builtin::BI__sync_fetch_and_sub_1:
1020 case Builtin::BI__sync_fetch_and_sub_2:
1021 case Builtin::BI__sync_fetch_and_sub_4:
1022 case Builtin::BI__sync_fetch_and_sub_8:
1023 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001024 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +00001025 case Builtin::BI__sync_fetch_and_or_1:
1026 case Builtin::BI__sync_fetch_and_or_2:
1027 case Builtin::BI__sync_fetch_and_or_4:
1028 case Builtin::BI__sync_fetch_and_or_8:
1029 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001030 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +00001031 case Builtin::BI__sync_fetch_and_and_1:
1032 case Builtin::BI__sync_fetch_and_and_2:
1033 case Builtin::BI__sync_fetch_and_and_4:
1034 case Builtin::BI__sync_fetch_and_and_8:
1035 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001036 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +00001037 case Builtin::BI__sync_fetch_and_xor_1:
1038 case Builtin::BI__sync_fetch_and_xor_2:
1039 case Builtin::BI__sync_fetch_and_xor_4:
1040 case Builtin::BI__sync_fetch_and_xor_8:
1041 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001042 case Builtin::BI__sync_fetch_and_nand:
1043 case Builtin::BI__sync_fetch_and_nand_1:
1044 case Builtin::BI__sync_fetch_and_nand_2:
1045 case Builtin::BI__sync_fetch_and_nand_4:
1046 case Builtin::BI__sync_fetch_and_nand_8:
1047 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001048 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001049 case Builtin::BI__sync_add_and_fetch_1:
1050 case Builtin::BI__sync_add_and_fetch_2:
1051 case Builtin::BI__sync_add_and_fetch_4:
1052 case Builtin::BI__sync_add_and_fetch_8:
1053 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001054 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001055 case Builtin::BI__sync_sub_and_fetch_1:
1056 case Builtin::BI__sync_sub_and_fetch_2:
1057 case Builtin::BI__sync_sub_and_fetch_4:
1058 case Builtin::BI__sync_sub_and_fetch_8:
1059 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001060 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001061 case Builtin::BI__sync_and_and_fetch_1:
1062 case Builtin::BI__sync_and_and_fetch_2:
1063 case Builtin::BI__sync_and_and_fetch_4:
1064 case Builtin::BI__sync_and_and_fetch_8:
1065 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001066 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001067 case Builtin::BI__sync_or_and_fetch_1:
1068 case Builtin::BI__sync_or_and_fetch_2:
1069 case Builtin::BI__sync_or_and_fetch_4:
1070 case Builtin::BI__sync_or_and_fetch_8:
1071 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001072 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001073 case Builtin::BI__sync_xor_and_fetch_1:
1074 case Builtin::BI__sync_xor_and_fetch_2:
1075 case Builtin::BI__sync_xor_and_fetch_4:
1076 case Builtin::BI__sync_xor_and_fetch_8:
1077 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001078 case Builtin::BI__sync_nand_and_fetch:
1079 case Builtin::BI__sync_nand_and_fetch_1:
1080 case Builtin::BI__sync_nand_and_fetch_2:
1081 case Builtin::BI__sync_nand_and_fetch_4:
1082 case Builtin::BI__sync_nand_and_fetch_8:
1083 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001084 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001085 case Builtin::BI__sync_val_compare_and_swap_1:
1086 case Builtin::BI__sync_val_compare_and_swap_2:
1087 case Builtin::BI__sync_val_compare_and_swap_4:
1088 case Builtin::BI__sync_val_compare_and_swap_8:
1089 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001090 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001091 case Builtin::BI__sync_bool_compare_and_swap_1:
1092 case Builtin::BI__sync_bool_compare_and_swap_2:
1093 case Builtin::BI__sync_bool_compare_and_swap_4:
1094 case Builtin::BI__sync_bool_compare_and_swap_8:
1095 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001096 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +00001097 case Builtin::BI__sync_lock_test_and_set_1:
1098 case Builtin::BI__sync_lock_test_and_set_2:
1099 case Builtin::BI__sync_lock_test_and_set_4:
1100 case Builtin::BI__sync_lock_test_and_set_8:
1101 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001102 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001103 case Builtin::BI__sync_lock_release_1:
1104 case Builtin::BI__sync_lock_release_2:
1105 case Builtin::BI__sync_lock_release_4:
1106 case Builtin::BI__sync_lock_release_8:
1107 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001108 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001109 case Builtin::BI__sync_swap_1:
1110 case Builtin::BI__sync_swap_2:
1111 case Builtin::BI__sync_swap_4:
1112 case Builtin::BI__sync_swap_8:
1113 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001114 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001115 case Builtin::BI__builtin_nontemporal_load:
1116 case Builtin::BI__builtin_nontemporal_store:
1117 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +00001118#define BUILTIN(ID, TYPE, ATTRS)
1119#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1120 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001121 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +00001122#include "clang/Basic/Builtins.def"
Reid Kleckner30701ed2017-09-05 20:27:35 +00001123 case Builtin::BI__annotation:
1124 if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1125 return ExprError();
1126 break;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001127 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +00001128 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001129 return ExprError();
1130 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +00001131 case Builtin::BI__builtin_addressof:
1132 if (SemaBuiltinAddressof(*this, TheCall))
1133 return ExprError();
1134 break;
John McCall03107a42015-10-29 20:48:01 +00001135 case Builtin::BI__builtin_add_overflow:
1136 case Builtin::BI__builtin_sub_overflow:
1137 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +00001138 if (SemaBuiltinOverflow(*this, TheCall))
1139 return ExprError();
1140 break;
Richard Smith760520b2014-06-03 23:27:44 +00001141 case Builtin::BI__builtin_operator_new:
Eric Fiselierfa752f22018-03-21 19:19:48 +00001142 case Builtin::BI__builtin_operator_delete: {
1143 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1144 ExprResult Res =
1145 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1146 if (Res.isInvalid())
1147 CorrectDelayedTyposInExpr(TheCallResult.get());
1148 return Res;
1149 }
Aaron Ballman06525342018-04-10 21:58:13 +00001150 case Builtin::BI__builtin_dump_struct: {
1151 // We first want to ensure we are called with 2 arguments
1152 if (checkArgCount(*this, TheCall, 2))
1153 return ExprError();
1154 // Ensure that the first argument is of type 'struct XX *'
1155 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1156 const QualType PtrArgType = PtrArg->getType();
1157 if (!PtrArgType->isPointerType() ||
1158 !PtrArgType->getPointeeType()->isRecordType()) {
1159 Diag(PtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1160 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1161 << "structure pointer";
1162 return ExprError();
1163 }
1164
1165 // Ensure that the second argument is of type 'FunctionType'
1166 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1167 const QualType FnPtrArgType = FnPtrArg->getType();
1168 if (!FnPtrArgType->isPointerType()) {
1169 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1170 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1171 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1172 return ExprError();
1173 }
1174
1175 const auto *FuncType =
1176 FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1177
1178 if (!FuncType) {
1179 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1180 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1181 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1182 return ExprError();
1183 }
1184
1185 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1186 if (!FT->getNumParams()) {
1187 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1188 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1189 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1190 return ExprError();
1191 }
1192 QualType PT = FT->getParamType(0);
1193 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1194 !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1195 !PT->getPointeeType().isConstQualified()) {
1196 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1197 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1198 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1199 return ExprError();
1200 }
1201 }
1202
1203 TheCall->setType(Context.IntTy);
1204 break;
1205 }
1206
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001207 // check secure string manipulation functions where overflows
1208 // are detectable at compile time
1209 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001210 case Builtin::BI__builtin___memmove_chk:
1211 case Builtin::BI__builtin___memset_chk:
1212 case Builtin::BI__builtin___strlcat_chk:
1213 case Builtin::BI__builtin___strlcpy_chk:
1214 case Builtin::BI__builtin___strncat_chk:
1215 case Builtin::BI__builtin___strncpy_chk:
1216 case Builtin::BI__builtin___stpncpy_chk:
1217 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1218 break;
Steven Wu566c14e2014-09-24 04:37:33 +00001219 case Builtin::BI__builtin___memccpy_chk:
1220 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1221 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001222 case Builtin::BI__builtin___snprintf_chk:
1223 case Builtin::BI__builtin___vsnprintf_chk:
1224 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1225 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001226 case Builtin::BI__builtin_call_with_static_chain:
1227 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1228 return ExprError();
1229 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001230 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001231 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001232 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1233 diag::err_seh___except_block))
1234 return ExprError();
1235 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001236 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001237 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001238 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1239 diag::err_seh___except_filter))
1240 return ExprError();
1241 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001242 case Builtin::BI__GetExceptionInfo:
1243 if (checkArgCount(*this, TheCall, 1))
1244 return ExprError();
1245
1246 if (CheckCXXThrowOperand(
1247 TheCall->getLocStart(),
1248 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1249 TheCall))
1250 return ExprError();
1251
1252 TheCall->setType(Context.VoidPtrTy);
1253 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001254 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001255 case Builtin::BIread_pipe:
1256 case Builtin::BIwrite_pipe:
1257 // Since those two functions are declared with var args, we need a semantic
1258 // check for the argument.
1259 if (SemaBuiltinRWPipe(*this, TheCall))
1260 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001261 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001262 break;
1263 case Builtin::BIreserve_read_pipe:
1264 case Builtin::BIreserve_write_pipe:
1265 case Builtin::BIwork_group_reserve_read_pipe:
1266 case Builtin::BIwork_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001267 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1268 return ExprError();
Joey Gouly84ae3362017-07-31 15:15:59 +00001269 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001270 case Builtin::BIsub_group_reserve_read_pipe:
1271 case Builtin::BIsub_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001272 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1273 SemaBuiltinReserveRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001274 return ExprError();
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001275 break;
1276 case Builtin::BIcommit_read_pipe:
1277 case Builtin::BIcommit_write_pipe:
1278 case Builtin::BIwork_group_commit_read_pipe:
1279 case Builtin::BIwork_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001280 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1281 return ExprError();
1282 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001283 case Builtin::BIsub_group_commit_read_pipe:
1284 case Builtin::BIsub_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001285 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1286 SemaBuiltinCommitRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001287 return ExprError();
1288 break;
1289 case Builtin::BIget_pipe_num_packets:
1290 case Builtin::BIget_pipe_max_packets:
1291 if (SemaBuiltinPipePackets(*this, TheCall))
1292 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001293 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001294 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001295 case Builtin::BIto_global:
1296 case Builtin::BIto_local:
1297 case Builtin::BIto_private:
1298 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1299 return ExprError();
1300 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001301 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1302 case Builtin::BIenqueue_kernel:
1303 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1304 return ExprError();
1305 break;
1306 case Builtin::BIget_kernel_work_group_size:
1307 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1308 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1309 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001310 break;
Joey Goulyfa76b492017-08-01 13:27:09 +00001311 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1312 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1313 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1314 return ExprError();
1315 break;
Mehdi Amini06d367c2016-10-24 20:39:34 +00001316 case Builtin::BI__builtin_os_log_format:
1317 case Builtin::BI__builtin_os_log_format_buffer_size:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00001318 if (SemaBuiltinOSLogFormat(TheCall))
Mehdi Amini06d367c2016-10-24 20:39:34 +00001319 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001320 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001321 }
Richard Smith760520b2014-06-03 23:27:44 +00001322
Nate Begeman4904e322010-06-08 02:47:44 +00001323 // Since the target specific builtins for each arch overlap, only check those
1324 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001325 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001326 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001327 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001328 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001329 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001330 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001331 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1332 return ExprError();
1333 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001334 case llvm::Triple::aarch64:
1335 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001336 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001337 return ExprError();
1338 break;
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00001339 case llvm::Triple::hexagon:
1340 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1341 return ExprError();
1342 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001343 case llvm::Triple::mips:
1344 case llvm::Triple::mipsel:
1345 case llvm::Triple::mips64:
1346 case llvm::Triple::mips64el:
1347 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1348 return ExprError();
1349 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001350 case llvm::Triple::systemz:
1351 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1352 return ExprError();
1353 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001354 case llvm::Triple::x86:
1355 case llvm::Triple::x86_64:
1356 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1357 return ExprError();
1358 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001359 case llvm::Triple::ppc:
1360 case llvm::Triple::ppc64:
1361 case llvm::Triple::ppc64le:
1362 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1363 return ExprError();
1364 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001365 default:
1366 break;
1367 }
1368 }
1369
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001370 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001371}
1372
Nate Begeman91e1fea2010-06-14 05:21:25 +00001373// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001374static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001375 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001376 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001377 switch (Type.getEltType()) {
1378 case NeonTypeFlags::Int8:
1379 case NeonTypeFlags::Poly8:
1380 return shift ? 7 : (8 << IsQuad) - 1;
1381 case NeonTypeFlags::Int16:
1382 case NeonTypeFlags::Poly16:
1383 return shift ? 15 : (4 << IsQuad) - 1;
1384 case NeonTypeFlags::Int32:
1385 return shift ? 31 : (2 << IsQuad) - 1;
1386 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001387 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001388 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001389 case NeonTypeFlags::Poly128:
1390 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001391 case NeonTypeFlags::Float16:
1392 assert(!shift && "cannot shift float types!");
1393 return (4 << IsQuad) - 1;
1394 case NeonTypeFlags::Float32:
1395 assert(!shift && "cannot shift float types!");
1396 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001397 case NeonTypeFlags::Float64:
1398 assert(!shift && "cannot shift float types!");
1399 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001400 }
David Blaikie8a40f702012-01-17 06:56:22 +00001401 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001402}
1403
Bob Wilsone4d77232011-11-08 05:04:11 +00001404/// getNeonEltType - Return the QualType corresponding to the elements of
1405/// the vector type specified by the NeonTypeFlags. This is used to check
1406/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001407static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001408 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001409 switch (Flags.getEltType()) {
1410 case NeonTypeFlags::Int8:
1411 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1412 case NeonTypeFlags::Int16:
1413 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1414 case NeonTypeFlags::Int32:
1415 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1416 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001417 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001418 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1419 else
1420 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1421 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001422 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001423 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001424 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001425 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001426 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001427 if (IsInt64Long)
1428 return Context.UnsignedLongTy;
1429 else
1430 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001431 case NeonTypeFlags::Poly128:
1432 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001433 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001434 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001435 case NeonTypeFlags::Float32:
1436 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001437 case NeonTypeFlags::Float64:
1438 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001439 }
David Blaikie8a40f702012-01-17 06:56:22 +00001440 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001441}
1442
Tim Northover12670412014-02-19 10:37:05 +00001443bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001444 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001445 uint64_t mask = 0;
1446 unsigned TV = 0;
1447 int PtrArgNum = -1;
1448 bool HasConstPtr = false;
1449 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001450#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001451#include "clang/Basic/arm_neon.inc"
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +00001452#include "clang/Basic/arm_fp16.inc"
Tim Northover12670412014-02-19 10:37:05 +00001453#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001454 }
1455
1456 // For NEON intrinsics which are overloaded on vector element type, validate
1457 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001458 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001459 if (mask) {
1460 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1461 return true;
1462
1463 TV = Result.getLimitedValue(64);
1464 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1465 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001466 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001467 }
1468
1469 if (PtrArgNum >= 0) {
1470 // Check that pointer arguments have the specified type.
1471 Expr *Arg = TheCall->getArg(PtrArgNum);
1472 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1473 Arg = ICE->getSubExpr();
1474 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1475 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001476
Tim Northovera2ee4332014-03-29 15:09:45 +00001477 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001478 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1479 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001480 bool IsInt64Long =
1481 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1482 QualType EltTy =
1483 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001484 if (HasConstPtr)
1485 EltTy = EltTy.withConst();
1486 QualType LHSTy = Context.getPointerType(EltTy);
1487 AssignConvertType ConvTy;
1488 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1489 if (RHS.isInvalid())
1490 return true;
1491 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1492 RHS.get(), AA_Assigning))
1493 return true;
1494 }
1495
1496 // For NEON intrinsics which take an immediate value as part of the
1497 // instruction, range check them here.
1498 unsigned i = 0, l = 0, u = 0;
1499 switch (BuiltinID) {
1500 default:
1501 return false;
Tim Northover12670412014-02-19 10:37:05 +00001502#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001503#include "clang/Basic/arm_neon.inc"
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +00001504#include "clang/Basic/arm_fp16.inc"
Tim Northover12670412014-02-19 10:37:05 +00001505#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001506 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001507
Richard Sandiford28940af2014-04-16 08:47:51 +00001508 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001509}
1510
Tim Northovera2ee4332014-03-29 15:09:45 +00001511bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1512 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001513 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001514 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001515 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001516 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001517 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001518 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1519 BuiltinID == AArch64::BI__builtin_arm_strex ||
1520 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001521 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001522 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001523 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1524 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1525 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001526
1527 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1528
1529 // Ensure that we have the proper number of arguments.
1530 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1531 return true;
1532
1533 // Inspect the pointer argument of the atomic builtin. This should always be
1534 // a pointer type, whose element is an integral scalar or pointer type.
1535 // Because it is a pointer type, we don't have to worry about any implicit
1536 // casts here.
1537 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1538 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1539 if (PointerArgRes.isInvalid())
1540 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001541 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001542
1543 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1544 if (!pointerType) {
1545 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1546 << PointerArg->getType() << PointerArg->getSourceRange();
1547 return true;
1548 }
1549
1550 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1551 // task is to insert the appropriate casts into the AST. First work out just
1552 // what the appropriate type is.
1553 QualType ValType = pointerType->getPointeeType();
1554 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1555 if (IsLdrex)
1556 AddrType.addConst();
1557
1558 // Issue a warning if the cast is dodgy.
1559 CastKind CastNeeded = CK_NoOp;
1560 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1561 CastNeeded = CK_BitCast;
1562 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1563 << PointerArg->getType()
1564 << Context.getPointerType(AddrType)
1565 << AA_Passing << PointerArg->getSourceRange();
1566 }
1567
1568 // Finally, do the cast and replace the argument with the corrected version.
1569 AddrType = Context.getPointerType(AddrType);
1570 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1571 if (PointerArgRes.isInvalid())
1572 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001573 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001574
1575 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1576
1577 // In general, we allow ints, floats and pointers to be loaded and stored.
1578 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1579 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1580 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1581 << PointerArg->getType() << PointerArg->getSourceRange();
1582 return true;
1583 }
1584
1585 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001586 if (Context.getTypeSize(ValType) > MaxWidth) {
1587 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001588 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1589 << PointerArg->getType() << PointerArg->getSourceRange();
1590 return true;
1591 }
1592
1593 switch (ValType.getObjCLifetime()) {
1594 case Qualifiers::OCL_None:
1595 case Qualifiers::OCL_ExplicitNone:
1596 // okay
1597 break;
1598
1599 case Qualifiers::OCL_Weak:
1600 case Qualifiers::OCL_Strong:
1601 case Qualifiers::OCL_Autoreleasing:
1602 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1603 << ValType << PointerArg->getSourceRange();
1604 return true;
1605 }
1606
Tim Northover6aacd492013-07-16 09:47:53 +00001607 if (IsLdrex) {
1608 TheCall->setType(ValType);
1609 return false;
1610 }
1611
1612 // Initialize the argument to be stored.
1613 ExprResult ValArg = TheCall->getArg(0);
1614 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1615 Context, ValType, /*consume*/ false);
1616 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1617 if (ValArg.isInvalid())
1618 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001619 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001620
1621 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1622 // but the custom checker bypasses all default analysis.
1623 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001624 return false;
1625}
1626
Nate Begeman4904e322010-06-08 02:47:44 +00001627bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover6aacd492013-07-16 09:47:53 +00001628 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001629 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1630 BuiltinID == ARM::BI__builtin_arm_strex ||
1631 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001632 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001633 }
1634
Yi Kong26d104a2014-08-13 19:18:14 +00001635 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1636 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1637 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1638 }
1639
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001640 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1641 BuiltinID == ARM::BI__builtin_arm_wsr64)
1642 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1643
1644 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1645 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1646 BuiltinID == ARM::BI__builtin_arm_wsr ||
1647 BuiltinID == ARM::BI__builtin_arm_wsrp)
1648 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1649
Tim Northover12670412014-02-19 10:37:05 +00001650 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1651 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001652
Yi Kong4efadfb2014-07-03 16:01:25 +00001653 // For intrinsics which take an immediate value as part of the instruction,
1654 // range check them here.
Sjoerd Meijer293da702017-12-07 09:54:39 +00001655 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begemand773fe62010-06-13 04:47:52 +00001656 switch (BuiltinID) {
1657 default: return false;
Sjoerd Meijer293da702017-12-07 09:54:39 +00001658 case ARM::BI__builtin_arm_ssat:
1659 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1660 case ARM::BI__builtin_arm_usat:
1661 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1662 case ARM::BI__builtin_arm_ssat16:
1663 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1664 case ARM::BI__builtin_arm_usat16:
1665 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
Nate Begemanf568b072010-08-03 21:32:34 +00001666 case ARM::BI__builtin_arm_vcvtr_f:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001667 case ARM::BI__builtin_arm_vcvtr_d:
1668 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
Weiming Zhao87bb4922013-11-12 21:42:50 +00001669 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001670 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001671 case ARM::BI__builtin_arm_isb:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001672 case ARM::BI__builtin_arm_dbg:
1673 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
Richard Sandiford28940af2014-04-16 08:47:51 +00001674 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001675}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001676
Tim Northover573cbee2014-05-24 12:52:07 +00001677bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001678 CallExpr *TheCall) {
Tim Northover573cbee2014-05-24 12:52:07 +00001679 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001680 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1681 BuiltinID == AArch64::BI__builtin_arm_strex ||
1682 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001683 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1684 }
1685
Yi Konga5548432014-08-13 19:18:20 +00001686 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1687 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1688 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1689 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1690 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1691 }
1692
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001693 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1694 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001695 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001696
1697 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1698 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1699 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1700 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1701 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1702
Tim Northovera2ee4332014-03-29 15:09:45 +00001703 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1704 return true;
1705
Yi Kong19a29ac2014-07-17 10:52:06 +00001706 // For intrinsics which take an immediate value as part of the instruction,
1707 // range check them here.
1708 unsigned i = 0, l = 0, u = 0;
1709 switch (BuiltinID) {
1710 default: return false;
1711 case AArch64::BI__builtin_arm_dmb:
1712 case AArch64::BI__builtin_arm_dsb:
1713 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1714 }
1715
Yi Kong19a29ac2014-07-17 10:52:06 +00001716 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001717}
1718
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00001719bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
1720 CallExpr *TheCall) {
1721 struct ArgInfo {
1722 ArgInfo(unsigned O, bool S, unsigned W, unsigned A)
1723 : OpNum(O), IsSigned(S), BitWidth(W), Align(A) {}
1724 unsigned OpNum = 0;
1725 bool IsSigned = false;
1726 unsigned BitWidth = 0;
1727 unsigned Align = 0;
1728 };
1729
1730 static const std::map<unsigned, std::vector<ArgInfo>> Infos = {
1731 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
1732 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
1733 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
1734 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} },
1735 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
1736 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
1737 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
1738 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
1739 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
1740 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
1741 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
1742
1743 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
1744 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
1745 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
1746 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
1747 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
1748 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
1749 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
1750 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
1751 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
1752 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
1753 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
1754
1755 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
1756 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
1757 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
1758 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
1759 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
1760 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
1761 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
1762 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
1763 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
1764 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
1765 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
1766 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
1767 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
1768 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
1769 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
1770 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
1771 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
1772 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
1773 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
1774 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
1775 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
1776 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
1777 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
1778 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
1779 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
1780 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
1781 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
1782 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
1783 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
1784 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
1785 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
1786 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
1787 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
1788 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
1789 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
1790 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
1791 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
1792 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
1793 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
1794 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
1795 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
1796 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
1797 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
1798 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
1799 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
1800 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
1801 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
1802 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
1803 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
1804 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
1805 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
1806 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
1807 {{ 1, false, 6, 0 }} },
1808 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
1809 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
1810 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
1811 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
1812 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
1813 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
1814 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
1815 {{ 1, false, 5, 0 }} },
1816 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
1817 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
1818 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
1819 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
1820 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
1821 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
1822 { 2, false, 5, 0 }} },
1823 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
1824 { 2, false, 6, 0 }} },
1825 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
1826 { 3, false, 5, 0 }} },
1827 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
1828 { 3, false, 6, 0 }} },
1829 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
1830 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
1831 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
1832 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
1833 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
1834 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
1835 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
1836 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
1837 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
1838 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
1839 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
1840 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
1841 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
1842 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
1843 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
1844 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
1845 {{ 2, false, 4, 0 },
1846 { 3, false, 5, 0 }} },
1847 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
1848 {{ 2, false, 4, 0 },
1849 { 3, false, 5, 0 }} },
1850 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
1851 {{ 2, false, 4, 0 },
1852 { 3, false, 5, 0 }} },
1853 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
1854 {{ 2, false, 4, 0 },
1855 { 3, false, 5, 0 }} },
1856 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
1857 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
1858 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
1859 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
1860 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
1861 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
1862 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
1863 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
1864 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
1865 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
1866 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
1867 { 2, false, 5, 0 }} },
1868 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
1869 { 2, false, 6, 0 }} },
1870 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
1871 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
1872 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
1873 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
1874 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
1875 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
1876 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
1877 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
1878 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
1879 {{ 1, false, 4, 0 }} },
1880 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
1881 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
1882 {{ 1, false, 4, 0 }} },
1883 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
1884 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
1885 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
1886 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
1887 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
1888 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
1889 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
1890 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
1891 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
1892 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
1893 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
1894 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
1895 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
1896 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
1897 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
1898 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
1899 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
1900 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
1901 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
1902 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
1903 {{ 3, false, 1, 0 }} },
1904 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
1905 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
1906 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
1907 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
1908 {{ 3, false, 1, 0 }} },
1909 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
1910 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
1911 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
1912 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
1913 {{ 3, false, 1, 0 }} },
1914 };
1915
1916 auto F = Infos.find(BuiltinID);
1917 if (F == Infos.end())
1918 return false;
1919
1920 bool Error = false;
1921
1922 for (const ArgInfo &A : F->second) {
1923 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth-1)) : 0;
1924 int32_t Max = (1 << (A.IsSigned ? A.BitWidth-1 : A.BitWidth)) - 1;
1925 if (!A.Align) {
1926 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
1927 } else {
1928 unsigned M = 1 << A.Align;
1929 Min *= M;
1930 Max *= M;
1931 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
1932 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
1933 }
1934 }
1935 return Error;
1936}
1937
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001938// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1939// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1940// ordering for DSP is unspecified. MSA is ordered by the data format used
1941// by the underlying instruction i.e., df/m, df/n and then by size.
1942//
1943// FIXME: The size tests here should instead be tablegen'd along with the
1944// definitions from include/clang/Basic/BuiltinsMips.def.
1945// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1946// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001947bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001948 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001949 switch (BuiltinID) {
1950 default: return false;
1951 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1952 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001953 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1954 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1955 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1956 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1957 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001958 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1959 // df/m field.
1960 // These intrinsics take an unsigned 3 bit immediate.
1961 case Mips::BI__builtin_msa_bclri_b:
1962 case Mips::BI__builtin_msa_bnegi_b:
1963 case Mips::BI__builtin_msa_bseti_b:
1964 case Mips::BI__builtin_msa_sat_s_b:
1965 case Mips::BI__builtin_msa_sat_u_b:
1966 case Mips::BI__builtin_msa_slli_b:
1967 case Mips::BI__builtin_msa_srai_b:
1968 case Mips::BI__builtin_msa_srari_b:
1969 case Mips::BI__builtin_msa_srli_b:
1970 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1971 case Mips::BI__builtin_msa_binsli_b:
1972 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1973 // These intrinsics take an unsigned 4 bit immediate.
1974 case Mips::BI__builtin_msa_bclri_h:
1975 case Mips::BI__builtin_msa_bnegi_h:
1976 case Mips::BI__builtin_msa_bseti_h:
1977 case Mips::BI__builtin_msa_sat_s_h:
1978 case Mips::BI__builtin_msa_sat_u_h:
1979 case Mips::BI__builtin_msa_slli_h:
1980 case Mips::BI__builtin_msa_srai_h:
1981 case Mips::BI__builtin_msa_srari_h:
1982 case Mips::BI__builtin_msa_srli_h:
1983 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1984 case Mips::BI__builtin_msa_binsli_h:
1985 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001986 // These intrinsics take an unsigned 5 bit immediate.
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001987 // The first block of intrinsics actually have an unsigned 5 bit field,
1988 // not a df/n field.
1989 case Mips::BI__builtin_msa_clei_u_b:
1990 case Mips::BI__builtin_msa_clei_u_h:
1991 case Mips::BI__builtin_msa_clei_u_w:
1992 case Mips::BI__builtin_msa_clei_u_d:
1993 case Mips::BI__builtin_msa_clti_u_b:
1994 case Mips::BI__builtin_msa_clti_u_h:
1995 case Mips::BI__builtin_msa_clti_u_w:
1996 case Mips::BI__builtin_msa_clti_u_d:
1997 case Mips::BI__builtin_msa_maxi_u_b:
1998 case Mips::BI__builtin_msa_maxi_u_h:
1999 case Mips::BI__builtin_msa_maxi_u_w:
2000 case Mips::BI__builtin_msa_maxi_u_d:
2001 case Mips::BI__builtin_msa_mini_u_b:
2002 case Mips::BI__builtin_msa_mini_u_h:
2003 case Mips::BI__builtin_msa_mini_u_w:
2004 case Mips::BI__builtin_msa_mini_u_d:
2005 case Mips::BI__builtin_msa_addvi_b:
2006 case Mips::BI__builtin_msa_addvi_h:
2007 case Mips::BI__builtin_msa_addvi_w:
2008 case Mips::BI__builtin_msa_addvi_d:
2009 case Mips::BI__builtin_msa_bclri_w:
2010 case Mips::BI__builtin_msa_bnegi_w:
2011 case Mips::BI__builtin_msa_bseti_w:
2012 case Mips::BI__builtin_msa_sat_s_w:
2013 case Mips::BI__builtin_msa_sat_u_w:
2014 case Mips::BI__builtin_msa_slli_w:
2015 case Mips::BI__builtin_msa_srai_w:
2016 case Mips::BI__builtin_msa_srari_w:
2017 case Mips::BI__builtin_msa_srli_w:
2018 case Mips::BI__builtin_msa_srlri_w:
2019 case Mips::BI__builtin_msa_subvi_b:
2020 case Mips::BI__builtin_msa_subvi_h:
2021 case Mips::BI__builtin_msa_subvi_w:
2022 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2023 case Mips::BI__builtin_msa_binsli_w:
2024 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2025 // These intrinsics take an unsigned 6 bit immediate.
2026 case Mips::BI__builtin_msa_bclri_d:
2027 case Mips::BI__builtin_msa_bnegi_d:
2028 case Mips::BI__builtin_msa_bseti_d:
2029 case Mips::BI__builtin_msa_sat_s_d:
2030 case Mips::BI__builtin_msa_sat_u_d:
2031 case Mips::BI__builtin_msa_slli_d:
2032 case Mips::BI__builtin_msa_srai_d:
2033 case Mips::BI__builtin_msa_srari_d:
2034 case Mips::BI__builtin_msa_srli_d:
2035 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
2036 case Mips::BI__builtin_msa_binsli_d:
2037 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
2038 // These intrinsics take a signed 5 bit immediate.
2039 case Mips::BI__builtin_msa_ceqi_b:
2040 case Mips::BI__builtin_msa_ceqi_h:
2041 case Mips::BI__builtin_msa_ceqi_w:
2042 case Mips::BI__builtin_msa_ceqi_d:
2043 case Mips::BI__builtin_msa_clti_s_b:
2044 case Mips::BI__builtin_msa_clti_s_h:
2045 case Mips::BI__builtin_msa_clti_s_w:
2046 case Mips::BI__builtin_msa_clti_s_d:
2047 case Mips::BI__builtin_msa_clei_s_b:
2048 case Mips::BI__builtin_msa_clei_s_h:
2049 case Mips::BI__builtin_msa_clei_s_w:
2050 case Mips::BI__builtin_msa_clei_s_d:
2051 case Mips::BI__builtin_msa_maxi_s_b:
2052 case Mips::BI__builtin_msa_maxi_s_h:
2053 case Mips::BI__builtin_msa_maxi_s_w:
2054 case Mips::BI__builtin_msa_maxi_s_d:
2055 case Mips::BI__builtin_msa_mini_s_b:
2056 case Mips::BI__builtin_msa_mini_s_h:
2057 case Mips::BI__builtin_msa_mini_s_w:
2058 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
2059 // These intrinsics take an unsigned 8 bit immediate.
2060 case Mips::BI__builtin_msa_andi_b:
2061 case Mips::BI__builtin_msa_nori_b:
2062 case Mips::BI__builtin_msa_ori_b:
2063 case Mips::BI__builtin_msa_shf_b:
2064 case Mips::BI__builtin_msa_shf_h:
2065 case Mips::BI__builtin_msa_shf_w:
2066 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
2067 case Mips::BI__builtin_msa_bseli_b:
2068 case Mips::BI__builtin_msa_bmnzi_b:
2069 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
2070 // df/n format
2071 // These intrinsics take an unsigned 4 bit immediate.
2072 case Mips::BI__builtin_msa_copy_s_b:
2073 case Mips::BI__builtin_msa_copy_u_b:
2074 case Mips::BI__builtin_msa_insve_b:
2075 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002076 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
2077 // These intrinsics take an unsigned 3 bit immediate.
2078 case Mips::BI__builtin_msa_copy_s_h:
2079 case Mips::BI__builtin_msa_copy_u_h:
2080 case Mips::BI__builtin_msa_insve_h:
2081 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002082 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
2083 // These intrinsics take an unsigned 2 bit immediate.
2084 case Mips::BI__builtin_msa_copy_s_w:
2085 case Mips::BI__builtin_msa_copy_u_w:
2086 case Mips::BI__builtin_msa_insve_w:
2087 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002088 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
2089 // These intrinsics take an unsigned 1 bit immediate.
2090 case Mips::BI__builtin_msa_copy_s_d:
2091 case Mips::BI__builtin_msa_copy_u_d:
2092 case Mips::BI__builtin_msa_insve_d:
2093 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002094 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
2095 // Memory offsets and immediate loads.
2096 // These intrinsics take a signed 10 bit immediate.
Petar Jovanovic9b8b9e82017-03-31 16:16:43 +00002097 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002098 case Mips::BI__builtin_msa_ldi_h:
2099 case Mips::BI__builtin_msa_ldi_w:
2100 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
2101 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
2102 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
2103 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
2104 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
2105 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
2106 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
2107 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
2108 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00002109 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00002110
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002111 if (!m)
2112 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2113
2114 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
2115 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00002116}
2117
Kit Bartone50adcb2015-03-30 19:40:59 +00002118bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2119 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00002120 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
2121 BuiltinID == PPC::BI__builtin_divdeu ||
2122 BuiltinID == PPC::BI__builtin_bpermd;
2123 bool IsTarget64Bit = Context.getTargetInfo()
2124 .getTypeWidth(Context
2125 .getTargetInfo()
2126 .getIntPtrType()) == 64;
2127 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
2128 BuiltinID == PPC::BI__builtin_divweu ||
2129 BuiltinID == PPC::BI__builtin_divde ||
2130 BuiltinID == PPC::BI__builtin_divdeu;
2131
2132 if (Is64BitBltin && !IsTarget64Bit)
2133 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
2134 << TheCall->getSourceRange();
2135
2136 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
2137 (BuiltinID == PPC::BI__builtin_bpermd &&
2138 !Context.getTargetInfo().hasFeature("bpermd")))
2139 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
2140 << TheCall->getSourceRange();
2141
Kit Bartone50adcb2015-03-30 19:40:59 +00002142 switch (BuiltinID) {
2143 default: return false;
2144 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
2145 case PPC::BI__builtin_altivec_crypto_vshasigmad:
2146 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2147 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
2148 case PPC::BI__builtin_tbegin:
2149 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
2150 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
2151 case PPC::BI__builtin_tabortwc:
2152 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
2153 case PPC::BI__builtin_tabortwci:
2154 case PPC::BI__builtin_tabortdci:
2155 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
2156 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
Tony Jiangbbc48e92017-05-24 15:13:32 +00002157 case PPC::BI__builtin_vsx_xxpermdi:
Tony Jiang9aa2c032017-05-24 15:54:13 +00002158 case PPC::BI__builtin_vsx_xxsldwi:
Tony Jiangbbc48e92017-05-24 15:13:32 +00002159 return SemaBuiltinVSX(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00002160 }
2161 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2162}
2163
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00002164bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
2165 CallExpr *TheCall) {
2166 if (BuiltinID == SystemZ::BI__builtin_tabort) {
2167 Expr *Arg = TheCall->getArg(0);
2168 llvm::APSInt AbortCode(32);
2169 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
2170 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
2171 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
2172 << Arg->getSourceRange();
2173 }
2174
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002175 // For intrinsics which take an immediate value as part of the instruction,
2176 // range check them here.
2177 unsigned i = 0, l = 0, u = 0;
2178 switch (BuiltinID) {
2179 default: return false;
2180 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
2181 case SystemZ::BI__builtin_s390_verimb:
2182 case SystemZ::BI__builtin_s390_verimh:
2183 case SystemZ::BI__builtin_s390_verimf:
2184 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
2185 case SystemZ::BI__builtin_s390_vfaeb:
2186 case SystemZ::BI__builtin_s390_vfaeh:
2187 case SystemZ::BI__builtin_s390_vfaef:
2188 case SystemZ::BI__builtin_s390_vfaebs:
2189 case SystemZ::BI__builtin_s390_vfaehs:
2190 case SystemZ::BI__builtin_s390_vfaefs:
2191 case SystemZ::BI__builtin_s390_vfaezb:
2192 case SystemZ::BI__builtin_s390_vfaezh:
2193 case SystemZ::BI__builtin_s390_vfaezf:
2194 case SystemZ::BI__builtin_s390_vfaezbs:
2195 case SystemZ::BI__builtin_s390_vfaezhs:
2196 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00002197 case SystemZ::BI__builtin_s390_vfisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002198 case SystemZ::BI__builtin_s390_vfidb:
2199 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
2200 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00002201 case SystemZ::BI__builtin_s390_vftcisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002202 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
2203 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
2204 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
2205 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
2206 case SystemZ::BI__builtin_s390_vstrcb:
2207 case SystemZ::BI__builtin_s390_vstrch:
2208 case SystemZ::BI__builtin_s390_vstrcf:
2209 case SystemZ::BI__builtin_s390_vstrczb:
2210 case SystemZ::BI__builtin_s390_vstrczh:
2211 case SystemZ::BI__builtin_s390_vstrczf:
2212 case SystemZ::BI__builtin_s390_vstrcbs:
2213 case SystemZ::BI__builtin_s390_vstrchs:
2214 case SystemZ::BI__builtin_s390_vstrcfs:
2215 case SystemZ::BI__builtin_s390_vstrczbs:
2216 case SystemZ::BI__builtin_s390_vstrczhs:
2217 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00002218 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
2219 case SystemZ::BI__builtin_s390_vfminsb:
2220 case SystemZ::BI__builtin_s390_vfmaxsb:
2221 case SystemZ::BI__builtin_s390_vfmindb:
2222 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002223 }
2224 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00002225}
2226
Craig Topper5ba2c502015-11-07 08:08:31 +00002227/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
2228/// This checks that the target supports __builtin_cpu_supports and
2229/// that the string argument is constant and valid.
2230static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
2231 Expr *Arg = TheCall->getArg(0);
2232
2233 // Check if the argument is a string literal.
2234 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2235 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2236 << Arg->getSourceRange();
2237
2238 // Check the contents of the string.
2239 StringRef Feature =
2240 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2241 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
2242 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
2243 << Arg->getSourceRange();
2244 return false;
2245}
2246
Craig Topper699ae0c2017-08-10 20:28:30 +00002247/// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
2248/// This checks that the target supports __builtin_cpu_is and
2249/// that the string argument is constant and valid.
2250static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
2251 Expr *Arg = TheCall->getArg(0);
2252
2253 // Check if the argument is a string literal.
2254 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2255 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2256 << Arg->getSourceRange();
2257
2258 // Check the contents of the string.
2259 StringRef Feature =
2260 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2261 if (!S.Context.getTargetInfo().validateCpuIs(Feature))
2262 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
2263 << Arg->getSourceRange();
2264 return false;
2265}
2266
Craig Toppera7e253e2016-09-23 04:48:31 +00002267// Check if the rounding mode is legal.
2268bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
2269 // Indicates if this instruction has rounding control or just SAE.
2270 bool HasRC = false;
2271
2272 unsigned ArgNum = 0;
2273 switch (BuiltinID) {
2274 default:
2275 return false;
2276 case X86::BI__builtin_ia32_vcvttsd2si32:
2277 case X86::BI__builtin_ia32_vcvttsd2si64:
2278 case X86::BI__builtin_ia32_vcvttsd2usi32:
2279 case X86::BI__builtin_ia32_vcvttsd2usi64:
2280 case X86::BI__builtin_ia32_vcvttss2si32:
2281 case X86::BI__builtin_ia32_vcvttss2si64:
2282 case X86::BI__builtin_ia32_vcvttss2usi32:
2283 case X86::BI__builtin_ia32_vcvttss2usi64:
2284 ArgNum = 1;
2285 break;
2286 case X86::BI__builtin_ia32_cvtps2pd512_mask:
2287 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
2288 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
2289 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
2290 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
2291 case X86::BI__builtin_ia32_cvttps2dq512_mask:
2292 case X86::BI__builtin_ia32_cvttps2qq512_mask:
2293 case X86::BI__builtin_ia32_cvttps2udq512_mask:
2294 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
2295 case X86::BI__builtin_ia32_exp2pd_mask:
2296 case X86::BI__builtin_ia32_exp2ps_mask:
2297 case X86::BI__builtin_ia32_getexppd512_mask:
2298 case X86::BI__builtin_ia32_getexpps512_mask:
2299 case X86::BI__builtin_ia32_rcp28pd_mask:
2300 case X86::BI__builtin_ia32_rcp28ps_mask:
2301 case X86::BI__builtin_ia32_rsqrt28pd_mask:
2302 case X86::BI__builtin_ia32_rsqrt28ps_mask:
2303 case X86::BI__builtin_ia32_vcomisd:
2304 case X86::BI__builtin_ia32_vcomiss:
2305 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
2306 ArgNum = 3;
2307 break;
2308 case X86::BI__builtin_ia32_cmppd512_mask:
2309 case X86::BI__builtin_ia32_cmpps512_mask:
2310 case X86::BI__builtin_ia32_cmpsd_mask:
2311 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002312 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00002313 case X86::BI__builtin_ia32_getexpsd128_round_mask:
2314 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002315 case X86::BI__builtin_ia32_maxpd512_mask:
2316 case X86::BI__builtin_ia32_maxps512_mask:
2317 case X86::BI__builtin_ia32_maxsd_round_mask:
2318 case X86::BI__builtin_ia32_maxss_round_mask:
2319 case X86::BI__builtin_ia32_minpd512_mask:
2320 case X86::BI__builtin_ia32_minps512_mask:
2321 case X86::BI__builtin_ia32_minsd_round_mask:
2322 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00002323 case X86::BI__builtin_ia32_rcp28sd_round_mask:
2324 case X86::BI__builtin_ia32_rcp28ss_round_mask:
2325 case X86::BI__builtin_ia32_reducepd512_mask:
2326 case X86::BI__builtin_ia32_reduceps512_mask:
2327 case X86::BI__builtin_ia32_rndscalepd_mask:
2328 case X86::BI__builtin_ia32_rndscaleps_mask:
2329 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
2330 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
2331 ArgNum = 4;
2332 break;
2333 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002334 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002335 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002336 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002337 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002338 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002339 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002340 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002341 case X86::BI__builtin_ia32_rangepd512_mask:
2342 case X86::BI__builtin_ia32_rangeps512_mask:
2343 case X86::BI__builtin_ia32_rangesd128_round_mask:
2344 case X86::BI__builtin_ia32_rangess128_round_mask:
2345 case X86::BI__builtin_ia32_reducesd_mask:
2346 case X86::BI__builtin_ia32_reducess_mask:
2347 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2348 case X86::BI__builtin_ia32_rndscaless_round_mask:
2349 ArgNum = 5;
2350 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00002351 case X86::BI__builtin_ia32_vcvtsd2si64:
2352 case X86::BI__builtin_ia32_vcvtsd2si32:
2353 case X86::BI__builtin_ia32_vcvtsd2usi32:
2354 case X86::BI__builtin_ia32_vcvtsd2usi64:
2355 case X86::BI__builtin_ia32_vcvtss2si32:
2356 case X86::BI__builtin_ia32_vcvtss2si64:
2357 case X86::BI__builtin_ia32_vcvtss2usi32:
2358 case X86::BI__builtin_ia32_vcvtss2usi64:
2359 ArgNum = 1;
2360 HasRC = true;
2361 break;
Craig Topper8e066312016-11-07 07:01:09 +00002362 case X86::BI__builtin_ia32_cvtsi2sd64:
2363 case X86::BI__builtin_ia32_cvtsi2ss32:
2364 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00002365 case X86::BI__builtin_ia32_cvtusi2sd64:
2366 case X86::BI__builtin_ia32_cvtusi2ss32:
2367 case X86::BI__builtin_ia32_cvtusi2ss64:
2368 ArgNum = 2;
2369 HasRC = true;
2370 break;
2371 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
2372 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
2373 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2374 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2375 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2376 case X86::BI__builtin_ia32_cvtps2qq512_mask:
2377 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2378 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2379 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2380 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2381 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002382 case X86::BI__builtin_ia32_sqrtpd512_mask:
2383 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002384 ArgNum = 3;
2385 HasRC = true;
2386 break;
2387 case X86::BI__builtin_ia32_addpd512_mask:
2388 case X86::BI__builtin_ia32_addps512_mask:
2389 case X86::BI__builtin_ia32_divpd512_mask:
2390 case X86::BI__builtin_ia32_divps512_mask:
2391 case X86::BI__builtin_ia32_mulpd512_mask:
2392 case X86::BI__builtin_ia32_mulps512_mask:
2393 case X86::BI__builtin_ia32_subpd512_mask:
2394 case X86::BI__builtin_ia32_subps512_mask:
2395 case X86::BI__builtin_ia32_addss_round_mask:
2396 case X86::BI__builtin_ia32_addsd_round_mask:
2397 case X86::BI__builtin_ia32_divss_round_mask:
2398 case X86::BI__builtin_ia32_divsd_round_mask:
2399 case X86::BI__builtin_ia32_mulss_round_mask:
2400 case X86::BI__builtin_ia32_mulsd_round_mask:
2401 case X86::BI__builtin_ia32_subss_round_mask:
2402 case X86::BI__builtin_ia32_subsd_round_mask:
2403 case X86::BI__builtin_ia32_scalefpd512_mask:
2404 case X86::BI__builtin_ia32_scalefps512_mask:
2405 case X86::BI__builtin_ia32_scalefsd_round_mask:
2406 case X86::BI__builtin_ia32_scalefss_round_mask:
2407 case X86::BI__builtin_ia32_getmantpd512_mask:
2408 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002409 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2410 case X86::BI__builtin_ia32_sqrtsd_round_mask:
2411 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002412 case X86::BI__builtin_ia32_vfmaddsd3_mask:
2413 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2414 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2415 case X86::BI__builtin_ia32_vfmaddss3_mask:
2416 case X86::BI__builtin_ia32_vfmaddss3_maskz:
2417 case X86::BI__builtin_ia32_vfmaddss3_mask3:
Craig Topperb92c77d2018-06-07 02:46:02 +00002418 case X86::BI__builtin_ia32_vfmaddpd512_mask:
2419 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2420 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2421 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2422 case X86::BI__builtin_ia32_vfmaddps512_mask:
2423 case X86::BI__builtin_ia32_vfmaddps512_maskz:
2424 case X86::BI__builtin_ia32_vfmaddps512_mask3:
2425 case X86::BI__builtin_ia32_vfmsubps512_mask3:
2426 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2427 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2428 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2429 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2430 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2431 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2432 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2433 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
Craig Topper7609f1c2016-10-01 21:03:50 +00002434 ArgNum = 4;
2435 HasRC = true;
2436 break;
2437 case X86::BI__builtin_ia32_getmantsd_round_mask:
2438 case X86::BI__builtin_ia32_getmantss_round_mask:
2439 ArgNum = 5;
2440 HasRC = true;
2441 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00002442 }
2443
2444 llvm::APSInt Result;
2445
2446 // We can't check the value of a dependent argument.
2447 Expr *Arg = TheCall->getArg(ArgNum);
2448 if (Arg->isTypeDependent() || Arg->isValueDependent())
2449 return false;
2450
2451 // Check constant-ness first.
2452 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2453 return true;
2454
2455 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2456 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2457 // combined with ROUND_NO_EXC.
2458 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2459 Result == 8/*ROUND_NO_EXC*/ ||
2460 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2461 return false;
2462
2463 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2464 << Arg->getSourceRange();
2465}
2466
Craig Topperdf5beb22017-03-13 17:16:50 +00002467// Check if the gather/scatter scale is legal.
2468bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2469 CallExpr *TheCall) {
2470 unsigned ArgNum = 0;
2471 switch (BuiltinID) {
2472 default:
2473 return false;
2474 case X86::BI__builtin_ia32_gatherpfdpd:
2475 case X86::BI__builtin_ia32_gatherpfdps:
2476 case X86::BI__builtin_ia32_gatherpfqpd:
2477 case X86::BI__builtin_ia32_gatherpfqps:
2478 case X86::BI__builtin_ia32_scatterpfdpd:
2479 case X86::BI__builtin_ia32_scatterpfdps:
2480 case X86::BI__builtin_ia32_scatterpfqpd:
2481 case X86::BI__builtin_ia32_scatterpfqps:
2482 ArgNum = 3;
2483 break;
2484 case X86::BI__builtin_ia32_gatherd_pd:
2485 case X86::BI__builtin_ia32_gatherd_pd256:
2486 case X86::BI__builtin_ia32_gatherq_pd:
2487 case X86::BI__builtin_ia32_gatherq_pd256:
2488 case X86::BI__builtin_ia32_gatherd_ps:
2489 case X86::BI__builtin_ia32_gatherd_ps256:
2490 case X86::BI__builtin_ia32_gatherq_ps:
2491 case X86::BI__builtin_ia32_gatherq_ps256:
2492 case X86::BI__builtin_ia32_gatherd_q:
2493 case X86::BI__builtin_ia32_gatherd_q256:
2494 case X86::BI__builtin_ia32_gatherq_q:
2495 case X86::BI__builtin_ia32_gatherq_q256:
2496 case X86::BI__builtin_ia32_gatherd_d:
2497 case X86::BI__builtin_ia32_gatherd_d256:
2498 case X86::BI__builtin_ia32_gatherq_d:
2499 case X86::BI__builtin_ia32_gatherq_d256:
2500 case X86::BI__builtin_ia32_gather3div2df:
2501 case X86::BI__builtin_ia32_gather3div2di:
2502 case X86::BI__builtin_ia32_gather3div4df:
2503 case X86::BI__builtin_ia32_gather3div4di:
2504 case X86::BI__builtin_ia32_gather3div4sf:
2505 case X86::BI__builtin_ia32_gather3div4si:
2506 case X86::BI__builtin_ia32_gather3div8sf:
2507 case X86::BI__builtin_ia32_gather3div8si:
2508 case X86::BI__builtin_ia32_gather3siv2df:
2509 case X86::BI__builtin_ia32_gather3siv2di:
2510 case X86::BI__builtin_ia32_gather3siv4df:
2511 case X86::BI__builtin_ia32_gather3siv4di:
2512 case X86::BI__builtin_ia32_gather3siv4sf:
2513 case X86::BI__builtin_ia32_gather3siv4si:
2514 case X86::BI__builtin_ia32_gather3siv8sf:
2515 case X86::BI__builtin_ia32_gather3siv8si:
2516 case X86::BI__builtin_ia32_gathersiv8df:
2517 case X86::BI__builtin_ia32_gathersiv16sf:
2518 case X86::BI__builtin_ia32_gatherdiv8df:
2519 case X86::BI__builtin_ia32_gatherdiv16sf:
2520 case X86::BI__builtin_ia32_gathersiv8di:
2521 case X86::BI__builtin_ia32_gathersiv16si:
2522 case X86::BI__builtin_ia32_gatherdiv8di:
2523 case X86::BI__builtin_ia32_gatherdiv16si:
2524 case X86::BI__builtin_ia32_scatterdiv2df:
2525 case X86::BI__builtin_ia32_scatterdiv2di:
2526 case X86::BI__builtin_ia32_scatterdiv4df:
2527 case X86::BI__builtin_ia32_scatterdiv4di:
2528 case X86::BI__builtin_ia32_scatterdiv4sf:
2529 case X86::BI__builtin_ia32_scatterdiv4si:
2530 case X86::BI__builtin_ia32_scatterdiv8sf:
2531 case X86::BI__builtin_ia32_scatterdiv8si:
2532 case X86::BI__builtin_ia32_scattersiv2df:
2533 case X86::BI__builtin_ia32_scattersiv2di:
2534 case X86::BI__builtin_ia32_scattersiv4df:
2535 case X86::BI__builtin_ia32_scattersiv4di:
2536 case X86::BI__builtin_ia32_scattersiv4sf:
2537 case X86::BI__builtin_ia32_scattersiv4si:
2538 case X86::BI__builtin_ia32_scattersiv8sf:
2539 case X86::BI__builtin_ia32_scattersiv8si:
2540 case X86::BI__builtin_ia32_scattersiv8df:
2541 case X86::BI__builtin_ia32_scattersiv16sf:
2542 case X86::BI__builtin_ia32_scatterdiv8df:
2543 case X86::BI__builtin_ia32_scatterdiv16sf:
2544 case X86::BI__builtin_ia32_scattersiv8di:
2545 case X86::BI__builtin_ia32_scattersiv16si:
2546 case X86::BI__builtin_ia32_scatterdiv8di:
2547 case X86::BI__builtin_ia32_scatterdiv16si:
2548 ArgNum = 4;
2549 break;
2550 }
2551
2552 llvm::APSInt Result;
2553
2554 // We can't check the value of a dependent argument.
2555 Expr *Arg = TheCall->getArg(ArgNum);
2556 if (Arg->isTypeDependent() || Arg->isValueDependent())
2557 return false;
2558
2559 // Check constant-ness first.
2560 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2561 return true;
2562
2563 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2564 return false;
2565
2566 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2567 << Arg->getSourceRange();
2568}
2569
Craig Topper51738f82018-04-26 20:14:46 +00002570static bool isX86_32Builtin(unsigned BuiltinID) {
2571 // These builtins only work on x86-32 targets.
2572 switch (BuiltinID) {
2573 case X86::BI__builtin_ia32_readeflags_u32:
2574 case X86::BI__builtin_ia32_writeeflags_u32:
2575 return true;
2576 }
2577
2578 return false;
2579}
2580
Craig Topperf0ddc892016-09-23 04:48:27 +00002581bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2582 if (BuiltinID == X86::BI__builtin_cpu_supports)
2583 return SemaBuiltinCpuSupports(*this, TheCall);
2584
Craig Topper699ae0c2017-08-10 20:28:30 +00002585 if (BuiltinID == X86::BI__builtin_cpu_is)
2586 return SemaBuiltinCpuIs(*this, TheCall);
2587
Craig Topper51738f82018-04-26 20:14:46 +00002588 // Check for 32-bit only builtins on a 64-bit target.
2589 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2590 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
2591 return Diag(TheCall->getCallee()->getLocStart(),
2592 diag::err_32_bit_builtin_64_bit_tgt);
2593
Craig Toppera7e253e2016-09-23 04:48:31 +00002594 // If the intrinsic has rounding or SAE make sure its valid.
2595 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2596 return true;
2597
Craig Topperdf5beb22017-03-13 17:16:50 +00002598 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2599 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2600 return true;
2601
Craig Topperf0ddc892016-09-23 04:48:27 +00002602 // For intrinsics which take an immediate value as part of the instruction,
2603 // range check them here.
2604 int i = 0, l = 0, u = 0;
2605 switch (BuiltinID) {
2606 default:
2607 return false;
Craig Topper11899b02018-06-05 21:54:35 +00002608 case X86::BI__builtin_ia32_vec_ext_v2si:
Craig Topperf3914b72018-06-06 00:24:55 +00002609 case X86::BI__builtin_ia32_vec_ext_v2di:
Craig Topper3428bee2018-06-08 03:24:47 +00002610 case X86::BI__builtin_ia32_vextractf128_pd256:
2611 case X86::BI__builtin_ia32_vextractf128_ps256:
2612 case X86::BI__builtin_ia32_vextractf128_si256:
2613 case X86::BI__builtin_ia32_extract128i256:
2614 case X86::BI__builtin_ia32_extractf64x4:
2615 case X86::BI__builtin_ia32_extracti64x4:
2616 case X86::BI__builtin_ia32_extractf32x8:
2617 case X86::BI__builtin_ia32_extracti32x8:
2618 case X86::BI__builtin_ia32_extractf64x2_256:
2619 case X86::BI__builtin_ia32_extracti64x2_256:
2620 case X86::BI__builtin_ia32_extractf32x4_256:
2621 case X86::BI__builtin_ia32_extracti32x4_256:
Craig Topper11899b02018-06-05 21:54:35 +00002622 i = 1; l = 0; u = 1;
2623 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002624 case X86::BI__builtin_ia32_vec_set_v2di:
Craig Topper3428bee2018-06-08 03:24:47 +00002625 case X86::BI__builtin_ia32_vinsertf128_pd256:
2626 case X86::BI__builtin_ia32_vinsertf128_ps256:
2627 case X86::BI__builtin_ia32_vinsertf128_si256:
2628 case X86::BI__builtin_ia32_insert128i256:
2629 case X86::BI__builtin_ia32_insertf32x8:
2630 case X86::BI__builtin_ia32_inserti32x8:
2631 case X86::BI__builtin_ia32_insertf64x4:
2632 case X86::BI__builtin_ia32_inserti64x4:
2633 case X86::BI__builtin_ia32_insertf64x2_256:
2634 case X86::BI__builtin_ia32_inserti64x2_256:
2635 case X86::BI__builtin_ia32_insertf32x4_256:
2636 case X86::BI__builtin_ia32_inserti32x4_256:
Craig Topperf3914b72018-06-06 00:24:55 +00002637 i = 2; l = 0; u = 1;
2638 break;
Craig Topperacf56012018-06-08 00:59:27 +00002639 case X86::BI__builtin_ia32_vpermilpd:
Craig Topper11899b02018-06-05 21:54:35 +00002640 case X86::BI__builtin_ia32_vec_ext_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00002641 case X86::BI__builtin_ia32_vec_ext_v4si:
2642 case X86::BI__builtin_ia32_vec_ext_v4sf:
2643 case X86::BI__builtin_ia32_vec_ext_v4di:
Craig Topper3428bee2018-06-08 03:24:47 +00002644 case X86::BI__builtin_ia32_extractf32x4:
2645 case X86::BI__builtin_ia32_extracti32x4:
2646 case X86::BI__builtin_ia32_extractf64x2_512:
2647 case X86::BI__builtin_ia32_extracti64x2_512:
Craig Topper11899b02018-06-05 21:54:35 +00002648 i = 1; l = 0; u = 3;
2649 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002650 case X86::BI_mm_prefetch:
2651 case X86::BI__builtin_ia32_vec_ext_v8hi:
2652 case X86::BI__builtin_ia32_vec_ext_v8si:
2653 i = 1; l = 0; u = 7;
2654 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002655 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper7d17d722018-06-08 00:00:21 +00002656 case X86::BI__builtin_ia32_blendpd:
Craig Topper422a1bb2018-06-08 07:18:33 +00002657 case X86::BI__builtin_ia32_shufpd:
Craig Topper11899b02018-06-05 21:54:35 +00002658 case X86::BI__builtin_ia32_vec_set_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00002659 case X86::BI__builtin_ia32_vec_set_v4si:
2660 case X86::BI__builtin_ia32_vec_set_v4di:
Craig Topper93921362018-06-07 23:03:08 +00002661 case X86::BI__builtin_ia32_shuf_f32x4_256:
2662 case X86::BI__builtin_ia32_shuf_f64x2_256:
2663 case X86::BI__builtin_ia32_shuf_i32x4_256:
2664 case X86::BI__builtin_ia32_shuf_i64x2_256:
Craig Topper3428bee2018-06-08 03:24:47 +00002665 case X86::BI__builtin_ia32_insertf64x2_512:
2666 case X86::BI__builtin_ia32_inserti64x2_512:
2667 case X86::BI__builtin_ia32_insertf32x4:
2668 case X86::BI__builtin_ia32_inserti32x4:
Craig Topper39c87102016-05-18 03:18:12 +00002669 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002670 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002671 case X86::BI__builtin_ia32_vpermil2pd:
2672 case X86::BI__builtin_ia32_vpermil2pd256:
2673 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002674 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002675 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002676 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002677 case X86::BI__builtin_ia32_cmpb128_mask:
2678 case X86::BI__builtin_ia32_cmpw128_mask:
2679 case X86::BI__builtin_ia32_cmpd128_mask:
2680 case X86::BI__builtin_ia32_cmpq128_mask:
2681 case X86::BI__builtin_ia32_cmpb256_mask:
2682 case X86::BI__builtin_ia32_cmpw256_mask:
2683 case X86::BI__builtin_ia32_cmpd256_mask:
2684 case X86::BI__builtin_ia32_cmpq256_mask:
2685 case X86::BI__builtin_ia32_cmpb512_mask:
2686 case X86::BI__builtin_ia32_cmpw512_mask:
2687 case X86::BI__builtin_ia32_cmpd512_mask:
2688 case X86::BI__builtin_ia32_cmpq512_mask:
2689 case X86::BI__builtin_ia32_ucmpb128_mask:
2690 case X86::BI__builtin_ia32_ucmpw128_mask:
2691 case X86::BI__builtin_ia32_ucmpd128_mask:
2692 case X86::BI__builtin_ia32_ucmpq128_mask:
2693 case X86::BI__builtin_ia32_ucmpb256_mask:
2694 case X86::BI__builtin_ia32_ucmpw256_mask:
2695 case X86::BI__builtin_ia32_ucmpd256_mask:
2696 case X86::BI__builtin_ia32_ucmpq256_mask:
2697 case X86::BI__builtin_ia32_ucmpb512_mask:
2698 case X86::BI__builtin_ia32_ucmpw512_mask:
2699 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002700 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002701 case X86::BI__builtin_ia32_vpcomub:
2702 case X86::BI__builtin_ia32_vpcomuw:
2703 case X86::BI__builtin_ia32_vpcomud:
2704 case X86::BI__builtin_ia32_vpcomuq:
2705 case X86::BI__builtin_ia32_vpcomb:
2706 case X86::BI__builtin_ia32_vpcomw:
2707 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002708 case X86::BI__builtin_ia32_vpcomq:
Craig Topperf3914b72018-06-06 00:24:55 +00002709 case X86::BI__builtin_ia32_vec_set_v8hi:
2710 case X86::BI__builtin_ia32_vec_set_v8si:
Craig Topper39c87102016-05-18 03:18:12 +00002711 i = 2; l = 0; u = 7;
2712 break;
Craig Topperacf56012018-06-08 00:59:27 +00002713 case X86::BI__builtin_ia32_vpermilpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002714 case X86::BI__builtin_ia32_roundps:
2715 case X86::BI__builtin_ia32_roundpd:
2716 case X86::BI__builtin_ia32_roundps256:
2717 case X86::BI__builtin_ia32_roundpd256:
Craig Topperf3914b72018-06-06 00:24:55 +00002718 case X86::BI__builtin_ia32_vec_ext_v16qi:
2719 case X86::BI__builtin_ia32_vec_ext_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00002720 i = 1; l = 0; u = 15;
2721 break;
Craig Topper7d17d722018-06-08 00:00:21 +00002722 case X86::BI__builtin_ia32_pblendd128:
2723 case X86::BI__builtin_ia32_blendps:
2724 case X86::BI__builtin_ia32_blendpd256:
Craig Topper422a1bb2018-06-08 07:18:33 +00002725 case X86::BI__builtin_ia32_shufpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002726 case X86::BI__builtin_ia32_roundss:
2727 case X86::BI__builtin_ia32_roundsd:
2728 case X86::BI__builtin_ia32_rangepd128_mask:
2729 case X86::BI__builtin_ia32_rangepd256_mask:
2730 case X86::BI__builtin_ia32_rangepd512_mask:
2731 case X86::BI__builtin_ia32_rangeps128_mask:
2732 case X86::BI__builtin_ia32_rangeps256_mask:
2733 case X86::BI__builtin_ia32_rangeps512_mask:
2734 case X86::BI__builtin_ia32_getmantsd_round_mask:
2735 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00002736 case X86::BI__builtin_ia32_vec_set_v16qi:
2737 case X86::BI__builtin_ia32_vec_set_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00002738 i = 2; l = 0; u = 15;
2739 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002740 case X86::BI__builtin_ia32_vec_ext_v32qi:
2741 i = 1; l = 0; u = 31;
2742 break;
Craig Topper39c87102016-05-18 03:18:12 +00002743 case X86::BI__builtin_ia32_cmpps:
2744 case X86::BI__builtin_ia32_cmpss:
2745 case X86::BI__builtin_ia32_cmppd:
2746 case X86::BI__builtin_ia32_cmpsd:
2747 case X86::BI__builtin_ia32_cmpps256:
2748 case X86::BI__builtin_ia32_cmppd256:
2749 case X86::BI__builtin_ia32_cmpps128_mask:
2750 case X86::BI__builtin_ia32_cmppd128_mask:
2751 case X86::BI__builtin_ia32_cmpps256_mask:
2752 case X86::BI__builtin_ia32_cmppd256_mask:
2753 case X86::BI__builtin_ia32_cmpps512_mask:
2754 case X86::BI__builtin_ia32_cmppd512_mask:
2755 case X86::BI__builtin_ia32_cmpsd_mask:
2756 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00002757 case X86::BI__builtin_ia32_vec_set_v32qi:
Craig Topper39c87102016-05-18 03:18:12 +00002758 i = 2; l = 0; u = 31;
2759 break;
Craig Topperacf56012018-06-08 00:59:27 +00002760 case X86::BI__builtin_ia32_vpermilps:
2761 case X86::BI__builtin_ia32_vpermilps256:
2762 case X86::BI__builtin_ia32_vpermilpd512:
2763 case X86::BI__builtin_ia32_vpermilps512:
Craig Topper03de1662018-06-08 06:13:16 +00002764 case X86::BI__builtin_ia32_pshufd:
2765 case X86::BI__builtin_ia32_pshufd256:
2766 case X86::BI__builtin_ia32_pshufd512:
2767 case X86::BI__builtin_ia32_pshufhw:
2768 case X86::BI__builtin_ia32_pshufhw256:
2769 case X86::BI__builtin_ia32_pshufhw512:
2770 case X86::BI__builtin_ia32_pshuflw:
2771 case X86::BI__builtin_ia32_pshuflw256:
2772 case X86::BI__builtin_ia32_pshuflw512:
Craig Topper39c87102016-05-18 03:18:12 +00002773 case X86::BI__builtin_ia32_vcvtps2ph:
Craig Topper23a30222017-11-08 04:54:26 +00002774 case X86::BI__builtin_ia32_vcvtps2ph_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002775 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper23a30222017-11-08 04:54:26 +00002776 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2777 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002778 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2779 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2780 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2781 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2782 case X86::BI__builtin_ia32_rndscaleps_mask:
2783 case X86::BI__builtin_ia32_rndscalepd_mask:
2784 case X86::BI__builtin_ia32_reducepd128_mask:
2785 case X86::BI__builtin_ia32_reducepd256_mask:
2786 case X86::BI__builtin_ia32_reducepd512_mask:
2787 case X86::BI__builtin_ia32_reduceps128_mask:
2788 case X86::BI__builtin_ia32_reduceps256_mask:
2789 case X86::BI__builtin_ia32_reduceps512_mask:
2790 case X86::BI__builtin_ia32_prold512_mask:
2791 case X86::BI__builtin_ia32_prolq512_mask:
2792 case X86::BI__builtin_ia32_prold128_mask:
2793 case X86::BI__builtin_ia32_prold256_mask:
2794 case X86::BI__builtin_ia32_prolq128_mask:
2795 case X86::BI__builtin_ia32_prolq256_mask:
2796 case X86::BI__builtin_ia32_prord128_mask:
2797 case X86::BI__builtin_ia32_prord256_mask:
2798 case X86::BI__builtin_ia32_prorq128_mask:
2799 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002800 case X86::BI__builtin_ia32_fpclasspd128_mask:
2801 case X86::BI__builtin_ia32_fpclasspd256_mask:
2802 case X86::BI__builtin_ia32_fpclassps128_mask:
2803 case X86::BI__builtin_ia32_fpclassps256_mask:
2804 case X86::BI__builtin_ia32_fpclassps512_mask:
2805 case X86::BI__builtin_ia32_fpclasspd512_mask:
2806 case X86::BI__builtin_ia32_fpclasssd_mask:
2807 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002808 i = 1; l = 0; u = 255;
2809 break;
Craig Topper9d3962f2018-06-08 18:00:22 +00002810 case X86::BI__builtin_ia32_vperm2f128_pd256:
2811 case X86::BI__builtin_ia32_vperm2f128_ps256:
2812 case X86::BI__builtin_ia32_vperm2f128_si256:
2813 case X86::BI__builtin_ia32_permti256:
Craig Topper7d17d722018-06-08 00:00:21 +00002814 case X86::BI__builtin_ia32_pblendw128:
2815 case X86::BI__builtin_ia32_pblendw256:
2816 case X86::BI__builtin_ia32_blendps256:
2817 case X86::BI__builtin_ia32_pblendd256:
Craig Topper39c87102016-05-18 03:18:12 +00002818 case X86::BI__builtin_ia32_palignr128:
2819 case X86::BI__builtin_ia32_palignr256:
Craig Topper8e3689c2018-05-22 20:48:24 +00002820 case X86::BI__builtin_ia32_palignr512:
Craig Toppere56819e2018-06-07 21:27:41 +00002821 case X86::BI__builtin_ia32_alignq512:
2822 case X86::BI__builtin_ia32_alignd512:
2823 case X86::BI__builtin_ia32_alignd128:
2824 case X86::BI__builtin_ia32_alignd256:
2825 case X86::BI__builtin_ia32_alignq128:
2826 case X86::BI__builtin_ia32_alignq256:
Craig Topper39c87102016-05-18 03:18:12 +00002827 case X86::BI__builtin_ia32_vcomisd:
2828 case X86::BI__builtin_ia32_vcomiss:
Craig Topper93921362018-06-07 23:03:08 +00002829 case X86::BI__builtin_ia32_shuf_f32x4:
2830 case X86::BI__builtin_ia32_shuf_f64x2:
2831 case X86::BI__builtin_ia32_shuf_i32x4:
2832 case X86::BI__builtin_ia32_shuf_i64x2:
Craig Topper422a1bb2018-06-08 07:18:33 +00002833 case X86::BI__builtin_ia32_shufpd512:
2834 case X86::BI__builtin_ia32_shufps:
2835 case X86::BI__builtin_ia32_shufps256:
2836 case X86::BI__builtin_ia32_shufps512:
Craig Topper39c87102016-05-18 03:18:12 +00002837 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2838 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2839 case X86::BI__builtin_ia32_dbpsadbw512_mask:
Craig Topper91926432018-01-11 01:38:02 +00002840 case X86::BI__builtin_ia32_vpshldd128_mask:
2841 case X86::BI__builtin_ia32_vpshldd256_mask:
2842 case X86::BI__builtin_ia32_vpshldd512_mask:
2843 case X86::BI__builtin_ia32_vpshldq128_mask:
2844 case X86::BI__builtin_ia32_vpshldq256_mask:
2845 case X86::BI__builtin_ia32_vpshldq512_mask:
2846 case X86::BI__builtin_ia32_vpshldw128_mask:
2847 case X86::BI__builtin_ia32_vpshldw256_mask:
2848 case X86::BI__builtin_ia32_vpshldw512_mask:
2849 case X86::BI__builtin_ia32_vpshrdd128_mask:
2850 case X86::BI__builtin_ia32_vpshrdd256_mask:
2851 case X86::BI__builtin_ia32_vpshrdd512_mask:
2852 case X86::BI__builtin_ia32_vpshrdq128_mask:
2853 case X86::BI__builtin_ia32_vpshrdq256_mask:
2854 case X86::BI__builtin_ia32_vpshrdq512_mask:
2855 case X86::BI__builtin_ia32_vpshrdw128_mask:
2856 case X86::BI__builtin_ia32_vpshrdw256_mask:
2857 case X86::BI__builtin_ia32_vpshrdw512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002858 i = 2; l = 0; u = 255;
2859 break;
2860 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2861 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2862 case X86::BI__builtin_ia32_fixupimmps512_mask:
2863 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2864 case X86::BI__builtin_ia32_fixupimmsd_mask:
2865 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2866 case X86::BI__builtin_ia32_fixupimmss_mask:
2867 case X86::BI__builtin_ia32_fixupimmss_maskz:
2868 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2869 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2870 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2871 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2872 case X86::BI__builtin_ia32_fixupimmps128_mask:
2873 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2874 case X86::BI__builtin_ia32_fixupimmps256_mask:
2875 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2876 case X86::BI__builtin_ia32_pternlogd512_mask:
2877 case X86::BI__builtin_ia32_pternlogd512_maskz:
2878 case X86::BI__builtin_ia32_pternlogq512_mask:
2879 case X86::BI__builtin_ia32_pternlogq512_maskz:
2880 case X86::BI__builtin_ia32_pternlogd128_mask:
2881 case X86::BI__builtin_ia32_pternlogd128_maskz:
2882 case X86::BI__builtin_ia32_pternlogd256_mask:
2883 case X86::BI__builtin_ia32_pternlogd256_maskz:
2884 case X86::BI__builtin_ia32_pternlogq128_mask:
2885 case X86::BI__builtin_ia32_pternlogq128_maskz:
2886 case X86::BI__builtin_ia32_pternlogq256_mask:
2887 case X86::BI__builtin_ia32_pternlogq256_maskz:
2888 i = 3; l = 0; u = 255;
2889 break;
Craig Topper9625db02017-03-12 22:19:10 +00002890 case X86::BI__builtin_ia32_gatherpfdpd:
2891 case X86::BI__builtin_ia32_gatherpfdps:
2892 case X86::BI__builtin_ia32_gatherpfqpd:
2893 case X86::BI__builtin_ia32_gatherpfqps:
2894 case X86::BI__builtin_ia32_scatterpfdpd:
2895 case X86::BI__builtin_ia32_scatterpfdps:
2896 case X86::BI__builtin_ia32_scatterpfqpd:
2897 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00002898 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00002899 break;
Craig Topper39c87102016-05-18 03:18:12 +00002900 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2901 case X86::BI__builtin_ia32_rndscaless_round_mask:
2902 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002903 break;
Craig Topperd3623152018-06-07 17:28:03 +00002904 case X86::BI__builtin_ia32_pslldqi128:
2905 case X86::BI__builtin_ia32_pslldqi256:
2906 case X86::BI__builtin_ia32_pslldqi512:
2907 case X86::BI__builtin_ia32_psrldqi128:
2908 case X86::BI__builtin_ia32_psrldqi256:
2909 case X86::BI__builtin_ia32_psrldqi512:
2910 i = 1; l = 0; u = 1023;
2911 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002912 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002913 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002914}
2915
Richard Smith55ce3522012-06-25 20:30:08 +00002916/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2917/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2918/// Returns true when the format fits the function and the FormatStringInfo has
2919/// been populated.
2920bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2921 FormatStringInfo *FSI) {
2922 FSI->HasVAListArg = Format->getFirstArg() == 0;
2923 FSI->FormatIdx = Format->getFormatIdx() - 1;
2924 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002925
Richard Smith55ce3522012-06-25 20:30:08 +00002926 // The way the format attribute works in GCC, the implicit this argument
2927 // of member functions is counted. However, it doesn't appear in our own
2928 // lists, so decrement format_idx in that case.
2929 if (IsCXXMember) {
2930 if(FSI->FormatIdx == 0)
2931 return false;
2932 --FSI->FormatIdx;
2933 if (FSI->FirstDataArg != 0)
2934 --FSI->FirstDataArg;
2935 }
2936 return true;
2937}
Mike Stump11289f42009-09-09 15:08:12 +00002938
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002939/// Checks if a the given expression evaluates to null.
2940///
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002941/// Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002942static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002943 // If the expression has non-null type, it doesn't evaluate to null.
2944 if (auto nullability
2945 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2946 if (*nullability == NullabilityKind::NonNull)
2947 return false;
2948 }
2949
Ted Kremeneka146db32014-01-17 06:24:47 +00002950 // As a special case, transparent unions initialized with zero are
2951 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002952 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002953 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2954 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002955 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002956 if (const InitListExpr *ILE =
2957 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002958 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002959 }
2960
2961 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002962 return (!Expr->isValueDependent() &&
2963 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2964 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002965}
2966
2967static void CheckNonNullArgument(Sema &S,
2968 const Expr *ArgExpr,
2969 SourceLocation CallSiteLoc) {
2970 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002971 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2972 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002973}
2974
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002975bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2976 FormatStringInfo FSI;
2977 if ((GetFormatStringType(Format) == FST_NSString) &&
2978 getFormatStringInfo(Format, false, &FSI)) {
2979 Idx = FSI.FormatIdx;
2980 return true;
2981 }
2982 return false;
2983}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002984
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002985/// Diagnose use of %s directive in an NSString which is being passed
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002986/// as formatting string to formatting method.
2987static void
2988DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2989 const NamedDecl *FDecl,
2990 Expr **Args,
2991 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002992 unsigned Idx = 0;
2993 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002994 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2995 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002996 Idx = 2;
2997 Format = true;
2998 }
2999 else
3000 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3001 if (S.GetFormatNSStringIdx(I, Idx)) {
3002 Format = true;
3003 break;
3004 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003005 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003006 if (!Format || NumArgs <= Idx)
3007 return;
3008 const Expr *FormatExpr = Args[Idx];
3009 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
3010 FormatExpr = CSCE->getSubExpr();
3011 const StringLiteral *FormatString;
3012 if (const ObjCStringLiteral *OSL =
3013 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
3014 FormatString = OSL->getString();
3015 else
3016 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
3017 if (!FormatString)
3018 return;
3019 if (S.FormatStringHasSArg(FormatString)) {
3020 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
3021 << "%s" << 1 << 1;
3022 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
3023 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003024 }
3025}
3026
Douglas Gregorb4866e82015-06-19 18:13:19 +00003027/// Determine whether the given type has a non-null nullability annotation.
3028static bool isNonNullType(ASTContext &ctx, QualType type) {
3029 if (auto nullability = type->getNullability(ctx))
3030 return *nullability == NullabilityKind::NonNull;
3031
3032 return false;
3033}
3034
Ted Kremenek2bc73332014-01-17 06:24:43 +00003035static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00003036 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00003037 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00003038 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00003039 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00003040 assert((FDecl || Proto) && "Need a function declaration or prototype");
3041
Ted Kremenek9aedc152014-01-17 06:24:56 +00003042 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00003043 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00003044 if (FDecl) {
3045 // Handle the nonnull attribute on the function/method declaration itself.
3046 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3047 if (!NonNull->args_size()) {
3048 // Easy case: all pointer arguments are nonnull.
3049 for (const auto *Arg : Args)
3050 if (S.isValidPointerAttrType(Arg->getType()))
3051 CheckNonNullArgument(S, Arg, CallSiteLoc);
3052 return;
3053 }
Richard Smith588bd9b2014-08-27 04:59:42 +00003054
Joel E. Denny81508102018-03-13 14:51:22 +00003055 for (const ParamIdx &Idx : NonNull->args()) {
3056 unsigned IdxAST = Idx.getASTIndex();
3057 if (IdxAST >= Args.size())
Douglas Gregorb4866e82015-06-19 18:13:19 +00003058 continue;
3059 if (NonNullArgs.empty())
3060 NonNullArgs.resize(Args.size());
Joel E. Denny81508102018-03-13 14:51:22 +00003061 NonNullArgs.set(IdxAST);
Douglas Gregorb4866e82015-06-19 18:13:19 +00003062 }
Richard Smith588bd9b2014-08-27 04:59:42 +00003063 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00003064 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00003065
Douglas Gregorb4866e82015-06-19 18:13:19 +00003066 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3067 // Handle the nonnull attribute on the parameters of the
3068 // function/method.
3069 ArrayRef<ParmVarDecl*> parms;
3070 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
3071 parms = FD->parameters();
3072 else
3073 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3074
3075 unsigned ParamIndex = 0;
3076 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3077 I != E; ++I, ++ParamIndex) {
3078 const ParmVarDecl *PVD = *I;
3079 if (PVD->hasAttr<NonNullAttr>() ||
3080 isNonNullType(S.Context, PVD->getType())) {
3081 if (NonNullArgs.empty())
3082 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00003083
Douglas Gregorb4866e82015-06-19 18:13:19 +00003084 NonNullArgs.set(ParamIndex);
3085 }
3086 }
3087 } else {
3088 // If we have a non-function, non-method declaration but no
3089 // function prototype, try to dig out the function prototype.
3090 if (!Proto) {
3091 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
3092 QualType type = VD->getType().getNonReferenceType();
3093 if (auto pointerType = type->getAs<PointerType>())
3094 type = pointerType->getPointeeType();
3095 else if (auto blockType = type->getAs<BlockPointerType>())
3096 type = blockType->getPointeeType();
3097 // FIXME: data member pointers?
3098
3099 // Dig out the function prototype, if there is one.
3100 Proto = type->getAs<FunctionProtoType>();
3101 }
3102 }
3103
3104 // Fill in non-null argument information from the nullability
3105 // information on the parameter types (if we have them).
3106 if (Proto) {
3107 unsigned Index = 0;
3108 for (auto paramType : Proto->getParamTypes()) {
3109 if (isNonNullType(S.Context, paramType)) {
3110 if (NonNullArgs.empty())
3111 NonNullArgs.resize(Args.size());
3112
3113 NonNullArgs.set(Index);
3114 }
3115
3116 ++Index;
3117 }
3118 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00003119 }
Richard Smith588bd9b2014-08-27 04:59:42 +00003120
Douglas Gregorb4866e82015-06-19 18:13:19 +00003121 // Check for non-null arguments.
3122 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3123 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00003124 if (NonNullArgs[ArgIndex])
3125 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00003126 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00003127}
3128
Richard Smith55ce3522012-06-25 20:30:08 +00003129/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00003130/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
3131/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00003132void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00003133 const Expr *ThisArg, ArrayRef<const Expr *> Args,
3134 bool IsMemberFunction, SourceLocation Loc,
3135 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00003136 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00003137 if (CurContext->isDependentContext())
3138 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00003139
Ted Kremenekb8176da2010-09-09 04:33:05 +00003140 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00003141 llvm::SmallBitVector CheckedVarArgs;
3142 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003143 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00003144 // Only create vector if there are format attributes.
3145 CheckedVarArgs.resize(Args.size());
3146
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003147 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00003148 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00003149 }
Richard Smithd7293d72013-08-05 18:49:43 +00003150 }
Richard Smith55ce3522012-06-25 20:30:08 +00003151
3152 // Refuse POD arguments that weren't caught by the format string
3153 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00003154 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3155 if (CallType != VariadicDoesNotApply &&
3156 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00003157 unsigned NumParams = Proto ? Proto->getNumParams()
3158 : FDecl && isa<FunctionDecl>(FDecl)
3159 ? cast<FunctionDecl>(FDecl)->getNumParams()
3160 : FDecl && isa<ObjCMethodDecl>(FDecl)
3161 ? cast<ObjCMethodDecl>(FDecl)->param_size()
3162 : 0;
3163
Alp Toker9cacbab2014-01-20 20:26:09 +00003164 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00003165 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00003166 if (const Expr *Arg = Args[ArgIdx]) {
3167 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3168 checkVariadicArgument(Arg, CallType);
3169 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00003170 }
Richard Smithd7293d72013-08-05 18:49:43 +00003171 }
Mike Stump11289f42009-09-09 15:08:12 +00003172
Douglas Gregorb4866e82015-06-19 18:13:19 +00003173 if (FDecl || Proto) {
3174 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00003175
Richard Trieu41bc0992013-06-22 00:20:41 +00003176 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00003177 if (FDecl) {
3178 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +00003179 CheckArgumentWithTypeTag(I, Args, Loc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00003180 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00003181 }
George Burgess IVce6284b2017-01-28 02:19:40 +00003182
3183 if (FD)
3184 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00003185}
3186
3187/// CheckConstructorCall - Check a constructor call for correctness and safety
3188/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003189void Sema::CheckConstructorCall(FunctionDecl *FDecl,
3190 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003191 const FunctionProtoType *Proto,
3192 SourceLocation Loc) {
3193 VariadicCallType CallType =
3194 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00003195 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
3196 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00003197}
3198
3199/// CheckFunctionCall - Check a direct function call for various correctness
3200/// and safety properties not strictly enforced by the C type system.
3201bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
3202 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00003203 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
3204 isa<CXXMethodDecl>(FDecl);
3205 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
3206 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00003207 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
3208 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00003209 Expr** Args = TheCall->getArgs();
3210 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00003211
3212 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00003213 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00003214 // If this is a call to a member operator, hide the first argument
3215 // from checkCall.
3216 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00003217 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00003218 ++Args;
3219 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00003220 } else if (IsMemberFunction)
3221 ImplicitThis =
3222 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
3223
3224 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00003225 IsMemberFunction, TheCall->getRParenLoc(),
3226 TheCall->getCallee()->getSourceRange(), CallType);
3227
3228 IdentifierInfo *FnInfo = FDecl->getIdentifier();
3229 // None of the checks below are needed for functions that don't have
3230 // simple names (e.g., C++ conversion functions).
3231 if (!FnInfo)
3232 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003233
Richard Trieua7f30b12016-12-06 01:42:28 +00003234 CheckAbsoluteValueFunction(TheCall, FDecl);
3235 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00003236
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003237 if (getLangOpts().ObjC1)
3238 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003239
Anna Zaks22122702012-01-17 00:37:07 +00003240 unsigned CMId = FDecl->getMemoryFunctionKind();
3241 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00003242 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00003243
Anna Zaks201d4892012-01-13 21:52:01 +00003244 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00003245 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00003246 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00003247 else if (CMId == Builtin::BIstrncat)
3248 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00003249 else
Anna Zaks22122702012-01-17 00:37:07 +00003250 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003251
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003252 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00003253}
3254
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003255bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00003256 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00003257 VariadicCallType CallType =
3258 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003259
George Burgess IVce6284b2017-01-28 02:19:40 +00003260 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
3261 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00003262 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003263
3264 return false;
3265}
3266
Richard Trieu664c4c62013-06-20 21:03:13 +00003267bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
3268 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00003269 QualType Ty;
3270 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00003271 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00003272 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00003273 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00003274 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003275 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003276
Douglas Gregorb4866e82015-06-19 18:13:19 +00003277 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
3278 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003279 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003280
Richard Trieu664c4c62013-06-20 21:03:13 +00003281 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00003282 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00003283 CallType = VariadicDoesNotApply;
3284 } else if (Ty->isBlockPointerType()) {
3285 CallType = VariadicBlock;
3286 } else { // Ty->isFunctionPointerType()
3287 CallType = VariadicFunction;
3288 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003289
George Burgess IVce6284b2017-01-28 02:19:40 +00003290 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00003291 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
3292 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00003293 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00003294
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003295 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00003296}
3297
Richard Trieu41bc0992013-06-22 00:20:41 +00003298/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
3299/// such as function pointers returned from functions.
3300bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003301 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00003302 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00003303 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00003304 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00003305 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00003306 TheCall->getCallee()->getSourceRange(), CallType);
3307
3308 return false;
3309}
3310
Tim Northovere94a34c2014-03-11 10:49:14 +00003311static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00003312 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00003313 return false;
3314
JF Bastiendda2cb12016-04-18 18:01:49 +00003315 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00003316 switch (Op) {
3317 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00003318 case AtomicExpr::AO__opencl_atomic_init:
Tim Northovere94a34c2014-03-11 10:49:14 +00003319 llvm_unreachable("There is no ordering argument for an init");
3320
3321 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00003322 case AtomicExpr::AO__opencl_atomic_load:
Tim Northovere94a34c2014-03-11 10:49:14 +00003323 case AtomicExpr::AO__atomic_load_n:
3324 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00003325 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
3326 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00003327
3328 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00003329 case AtomicExpr::AO__opencl_atomic_store:
Tim Northovere94a34c2014-03-11 10:49:14 +00003330 case AtomicExpr::AO__atomic_store:
3331 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00003332 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
3333 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
3334 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00003335
3336 default:
3337 return true;
3338 }
3339}
3340
Richard Smithfeea8832012-04-12 05:08:17 +00003341ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
3342 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003343 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3344 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003345
Yaxun Liu39195062017-08-04 18:16:31 +00003346 // All the non-OpenCL operations take one of the following forms.
3347 // The OpenCL operations take the __c11 forms with one extra argument for
3348 // synchronization scope.
Richard Smithfeea8832012-04-12 05:08:17 +00003349 enum {
3350 // C __c11_atomic_init(A *, C)
3351 Init,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003352
Richard Smithfeea8832012-04-12 05:08:17 +00003353 // C __c11_atomic_load(A *, int)
3354 Load,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003355
Richard Smithfeea8832012-04-12 05:08:17 +00003356 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00003357 LoadCopy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003358
Eric Fiselier8d662442016-03-30 23:39:56 +00003359 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00003360 Copy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003361
Richard Smithfeea8832012-04-12 05:08:17 +00003362 // C __c11_atomic_add(A *, M, int)
3363 Arithmetic,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003364
Richard Smithfeea8832012-04-12 05:08:17 +00003365 // C __atomic_exchange_n(A *, CP, int)
3366 Xchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003367
Richard Smithfeea8832012-04-12 05:08:17 +00003368 // void __atomic_exchange(A *, C *, CP, int)
3369 GNUXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003370
Richard Smithfeea8832012-04-12 05:08:17 +00003371 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
3372 C11CmpXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003373
Richard Smithfeea8832012-04-12 05:08:17 +00003374 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
3375 GNUCmpXchg
3376 } Form = Init;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003377
Yaxun Liu39195062017-08-04 18:16:31 +00003378 const unsigned NumForm = GNUCmpXchg + 1;
Eric Fiselier8d662442016-03-30 23:39:56 +00003379 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
3380 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00003381 // where:
3382 // C is an appropriate type,
3383 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
3384 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
3385 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
3386 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003387
Yaxun Liu39195062017-08-04 18:16:31 +00003388 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
3389 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
3390 "need to update code for modified forms");
Gabor Horvath98bd0982015-03-16 09:59:54 +00003391 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
3392 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
3393 AtomicExpr::AO__atomic_load,
3394 "need to update code for modified C11 atomics");
Yaxun Liu39195062017-08-04 18:16:31 +00003395 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
3396 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
3397 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
3398 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
3399 IsOpenCL;
Richard Smithfeea8832012-04-12 05:08:17 +00003400 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
3401 Op == AtomicExpr::AO__atomic_store_n ||
3402 Op == AtomicExpr::AO__atomic_exchange_n ||
3403 Op == AtomicExpr::AO__atomic_compare_exchange_n;
3404 bool IsAddSub = false;
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003405 bool IsMinMax = false;
Richard Smithfeea8832012-04-12 05:08:17 +00003406
3407 switch (Op) {
3408 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00003409 case AtomicExpr::AO__opencl_atomic_init:
Richard Smithfeea8832012-04-12 05:08:17 +00003410 Form = Init;
3411 break;
3412
3413 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00003414 case AtomicExpr::AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00003415 case AtomicExpr::AO__atomic_load_n:
3416 Form = Load;
3417 break;
3418
Richard Smithfeea8832012-04-12 05:08:17 +00003419 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00003420 Form = LoadCopy;
3421 break;
3422
3423 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00003424 case AtomicExpr::AO__opencl_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00003425 case AtomicExpr::AO__atomic_store:
3426 case AtomicExpr::AO__atomic_store_n:
3427 Form = Copy;
3428 break;
3429
3430 case AtomicExpr::AO__c11_atomic_fetch_add:
3431 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00003432 case AtomicExpr::AO__opencl_atomic_fetch_add:
3433 case AtomicExpr::AO__opencl_atomic_fetch_sub:
3434 case AtomicExpr::AO__opencl_atomic_fetch_min:
3435 case AtomicExpr::AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00003436 case AtomicExpr::AO__atomic_fetch_add:
3437 case AtomicExpr::AO__atomic_fetch_sub:
3438 case AtomicExpr::AO__atomic_add_fetch:
3439 case AtomicExpr::AO__atomic_sub_fetch:
3440 IsAddSub = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00003441 LLVM_FALLTHROUGH;
Richard Smithfeea8832012-04-12 05:08:17 +00003442 case AtomicExpr::AO__c11_atomic_fetch_and:
3443 case AtomicExpr::AO__c11_atomic_fetch_or:
3444 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00003445 case AtomicExpr::AO__opencl_atomic_fetch_and:
3446 case AtomicExpr::AO__opencl_atomic_fetch_or:
3447 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Richard Smithfeea8832012-04-12 05:08:17 +00003448 case AtomicExpr::AO__atomic_fetch_and:
3449 case AtomicExpr::AO__atomic_fetch_or:
3450 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00003451 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00003452 case AtomicExpr::AO__atomic_and_fetch:
3453 case AtomicExpr::AO__atomic_or_fetch:
3454 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00003455 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00003456 Form = Arithmetic;
3457 break;
3458
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003459 case AtomicExpr::AO__atomic_fetch_min:
3460 case AtomicExpr::AO__atomic_fetch_max:
3461 IsMinMax = true;
3462 Form = Arithmetic;
3463 break;
3464
Richard Smithfeea8832012-04-12 05:08:17 +00003465 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00003466 case AtomicExpr::AO__opencl_atomic_exchange:
Richard Smithfeea8832012-04-12 05:08:17 +00003467 case AtomicExpr::AO__atomic_exchange_n:
3468 Form = Xchg;
3469 break;
3470
3471 case AtomicExpr::AO__atomic_exchange:
3472 Form = GNUXchg;
3473 break;
3474
3475 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3476 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +00003477 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3478 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00003479 Form = C11CmpXchg;
3480 break;
3481
3482 case AtomicExpr::AO__atomic_compare_exchange:
3483 case AtomicExpr::AO__atomic_compare_exchange_n:
3484 Form = GNUCmpXchg;
3485 break;
3486 }
3487
Yaxun Liu39195062017-08-04 18:16:31 +00003488 unsigned AdjustedNumArgs = NumArgs[Form];
3489 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3490 ++AdjustedNumArgs;
Richard Smithfeea8832012-04-12 05:08:17 +00003491 // Check we have the right number of arguments.
Yaxun Liu39195062017-08-04 18:16:31 +00003492 if (TheCall->getNumArgs() < AdjustedNumArgs) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003493 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003494 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003495 << TheCall->getCallee()->getSourceRange();
3496 return ExprError();
Yaxun Liu39195062017-08-04 18:16:31 +00003497 } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3498 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003499 diag::err_typecheck_call_too_many_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003500 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003501 << TheCall->getCallee()->getSourceRange();
3502 return ExprError();
3503 }
3504
Richard Smithfeea8832012-04-12 05:08:17 +00003505 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003506 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00003507 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3508 if (ConvertedPtr.isInvalid())
3509 return ExprError();
3510
3511 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003512 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3513 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00003514 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003515 << Ptr->getType() << Ptr->getSourceRange();
3516 return ExprError();
3517 }
3518
Richard Smithfeea8832012-04-12 05:08:17 +00003519 // For a __c11 builtin, this should be a pointer to an _Atomic type.
3520 QualType AtomTy = pointerType->getPointeeType(); // 'A'
3521 QualType ValType = AtomTy; // 'C'
3522 if (IsC11) {
3523 if (!AtomTy->isAtomicType()) {
3524 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3525 << Ptr->getType() << Ptr->getSourceRange();
3526 return ExprError();
3527 }
Yaxun Liu39195062017-08-04 18:16:31 +00003528 if (AtomTy.isConstQualified() ||
3529 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
Richard Smithe00921a2012-09-15 06:09:58 +00003530 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
Yaxun Liu39195062017-08-04 18:16:31 +00003531 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3532 << Ptr->getSourceRange();
Richard Smithe00921a2012-09-15 06:09:58 +00003533 return ExprError();
3534 }
Richard Smithfeea8832012-04-12 05:08:17 +00003535 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00003536 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00003537 if (ValType.isConstQualified()) {
3538 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3539 << Ptr->getType() << Ptr->getSourceRange();
3540 return ExprError();
3541 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003542 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003543
Richard Smithfeea8832012-04-12 05:08:17 +00003544 // For an arithmetic operation, the implied arithmetic must be well-formed.
3545 if (Form == Arithmetic) {
3546 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003547 if (IsAddSub && !ValType->isIntegerType()
3548 && !ValType->isPointerType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003549 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3550 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3551 return ExprError();
3552 }
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003553 if (IsMinMax) {
3554 const BuiltinType *BT = ValType->getAs<BuiltinType>();
3555 if (!BT || (BT->getKind() != BuiltinType::Int &&
3556 BT->getKind() != BuiltinType::UInt)) {
3557 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_int32_or_ptr);
3558 return ExprError();
3559 }
3560 }
3561 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003562 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3563 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3564 return ExprError();
3565 }
David Majnemere85cff82015-01-28 05:48:06 +00003566 if (IsC11 && ValType->isPointerType() &&
3567 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3568 diag::err_incomplete_type)) {
3569 return ExprError();
3570 }
Richard Smithfeea8832012-04-12 05:08:17 +00003571 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3572 // For __atomic_*_n operations, the value type must be a scalar integral or
3573 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003574 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00003575 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3576 return ExprError();
3577 }
3578
Eli Friedmanaa769812013-09-11 03:49:34 +00003579 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3580 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003581 // For GNU atomics, require a trivially-copyable type. This is not part of
3582 // the GNU atomics specification, but we enforce it for sanity.
3583 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003584 << Ptr->getType() << Ptr->getSourceRange();
3585 return ExprError();
3586 }
3587
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003588 switch (ValType.getObjCLifetime()) {
3589 case Qualifiers::OCL_None:
3590 case Qualifiers::OCL_ExplicitNone:
3591 // okay
3592 break;
3593
3594 case Qualifiers::OCL_Weak:
3595 case Qualifiers::OCL_Strong:
3596 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00003597 // FIXME: Can this happen? By this point, ValType should be known
3598 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003599 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3600 << ValType << Ptr->getSourceRange();
3601 return ExprError();
3602 }
3603
JF Bastien7f0a05a2018-05-25 00:07:09 +00003604 // All atomic operations have an overload which takes a pointer to a volatile
3605 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
3606 // into the result or the other operands. Similarly atomic_load takes a
3607 // pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00003608 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00003609 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003610 QualType ResultType = ValType;
Yaxun Liu39195062017-08-04 18:16:31 +00003611 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3612 Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003613 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00003614 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003615 ResultType = Context.BoolTy;
3616
Richard Smithfeea8832012-04-12 05:08:17 +00003617 // The type of a parameter passed 'by value'. In the GNU atomics, such
3618 // arguments are actually passed as pointers.
3619 QualType ByValType = ValType; // 'CP'
JF Bastien7f0a05a2018-05-25 00:07:09 +00003620 bool IsPassedByAddress = false;
3621 if (!IsC11 && !IsN) {
Richard Smithfeea8832012-04-12 05:08:17 +00003622 ByValType = Ptr->getType();
JF Bastien7f0a05a2018-05-25 00:07:09 +00003623 IsPassedByAddress = true;
3624 }
Richard Smithfeea8832012-04-12 05:08:17 +00003625
JF Bastien7f0a05a2018-05-25 00:07:09 +00003626 // The first argument's non-CV pointer type is used to deduce the type of
3627 // subsequent arguments, except for:
3628 // - weak flag (always converted to bool)
3629 // - memory order (always converted to int)
3630 // - scope (always converted to int)
3631 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003632 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00003633 if (i < NumVals[Form] + 1) {
3634 switch (i) {
JF Bastien7f0a05a2018-05-25 00:07:09 +00003635 case 0:
3636 // The first argument is always a pointer. It has a fixed type.
3637 // It is always dereferenced, a nullptr is undefined.
3638 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
3639 // Nothing else to do: we already know all we want about this pointer.
3640 continue;
Richard Smithfeea8832012-04-12 05:08:17 +00003641 case 1:
3642 // The second argument is the non-atomic operand. For arithmetic, this
3643 // is always passed by value, and for a compare_exchange it is always
3644 // passed by address. For the rest, GNU uses by-address and C11 uses
3645 // by-value.
3646 assert(Form != Load);
3647 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3648 Ty = ValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00003649 else if (Form == Copy || Form == Xchg) {
3650 if (IsPassedByAddress)
3651 // The value pointer is always dereferenced, a nullptr is undefined.
3652 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
Richard Smithfeea8832012-04-12 05:08:17 +00003653 Ty = ByValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00003654 } else if (Form == Arithmetic)
Richard Smithfeea8832012-04-12 05:08:17 +00003655 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003656 else {
3657 Expr *ValArg = TheCall->getArg(i);
JF Bastien7f0a05a2018-05-25 00:07:09 +00003658 // The value pointer is always dereferenced, a nullptr is undefined.
Alex Lorenz67522152016-11-23 16:57:03 +00003659 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Alexander Richardson6d989432017-10-15 18:48:14 +00003660 LangAS AS = LangAS::Default;
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003661 // Keep address space of non-atomic pointer type.
3662 if (const PointerType *PtrTy =
3663 ValArg->getType()->getAs<PointerType>()) {
3664 AS = PtrTy->getPointeeType().getAddressSpace();
3665 }
3666 Ty = Context.getPointerType(
3667 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3668 }
Richard Smithfeea8832012-04-12 05:08:17 +00003669 break;
3670 case 2:
JF Bastien7f0a05a2018-05-25 00:07:09 +00003671 // The third argument to compare_exchange / GNU exchange is the desired
JF Bastien7853d5f2018-05-25 17:36:49 +00003672 // value, either by-value (for the C11 and *_n variant) or as a pointer.
3673 if (IsPassedByAddress)
JF Bastien7f0a05a2018-05-25 00:07:09 +00003674 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
Richard Smithfeea8832012-04-12 05:08:17 +00003675 Ty = ByValType;
3676 break;
3677 case 3:
3678 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3679 Ty = Context.BoolTy;
3680 break;
3681 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003682 } else {
Yaxun Liu39195062017-08-04 18:16:31 +00003683 // The order(s) and scope are always converted to int.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003684 Ty = Context.IntTy;
3685 }
Richard Smithfeea8832012-04-12 05:08:17 +00003686
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003687 InitializedEntity Entity =
3688 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00003689 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003690 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3691 if (Arg.isInvalid())
3692 return true;
3693 TheCall->setArg(i, Arg.get());
3694 }
3695
Richard Smithfeea8832012-04-12 05:08:17 +00003696 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003697 SmallVector<Expr*, 5> SubExprs;
3698 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00003699 switch (Form) {
3700 case Init:
3701 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00003702 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003703 break;
3704 case Load:
3705 SubExprs.push_back(TheCall->getArg(1)); // Order
3706 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00003707 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00003708 case Copy:
3709 case Arithmetic:
3710 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003711 SubExprs.push_back(TheCall->getArg(2)); // Order
3712 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003713 break;
3714 case GNUXchg:
3715 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3716 SubExprs.push_back(TheCall->getArg(3)); // Order
3717 SubExprs.push_back(TheCall->getArg(1)); // Val1
3718 SubExprs.push_back(TheCall->getArg(2)); // Val2
3719 break;
3720 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003721 SubExprs.push_back(TheCall->getArg(3)); // Order
3722 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003723 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00003724 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00003725 break;
3726 case GNUCmpXchg:
3727 SubExprs.push_back(TheCall->getArg(4)); // Order
3728 SubExprs.push_back(TheCall->getArg(1)); // Val1
3729 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3730 SubExprs.push_back(TheCall->getArg(2)); // Val2
3731 SubExprs.push_back(TheCall->getArg(3)); // Weak
3732 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003733 }
Tim Northovere94a34c2014-03-11 10:49:14 +00003734
3735 if (SubExprs.size() >= 2 && Form != Init) {
3736 llvm::APSInt Result(32);
3737 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3738 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00003739 Diag(SubExprs[1]->getLocStart(),
3740 diag::warn_atomic_op_has_invalid_memory_order)
3741 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00003742 }
3743
Yaxun Liu30d652a2017-08-15 16:02:49 +00003744 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3745 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3746 llvm::APSInt Result(32);
3747 if (Scope->isIntegerConstantExpr(Result, Context) &&
3748 !ScopeModel->isValid(Result.getZExtValue())) {
3749 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3750 << Scope->getSourceRange();
3751 }
3752 SubExprs.push_back(Scope);
3753 }
3754
Fariborz Jahanian615de762013-05-28 17:37:39 +00003755 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3756 SubExprs, ResultType, Op,
3757 TheCall->getRParenLoc());
3758
3759 if ((Op == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00003760 Op == AtomicExpr::AO__c11_atomic_store ||
3761 Op == AtomicExpr::AO__opencl_atomic_load ||
3762 Op == AtomicExpr::AO__opencl_atomic_store ) &&
Fariborz Jahanian615de762013-05-28 17:37:39 +00003763 Context.AtomicUsesUnsupportedLibcall(AE))
Yaxun Liu39195062017-08-04 18:16:31 +00003764 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3765 << ((Op == AtomicExpr::AO__c11_atomic_load ||
3766 Op == AtomicExpr::AO__opencl_atomic_load)
3767 ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003768
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003769 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003770}
3771
John McCall29ad95b2011-08-27 01:09:30 +00003772/// checkBuiltinArgument - Given a call to a builtin function, perform
3773/// normal type-checking on the given argument, updating the call in
3774/// place. This is useful when a builtin function requires custom
3775/// type-checking for some of its arguments but not necessarily all of
3776/// them.
3777///
3778/// Returns true on error.
3779static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3780 FunctionDecl *Fn = E->getDirectCallee();
3781 assert(Fn && "builtin call without direct callee!");
3782
3783 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3784 InitializedEntity Entity =
3785 InitializedEntity::InitializeParameter(S.Context, Param);
3786
3787 ExprResult Arg = E->getArg(0);
3788 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3789 if (Arg.isInvalid())
3790 return true;
3791
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003792 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003793 return false;
3794}
3795
Chris Lattnerdc046542009-05-08 06:58:22 +00003796/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3797/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3798/// type of its first argument. The main ActOnCallExpr routines have already
3799/// promoted the types of arguments because all of these calls are prototyped as
3800/// void(...).
3801///
3802/// This function goes through and does final semantic checking for these
3803/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003804ExprResult
3805Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003806 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003807 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3808 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3809
3810 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003811 if (TheCall->getNumArgs() < 1) {
3812 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3813 << 0 << 1 << TheCall->getNumArgs()
3814 << TheCall->getCallee()->getSourceRange();
3815 return ExprError();
3816 }
Mike Stump11289f42009-09-09 15:08:12 +00003817
Chris Lattnerdc046542009-05-08 06:58:22 +00003818 // Inspect the first argument of the atomic builtin. This should always be
3819 // a pointer type, whose element is an integral scalar or pointer type.
3820 // Because it is a pointer type, we don't have to worry about any implicit
3821 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003822 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003823 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003824 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3825 if (FirstArgResult.isInvalid())
3826 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003827 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003828 TheCall->setArg(0, FirstArg);
3829
John McCall31168b02011-06-15 23:02:42 +00003830 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3831 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003832 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3833 << FirstArg->getType() << FirstArg->getSourceRange();
3834 return ExprError();
3835 }
Mike Stump11289f42009-09-09 15:08:12 +00003836
John McCall31168b02011-06-15 23:02:42 +00003837 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003838 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003839 !ValType->isBlockPointerType()) {
3840 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3841 << FirstArg->getType() << FirstArg->getSourceRange();
3842 return ExprError();
3843 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003844
Aaron Ballmana383c942018-05-05 17:38:42 +00003845 if (ValType.isConstQualified()) {
3846 Diag(DRE->getLocStart(), diag::err_atomic_builtin_cannot_be_const)
3847 << FirstArg->getType() << FirstArg->getSourceRange();
3848 return ExprError();
3849 }
3850
John McCall31168b02011-06-15 23:02:42 +00003851 switch (ValType.getObjCLifetime()) {
3852 case Qualifiers::OCL_None:
3853 case Qualifiers::OCL_ExplicitNone:
3854 // okay
3855 break;
3856
3857 case Qualifiers::OCL_Weak:
3858 case Qualifiers::OCL_Strong:
3859 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003860 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003861 << ValType << FirstArg->getSourceRange();
3862 return ExprError();
3863 }
3864
John McCallb50451a2011-10-05 07:41:44 +00003865 // Strip any qualifiers off ValType.
3866 ValType = ValType.getUnqualifiedType();
3867
Chandler Carruth3973af72010-07-18 20:54:12 +00003868 // The majority of builtins return a value, but a few have special return
3869 // types, so allow them to override appropriately below.
3870 QualType ResultType = ValType;
3871
Chris Lattnerdc046542009-05-08 06:58:22 +00003872 // We need to figure out which concrete builtin this maps onto. For example,
3873 // __sync_fetch_and_add with a 2 byte object turns into
3874 // __sync_fetch_and_add_2.
3875#define BUILTIN_ROW(x) \
3876 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3877 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003878
Chris Lattnerdc046542009-05-08 06:58:22 +00003879 static const unsigned BuiltinIndices[][5] = {
3880 BUILTIN_ROW(__sync_fetch_and_add),
3881 BUILTIN_ROW(__sync_fetch_and_sub),
3882 BUILTIN_ROW(__sync_fetch_and_or),
3883 BUILTIN_ROW(__sync_fetch_and_and),
3884 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003885 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003886
Chris Lattnerdc046542009-05-08 06:58:22 +00003887 BUILTIN_ROW(__sync_add_and_fetch),
3888 BUILTIN_ROW(__sync_sub_and_fetch),
3889 BUILTIN_ROW(__sync_and_and_fetch),
3890 BUILTIN_ROW(__sync_or_and_fetch),
3891 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003892 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003893
Chris Lattnerdc046542009-05-08 06:58:22 +00003894 BUILTIN_ROW(__sync_val_compare_and_swap),
3895 BUILTIN_ROW(__sync_bool_compare_and_swap),
3896 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003897 BUILTIN_ROW(__sync_lock_release),
3898 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003899 };
Mike Stump11289f42009-09-09 15:08:12 +00003900#undef BUILTIN_ROW
3901
Chris Lattnerdc046542009-05-08 06:58:22 +00003902 // Determine the index of the size.
3903 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003904 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003905 case 1: SizeIndex = 0; break;
3906 case 2: SizeIndex = 1; break;
3907 case 4: SizeIndex = 2; break;
3908 case 8: SizeIndex = 3; break;
3909 case 16: SizeIndex = 4; break;
3910 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003911 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3912 << FirstArg->getType() << FirstArg->getSourceRange();
3913 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003914 }
Mike Stump11289f42009-09-09 15:08:12 +00003915
Chris Lattnerdc046542009-05-08 06:58:22 +00003916 // Each of these builtins has one pointer argument, followed by some number of
3917 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3918 // that we ignore. Find out which row of BuiltinIndices to read from as well
3919 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003920 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003921 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003922 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003923 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003924 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003925 case Builtin::BI__sync_fetch_and_add:
3926 case Builtin::BI__sync_fetch_and_add_1:
3927 case Builtin::BI__sync_fetch_and_add_2:
3928 case Builtin::BI__sync_fetch_and_add_4:
3929 case Builtin::BI__sync_fetch_and_add_8:
3930 case Builtin::BI__sync_fetch_and_add_16:
3931 BuiltinIndex = 0;
3932 break;
3933
3934 case Builtin::BI__sync_fetch_and_sub:
3935 case Builtin::BI__sync_fetch_and_sub_1:
3936 case Builtin::BI__sync_fetch_and_sub_2:
3937 case Builtin::BI__sync_fetch_and_sub_4:
3938 case Builtin::BI__sync_fetch_and_sub_8:
3939 case Builtin::BI__sync_fetch_and_sub_16:
3940 BuiltinIndex = 1;
3941 break;
3942
3943 case Builtin::BI__sync_fetch_and_or:
3944 case Builtin::BI__sync_fetch_and_or_1:
3945 case Builtin::BI__sync_fetch_and_or_2:
3946 case Builtin::BI__sync_fetch_and_or_4:
3947 case Builtin::BI__sync_fetch_and_or_8:
3948 case Builtin::BI__sync_fetch_and_or_16:
3949 BuiltinIndex = 2;
3950 break;
3951
3952 case Builtin::BI__sync_fetch_and_and:
3953 case Builtin::BI__sync_fetch_and_and_1:
3954 case Builtin::BI__sync_fetch_and_and_2:
3955 case Builtin::BI__sync_fetch_and_and_4:
3956 case Builtin::BI__sync_fetch_and_and_8:
3957 case Builtin::BI__sync_fetch_and_and_16:
3958 BuiltinIndex = 3;
3959 break;
Mike Stump11289f42009-09-09 15:08:12 +00003960
Douglas Gregor73722482011-11-28 16:30:08 +00003961 case Builtin::BI__sync_fetch_and_xor:
3962 case Builtin::BI__sync_fetch_and_xor_1:
3963 case Builtin::BI__sync_fetch_and_xor_2:
3964 case Builtin::BI__sync_fetch_and_xor_4:
3965 case Builtin::BI__sync_fetch_and_xor_8:
3966 case Builtin::BI__sync_fetch_and_xor_16:
3967 BuiltinIndex = 4;
3968 break;
3969
Hal Finkeld2208b52014-10-02 20:53:50 +00003970 case Builtin::BI__sync_fetch_and_nand:
3971 case Builtin::BI__sync_fetch_and_nand_1:
3972 case Builtin::BI__sync_fetch_and_nand_2:
3973 case Builtin::BI__sync_fetch_and_nand_4:
3974 case Builtin::BI__sync_fetch_and_nand_8:
3975 case Builtin::BI__sync_fetch_and_nand_16:
3976 BuiltinIndex = 5;
3977 WarnAboutSemanticsChange = true;
3978 break;
3979
Douglas Gregor73722482011-11-28 16:30:08 +00003980 case Builtin::BI__sync_add_and_fetch:
3981 case Builtin::BI__sync_add_and_fetch_1:
3982 case Builtin::BI__sync_add_and_fetch_2:
3983 case Builtin::BI__sync_add_and_fetch_4:
3984 case Builtin::BI__sync_add_and_fetch_8:
3985 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003986 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003987 break;
3988
3989 case Builtin::BI__sync_sub_and_fetch:
3990 case Builtin::BI__sync_sub_and_fetch_1:
3991 case Builtin::BI__sync_sub_and_fetch_2:
3992 case Builtin::BI__sync_sub_and_fetch_4:
3993 case Builtin::BI__sync_sub_and_fetch_8:
3994 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003995 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003996 break;
3997
3998 case Builtin::BI__sync_and_and_fetch:
3999 case Builtin::BI__sync_and_and_fetch_1:
4000 case Builtin::BI__sync_and_and_fetch_2:
4001 case Builtin::BI__sync_and_and_fetch_4:
4002 case Builtin::BI__sync_and_and_fetch_8:
4003 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004004 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00004005 break;
4006
4007 case Builtin::BI__sync_or_and_fetch:
4008 case Builtin::BI__sync_or_and_fetch_1:
4009 case Builtin::BI__sync_or_and_fetch_2:
4010 case Builtin::BI__sync_or_and_fetch_4:
4011 case Builtin::BI__sync_or_and_fetch_8:
4012 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004013 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00004014 break;
4015
4016 case Builtin::BI__sync_xor_and_fetch:
4017 case Builtin::BI__sync_xor_and_fetch_1:
4018 case Builtin::BI__sync_xor_and_fetch_2:
4019 case Builtin::BI__sync_xor_and_fetch_4:
4020 case Builtin::BI__sync_xor_and_fetch_8:
4021 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004022 BuiltinIndex = 10;
4023 break;
4024
4025 case Builtin::BI__sync_nand_and_fetch:
4026 case Builtin::BI__sync_nand_and_fetch_1:
4027 case Builtin::BI__sync_nand_and_fetch_2:
4028 case Builtin::BI__sync_nand_and_fetch_4:
4029 case Builtin::BI__sync_nand_and_fetch_8:
4030 case Builtin::BI__sync_nand_and_fetch_16:
4031 BuiltinIndex = 11;
4032 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00004033 break;
Mike Stump11289f42009-09-09 15:08:12 +00004034
Chris Lattnerdc046542009-05-08 06:58:22 +00004035 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00004036 case Builtin::BI__sync_val_compare_and_swap_1:
4037 case Builtin::BI__sync_val_compare_and_swap_2:
4038 case Builtin::BI__sync_val_compare_and_swap_4:
4039 case Builtin::BI__sync_val_compare_and_swap_8:
4040 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004041 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00004042 NumFixed = 2;
4043 break;
Douglas Gregor73722482011-11-28 16:30:08 +00004044
Chris Lattnerdc046542009-05-08 06:58:22 +00004045 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00004046 case Builtin::BI__sync_bool_compare_and_swap_1:
4047 case Builtin::BI__sync_bool_compare_and_swap_2:
4048 case Builtin::BI__sync_bool_compare_and_swap_4:
4049 case Builtin::BI__sync_bool_compare_and_swap_8:
4050 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004051 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00004052 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00004053 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00004054 break;
Douglas Gregor73722482011-11-28 16:30:08 +00004055
JF Bastien7f0a05a2018-05-25 00:07:09 +00004056 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +00004057 case Builtin::BI__sync_lock_test_and_set_1:
4058 case Builtin::BI__sync_lock_test_and_set_2:
4059 case Builtin::BI__sync_lock_test_and_set_4:
4060 case Builtin::BI__sync_lock_test_and_set_8:
4061 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004062 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00004063 break;
4064
Chris Lattnerdc046542009-05-08 06:58:22 +00004065 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00004066 case Builtin::BI__sync_lock_release_1:
4067 case Builtin::BI__sync_lock_release_2:
4068 case Builtin::BI__sync_lock_release_4:
4069 case Builtin::BI__sync_lock_release_8:
4070 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004071 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00004072 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00004073 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00004074 break;
Douglas Gregor73722482011-11-28 16:30:08 +00004075
4076 case Builtin::BI__sync_swap:
4077 case Builtin::BI__sync_swap_1:
4078 case Builtin::BI__sync_swap_2:
4079 case Builtin::BI__sync_swap_4:
4080 case Builtin::BI__sync_swap_8:
4081 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004082 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00004083 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00004084 }
Mike Stump11289f42009-09-09 15:08:12 +00004085
Chris Lattnerdc046542009-05-08 06:58:22 +00004086 // Now that we know how many fixed arguments we expect, first check that we
4087 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004088 if (TheCall->getNumArgs() < 1+NumFixed) {
4089 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
4090 << 0 << 1+NumFixed << TheCall->getNumArgs()
4091 << TheCall->getCallee()->getSourceRange();
4092 return ExprError();
4093 }
Mike Stump11289f42009-09-09 15:08:12 +00004094
Hal Finkeld2208b52014-10-02 20:53:50 +00004095 if (WarnAboutSemanticsChange) {
4096 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
4097 << TheCall->getCallee()->getSourceRange();
4098 }
4099
Chris Lattner5b9241b2009-05-08 15:36:58 +00004100 // Get the decl for the concrete builtin from this, we can tell what the
4101 // concrete integer type we should convert to is.
4102 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00004103 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00004104 FunctionDecl *NewBuiltinDecl;
4105 if (NewBuiltinID == BuiltinID)
4106 NewBuiltinDecl = FDecl;
4107 else {
4108 // Perform builtin lookup to avoid redeclaring it.
4109 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
4110 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
4111 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
4112 assert(Res.getFoundDecl());
4113 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004114 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00004115 return ExprError();
4116 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004117
John McCallcf142162010-08-07 06:22:56 +00004118 // The first argument --- the pointer --- has a fixed type; we
4119 // deduce the types of the rest of the arguments accordingly. Walk
4120 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00004121 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00004122 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00004123
Chris Lattnerdc046542009-05-08 06:58:22 +00004124 // GCC does an implicit conversion to the pointer or integer ValType. This
4125 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00004126 // Initialize the argument.
4127 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4128 ValType, /*consume*/ false);
4129 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00004130 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004131 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004132
Chris Lattnerdc046542009-05-08 06:58:22 +00004133 // Okay, we have something that *can* be converted to the right type. Check
4134 // to see if there is a potentially weird extension going on here. This can
4135 // happen when you do an atomic operation on something like an char* and
4136 // pass in 42. The 42 gets converted to char. This is even more strange
4137 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00004138 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004139 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00004140 }
Mike Stump11289f42009-09-09 15:08:12 +00004141
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004142 ASTContext& Context = this->getASTContext();
4143
4144 // Create a new DeclRefExpr to refer to the new decl.
4145 DeclRefExpr* NewDRE = DeclRefExpr::Create(
4146 Context,
4147 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00004148 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004149 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00004150 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004151 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00004152 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004153 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00004154
Chris Lattnerdc046542009-05-08 06:58:22 +00004155 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00004156 // FIXME: This loses syntactic information.
4157 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
4158 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
4159 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004160 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00004161
Chandler Carruthbc8cab12010-07-18 07:23:17 +00004162 // Change the result type of the call to match the original value type. This
4163 // is arbitrary, but the codegen for these builtins ins design to handle it
4164 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00004165 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004166
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004167 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00004168}
4169
Michael Zolotukhin84df1232015-09-08 23:52:33 +00004170/// SemaBuiltinNontemporalOverloaded - We have a call to
4171/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
4172/// overloaded function based on the pointer type of its last argument.
4173///
4174/// This function goes through and does final semantic checking for these
4175/// builtins.
4176ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
4177 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
4178 DeclRefExpr *DRE =
4179 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4180 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4181 unsigned BuiltinID = FDecl->getBuiltinID();
4182 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
4183 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
4184 "Unexpected nontemporal load/store builtin!");
4185 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
4186 unsigned numArgs = isStore ? 2 : 1;
4187
4188 // Ensure that we have the proper number of arguments.
4189 if (checkArgCount(*this, TheCall, numArgs))
4190 return ExprError();
4191
4192 // Inspect the last argument of the nontemporal builtin. This should always
4193 // be a pointer type, from which we imply the type of the memory access.
4194 // Because it is a pointer type, we don't have to worry about any implicit
4195 // casts here.
4196 Expr *PointerArg = TheCall->getArg(numArgs - 1);
4197 ExprResult PointerArgResult =
4198 DefaultFunctionArrayLvalueConversion(PointerArg);
4199
4200 if (PointerArgResult.isInvalid())
4201 return ExprError();
4202 PointerArg = PointerArgResult.get();
4203 TheCall->setArg(numArgs - 1, PointerArg);
4204
4205 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
4206 if (!pointerType) {
4207 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
4208 << PointerArg->getType() << PointerArg->getSourceRange();
4209 return ExprError();
4210 }
4211
4212 QualType ValType = pointerType->getPointeeType();
4213
4214 // Strip any qualifiers off ValType.
4215 ValType = ValType.getUnqualifiedType();
4216 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4217 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
4218 !ValType->isVectorType()) {
4219 Diag(DRE->getLocStart(),
4220 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
4221 << PointerArg->getType() << PointerArg->getSourceRange();
4222 return ExprError();
4223 }
4224
4225 if (!isStore) {
4226 TheCall->setType(ValType);
4227 return TheCallResult;
4228 }
4229
4230 ExprResult ValArg = TheCall->getArg(0);
4231 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4232 Context, ValType, /*consume*/ false);
4233 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
4234 if (ValArg.isInvalid())
4235 return ExprError();
4236
4237 TheCall->setArg(0, ValArg.get());
4238 TheCall->setType(Context.VoidTy);
4239 return TheCallResult;
4240}
4241
Chris Lattner6436fb62009-02-18 06:01:06 +00004242/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00004243/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00004244/// Note: It might also make sense to do the UTF-16 conversion here (would
4245/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00004246bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00004247 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00004248 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
4249
Douglas Gregorfb65e592011-07-27 05:40:30 +00004250 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00004251 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
4252 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00004253 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00004254 }
Mike Stump11289f42009-09-09 15:08:12 +00004255
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004256 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004257 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004258 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00004259 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
4260 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4261 llvm::UTF16 *ToPtr = &ToBuf[0];
4262
4263 llvm::ConversionResult Result =
4264 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4265 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004266 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00004267 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004268 Diag(Arg->getLocStart(),
4269 diag::warn_cfstring_truncated) << Arg->getSourceRange();
4270 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00004271 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004272}
4273
Mehdi Amini06d367c2016-10-24 20:39:34 +00004274/// CheckObjCString - Checks that the format string argument to the os_log()
4275/// and os_trace() functions is correct, and converts it to const char *.
4276ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
4277 Arg = Arg->IgnoreParenCasts();
4278 auto *Literal = dyn_cast<StringLiteral>(Arg);
4279 if (!Literal) {
4280 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
4281 Literal = ObjcLiteral->getString();
4282 }
4283 }
4284
4285 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
4286 return ExprError(
4287 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
4288 << Arg->getSourceRange());
4289 }
4290
4291 ExprResult Result(Literal);
4292 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
4293 InitializedEntity Entity =
4294 InitializedEntity::InitializeParameter(Context, ResultTy, false);
4295 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
4296 return Result;
4297}
4298
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004299/// Check that the user is calling the appropriate va_start builtin for the
4300/// target and calling convention.
4301static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
4302 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
4303 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
Martin Storsjo022e7822017-07-17 20:49:45 +00004304 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004305 bool IsWindows = TT.isOSWindows();
Martin Storsjo022e7822017-07-17 20:49:45 +00004306 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
4307 if (IsX64 || IsAArch64) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004308 CallingConv CC = CC_C;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004309 if (const FunctionDecl *FD = S.getCurFunctionDecl())
4310 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
4311 if (IsMSVAStart) {
4312 // Don't allow this in System V ABI functions.
Martin Storsjo022e7822017-07-17 20:49:45 +00004313 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004314 return S.Diag(Fn->getLocStart(),
4315 diag::err_ms_va_start_used_in_sysv_function);
4316 } else {
Martin Storsjo022e7822017-07-17 20:49:45 +00004317 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004318 // On x64 Windows, don't allow this in System V ABI functions.
4319 // (Yes, that means there's no corresponding way to support variadic
4320 // System V ABI functions on Windows.)
4321 if ((IsWindows && CC == CC_X86_64SysV) ||
Martin Storsjo022e7822017-07-17 20:49:45 +00004322 (!IsWindows && CC == CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004323 return S.Diag(Fn->getLocStart(),
4324 diag::err_va_start_used_in_wrong_abi_function)
4325 << !IsWindows;
4326 }
4327 return false;
4328 }
4329
4330 if (IsMSVAStart)
Martin Storsjo022e7822017-07-17 20:49:45 +00004331 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004332 return false;
4333}
4334
4335static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
4336 ParmVarDecl **LastParam = nullptr) {
4337 // Determine whether the current function, block, or obj-c method is variadic
4338 // and get its parameter list.
4339 bool IsVariadic = false;
4340 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00004341 DeclContext *Caller = S.CurContext;
4342 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
4343 IsVariadic = Block->isVariadic();
4344 Params = Block->parameters();
4345 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004346 IsVariadic = FD->isVariadic();
4347 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00004348 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004349 IsVariadic = MD->isVariadic();
4350 // FIXME: This isn't correct for methods (results in bogus warning).
4351 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00004352 } else if (isa<CapturedDecl>(Caller)) {
4353 // We don't support va_start in a CapturedDecl.
4354 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
4355 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004356 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00004357 // This must be some other declcontext that parses exprs.
4358 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
4359 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004360 }
4361
4362 if (!IsVariadic) {
Reid Klecknerf1deb832017-05-04 19:51:05 +00004363 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004364 return true;
4365 }
4366
4367 if (LastParam)
4368 *LastParam = Params.empty() ? nullptr : Params.back();
4369
4370 return false;
4371}
4372
Charles Davisc7d5c942015-09-17 20:55:33 +00004373/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
4374/// for validity. Emit an error and return true on failure; return false
4375/// on success.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004376bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00004377 Expr *Fn = TheCall->getCallee();
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004378
4379 if (checkVAStartABI(*this, BuiltinID, Fn))
4380 return true;
4381
Chris Lattner08464942007-12-28 05:29:59 +00004382 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00004383 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004384 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004385 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4386 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00004387 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004388 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00004389 return true;
4390 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00004391
4392 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00004393 return Diag(TheCall->getLocEnd(),
4394 diag::err_typecheck_call_too_few_args_at_least)
4395 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00004396 }
4397
John McCall29ad95b2011-08-27 01:09:30 +00004398 // Type-check the first argument normally.
4399 if (checkBuiltinArgument(*this, TheCall, 0))
4400 return true;
4401
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004402 // Check that the current function is variadic, and get its last parameter.
4403 ParmVarDecl *LastParam;
4404 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
Chris Lattner43be2e62007-12-19 23:59:04 +00004405 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004406
Chris Lattner43be2e62007-12-19 23:59:04 +00004407 // Verify that the second argument to the builtin is the last argument of the
4408 // current function or method.
4409 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00004410 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004411
Nico Weber9eea7642013-05-24 23:31:57 +00004412 // These are valid if SecondArgIsLastNamedArgument is false after the next
4413 // block.
4414 QualType Type;
4415 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00004416 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00004417
Anders Carlsson6a8350b2008-02-11 04:20:54 +00004418 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
4419 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004420 SecondArgIsLastNamedArgument = PV == LastParam;
Nico Weber9eea7642013-05-24 23:31:57 +00004421
4422 Type = PV->getType();
4423 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00004424 IsCRegister =
4425 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00004426 }
4427 }
Mike Stump11289f42009-09-09 15:08:12 +00004428
Chris Lattner43be2e62007-12-19 23:59:04 +00004429 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00004430 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00004431 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00004432 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00004433 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
4434 // Promotable integers are UB, but enumerations need a bit of
4435 // extra checking to see what their promotable type actually is.
4436 if (!Type->isPromotableIntegerType())
4437 return false;
4438 if (!Type->isEnumeralType())
4439 return true;
4440 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
4441 return !(ED &&
4442 Context.typesAreCompatible(ED->getPromotionType(), Type));
4443 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00004444 unsigned Reason = 0;
4445 if (Type->isReferenceType()) Reason = 1;
4446 else if (IsCRegister) Reason = 2;
4447 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00004448 Diag(ParamLoc, diag::note_parameter_type) << Type;
4449 }
4450
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00004451 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00004452 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00004453}
Chris Lattner43be2e62007-12-19 23:59:04 +00004454
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +00004455bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004456 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
4457 // const char *named_addr);
4458
4459 Expr *Func = Call->getCallee();
4460
4461 if (Call->getNumArgs() < 3)
4462 return Diag(Call->getLocEnd(),
4463 diag::err_typecheck_call_too_few_args_at_least)
4464 << 0 /*function call*/ << 3 << Call->getNumArgs();
4465
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004466 // Type-check the first argument normally.
4467 if (checkBuiltinArgument(*this, Call, 0))
4468 return true;
4469
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004470 // Check that the current function is variadic.
4471 if (checkVAStartIsInVariadicFunction(*this, Func))
4472 return true;
4473
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004474 // __va_start on Windows does not validate the parameter qualifiers
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004475
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004476 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4477 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4478
4479 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4480 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4481
4482 const QualType &ConstCharPtrTy =
4483 Context.getPointerType(Context.CharTy.withConst());
4484 if (!Arg1Ty->isPointerType() ||
4485 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4486 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4487 << Arg1->getType() << ConstCharPtrTy
4488 << 1 /* different class */
4489 << 0 /* qualifier difference */
4490 << 3 /* parameter mismatch */
4491 << 2 << Arg1->getType() << ConstCharPtrTy;
4492
4493 const QualType SizeTy = Context.getSizeType();
4494 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4495 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4496 << Arg2->getType() << SizeTy
4497 << 1 /* different class */
4498 << 0 /* qualifier difference */
4499 << 3 /* parameter mismatch */
4500 << 3 << Arg2->getType() << SizeTy;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004501
4502 return false;
4503}
4504
Chris Lattner2da14fb2007-12-20 00:26:33 +00004505/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4506/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00004507bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4508 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00004509 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004510 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00004511 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00004512 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004513 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004514 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00004515 << SourceRange(TheCall->getArg(2)->getLocStart(),
4516 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004517
John Wiegley01296292011-04-08 18:41:53 +00004518 ExprResult OrigArg0 = TheCall->getArg(0);
4519 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004520
Chris Lattner2da14fb2007-12-20 00:26:33 +00004521 // Do standard promotions between the two arguments, returning their common
4522 // type.
Chris Lattner08464942007-12-28 05:29:59 +00004523 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00004524 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4525 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00004526
4527 // Make sure any conversions are pushed back into the call; this is
4528 // type safe since unordered compare builtins are declared as "_Bool
4529 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00004530 TheCall->setArg(0, OrigArg0.get());
4531 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00004532
John Wiegley01296292011-04-08 18:41:53 +00004533 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00004534 return false;
4535
Chris Lattner2da14fb2007-12-20 00:26:33 +00004536 // If the common type isn't a real floating type, then the arguments were
4537 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00004538 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00004539 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004540 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00004541 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4542 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004543
Chris Lattner2da14fb2007-12-20 00:26:33 +00004544 return false;
4545}
4546
Benjamin Kramer634fc102010-02-15 22:42:31 +00004547/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4548/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00004549/// to check everything. We expect the last argument to be a floating point
4550/// value.
4551bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4552 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00004553 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004554 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00004555 if (TheCall->getNumArgs() > NumArgs)
4556 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004557 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004558 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00004559 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004560 (*(TheCall->arg_end()-1))->getLocEnd());
4561
Benjamin Kramer64aae502010-02-16 10:07:31 +00004562 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00004563
Eli Friedman7e4faac2009-08-31 20:06:00 +00004564 if (OrigArg->isTypeDependent())
4565 return false;
4566
Chris Lattner68784ef2010-05-06 05:50:07 +00004567 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00004568 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00004569 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004570 diag::err_typecheck_call_invalid_unary_fp)
4571 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004572
Neil Hickey88c0fac2016-12-13 16:22:50 +00004573 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00004574 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00004575 // Only remove standard FloatCasts, leaving other casts inplace
4576 if (Cast->getCastKind() == CK_FloatingCast) {
4577 Expr *CastArg = Cast->getSubExpr();
4578 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4579 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4580 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4581 "promotion from float to either float or double is the only expected cast here");
4582 Cast->setSubExpr(nullptr);
4583 TheCall->setArg(NumArgs-1, CastArg);
4584 }
Chris Lattner68784ef2010-05-06 05:50:07 +00004585 }
4586 }
4587
Eli Friedman7e4faac2009-08-31 20:06:00 +00004588 return false;
4589}
4590
Tony Jiangbbc48e92017-05-24 15:13:32 +00004591// Customized Sema Checking for VSX builtins that have the following signature:
4592// vector [...] builtinName(vector [...], vector [...], const int);
4593// Which takes the same type of vectors (any legal vector type) for the first
4594// two arguments and takes compile time constant for the third argument.
4595// Example builtins are :
4596// vector double vec_xxpermdi(vector double, vector double, int);
4597// vector short vec_xxsldwi(vector short, vector short, int);
4598bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4599 unsigned ExpectedNumArgs = 3;
4600 if (TheCall->getNumArgs() < ExpectedNumArgs)
4601 return Diag(TheCall->getLocEnd(),
4602 diag::err_typecheck_call_too_few_args_at_least)
4603 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4604 << TheCall->getSourceRange();
4605
4606 if (TheCall->getNumArgs() > ExpectedNumArgs)
4607 return Diag(TheCall->getLocEnd(),
4608 diag::err_typecheck_call_too_many_args_at_most)
4609 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4610 << TheCall->getSourceRange();
4611
4612 // Check the third argument is a compile time constant
4613 llvm::APSInt Value;
4614 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4615 return Diag(TheCall->getLocStart(),
4616 diag::err_vsx_builtin_nonconstant_argument)
4617 << 3 /* argument index */ << TheCall->getDirectCallee()
4618 << SourceRange(TheCall->getArg(2)->getLocStart(),
4619 TheCall->getArg(2)->getLocEnd());
4620
4621 QualType Arg1Ty = TheCall->getArg(0)->getType();
4622 QualType Arg2Ty = TheCall->getArg(1)->getType();
4623
4624 // Check the type of argument 1 and argument 2 are vectors.
4625 SourceLocation BuiltinLoc = TheCall->getLocStart();
4626 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4627 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4628 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4629 << TheCall->getDirectCallee()
4630 << SourceRange(TheCall->getArg(0)->getLocStart(),
4631 TheCall->getArg(1)->getLocEnd());
4632 }
4633
4634 // Check the first two arguments are the same type.
4635 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4636 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4637 << TheCall->getDirectCallee()
4638 << SourceRange(TheCall->getArg(0)->getLocStart(),
4639 TheCall->getArg(1)->getLocEnd());
4640 }
4641
4642 // When default clang type checking is turned off and the customized type
4643 // checking is used, the returning type of the function must be explicitly
4644 // set. Otherwise it is _Bool by default.
4645 TheCall->setType(Arg1Ty);
4646
4647 return false;
4648}
4649
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004650/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4651// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00004652ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00004653 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004654 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00004655 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00004656 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4657 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004658
Nate Begemana0110022010-06-08 00:16:34 +00004659 // Determine which of the following types of shufflevector we're checking:
4660 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00004661 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00004662 QualType resType = TheCall->getArg(0)->getType();
4663 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00004664
Douglas Gregorc25f7662009-05-19 22:10:17 +00004665 if (!TheCall->getArg(0)->isTypeDependent() &&
4666 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00004667 QualType LHSType = TheCall->getArg(0)->getType();
4668 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00004669
Craig Topperbaca3892013-07-29 06:47:04 +00004670 if (!LHSType->isVectorType() || !RHSType->isVectorType())
4671 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004672 diag::err_vec_builtin_non_vector)
4673 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004674 << SourceRange(TheCall->getArg(0)->getLocStart(),
4675 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004676
Nate Begemana0110022010-06-08 00:16:34 +00004677 numElements = LHSType->getAs<VectorType>()->getNumElements();
4678 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00004679
Nate Begemana0110022010-06-08 00:16:34 +00004680 // Check to see if we have a call with 2 vector arguments, the unary shuffle
4681 // with mask. If so, verify that RHS is an integer vector type with the
4682 // same number of elts as lhs.
4683 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00004684 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00004685 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00004686 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004687 diag::err_vec_builtin_incompatible_vector)
4688 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004689 << SourceRange(TheCall->getArg(1)->getLocStart(),
4690 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004691 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00004692 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004693 diag::err_vec_builtin_incompatible_vector)
4694 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004695 << SourceRange(TheCall->getArg(0)->getLocStart(),
4696 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00004697 } else if (numElements != numResElements) {
4698 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00004699 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00004700 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004701 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004702 }
4703
4704 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00004705 if (TheCall->getArg(i)->isTypeDependent() ||
4706 TheCall->getArg(i)->isValueDependent())
4707 continue;
4708
Nate Begemana0110022010-06-08 00:16:34 +00004709 llvm::APSInt Result(32);
4710 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4711 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004712 diag::err_shufflevector_nonconstant_argument)
4713 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004714
Craig Topper50ad5b72013-08-03 17:40:38 +00004715 // Allow -1 which will be translated to undef in the IR.
4716 if (Result.isSigned() && Result.isAllOnesValue())
4717 continue;
4718
Chris Lattner7ab824e2008-08-10 02:05:13 +00004719 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004720 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004721 diag::err_shufflevector_argument_too_large)
4722 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004723 }
4724
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004725 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004726
Chris Lattner7ab824e2008-08-10 02:05:13 +00004727 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004728 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00004729 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004730 }
4731
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004732 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4733 TheCall->getCallee()->getLocStart(),
4734 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004735}
Chris Lattner43be2e62007-12-19 23:59:04 +00004736
Hal Finkelc4d7c822013-09-18 03:29:45 +00004737/// SemaConvertVectorExpr - Handle __builtin_convertvector
4738ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4739 SourceLocation BuiltinLoc,
4740 SourceLocation RParenLoc) {
4741 ExprValueKind VK = VK_RValue;
4742 ExprObjectKind OK = OK_Ordinary;
4743 QualType DstTy = TInfo->getType();
4744 QualType SrcTy = E->getType();
4745
4746 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4747 return ExprError(Diag(BuiltinLoc,
4748 diag::err_convertvector_non_vector)
4749 << E->getSourceRange());
4750 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4751 return ExprError(Diag(BuiltinLoc,
4752 diag::err_convertvector_non_vector_type));
4753
4754 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4755 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4756 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4757 if (SrcElts != DstElts)
4758 return ExprError(Diag(BuiltinLoc,
4759 diag::err_convertvector_incompatible_vector)
4760 << E->getSourceRange());
4761 }
4762
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004763 return new (Context)
4764 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00004765}
4766
Daniel Dunbarb7257262008-07-21 22:59:13 +00004767/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4768// This is declared to take (const void*, ...) and can take two
4769// optional constant int args.
4770bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00004771 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004772
Chris Lattner3b054132008-11-19 05:08:23 +00004773 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004774 return Diag(TheCall->getLocEnd(),
4775 diag::err_typecheck_call_too_many_args_at_most)
4776 << 0 /*function call*/ << 3 << NumArgs
4777 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004778
4779 // Argument 0 is checked for us and the remaining arguments must be
4780 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00004781 for (unsigned i = 1; i != NumArgs; ++i)
4782 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004783 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004784
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004785 return false;
4786}
4787
Hal Finkelf0417332014-07-17 14:25:55 +00004788/// SemaBuiltinAssume - Handle __assume (MS Extension).
4789// __assume does not evaluate its arguments, and should warn if its argument
4790// has side effects.
4791bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4792 Expr *Arg = TheCall->getArg(0);
4793 if (Arg->isInstantiationDependent()) return false;
4794
4795 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00004796 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00004797 << Arg->getSourceRange()
4798 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4799
4800 return false;
4801}
4802
David Majnemer86b1bfa2016-10-31 18:07:57 +00004803/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00004804/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4805/// than 8.
4806bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4807 // The alignment must be a constant integer.
4808 Expr *Arg = TheCall->getArg(1);
4809
4810 // We can't check the value of a dependent argument.
4811 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00004812 if (const auto *UE =
4813 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4814 if (UE->getKind() == UETT_AlignOf)
4815 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4816 << Arg->getSourceRange();
4817
David Majnemer51169932016-10-31 05:37:48 +00004818 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4819
4820 if (!Result.isPowerOf2())
4821 return Diag(TheCall->getLocStart(),
4822 diag::err_alignment_not_power_of_two)
4823 << Arg->getSourceRange();
4824
4825 if (Result < Context.getCharWidth())
4826 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4827 << (unsigned)Context.getCharWidth()
4828 << Arg->getSourceRange();
4829
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004830 if (Result > std::numeric_limits<int32_t>::max())
David Majnemer51169932016-10-31 05:37:48 +00004831 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004832 << std::numeric_limits<int32_t>::max()
David Majnemer51169932016-10-31 05:37:48 +00004833 << Arg->getSourceRange();
4834 }
4835
4836 return false;
4837}
4838
4839/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00004840/// as (const void*, size_t, ...) and can take one optional constant int arg.
4841bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4842 unsigned NumArgs = TheCall->getNumArgs();
4843
4844 if (NumArgs > 3)
4845 return Diag(TheCall->getLocEnd(),
4846 diag::err_typecheck_call_too_many_args_at_most)
4847 << 0 /*function call*/ << 3 << NumArgs
4848 << TheCall->getSourceRange();
4849
4850 // The alignment must be a constant integer.
4851 Expr *Arg = TheCall->getArg(1);
4852
4853 // We can't check the value of a dependent argument.
4854 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4855 llvm::APSInt Result;
4856 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4857 return true;
4858
4859 if (!Result.isPowerOf2())
4860 return Diag(TheCall->getLocStart(),
4861 diag::err_alignment_not_power_of_two)
4862 << Arg->getSourceRange();
4863 }
4864
4865 if (NumArgs > 2) {
4866 ExprResult Arg(TheCall->getArg(2));
4867 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4868 Context.getSizeType(), false);
4869 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4870 if (Arg.isInvalid()) return true;
4871 TheCall->setArg(2, Arg.get());
4872 }
Hal Finkelf0417332014-07-17 14:25:55 +00004873
4874 return false;
4875}
4876
Mehdi Amini06d367c2016-10-24 20:39:34 +00004877bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4878 unsigned BuiltinID =
4879 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4880 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4881
4882 unsigned NumArgs = TheCall->getNumArgs();
4883 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4884 if (NumArgs < NumRequiredArgs) {
4885 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4886 << 0 /* function call */ << NumRequiredArgs << NumArgs
4887 << TheCall->getSourceRange();
4888 }
4889 if (NumArgs >= NumRequiredArgs + 0x100) {
4890 return Diag(TheCall->getLocEnd(),
4891 diag::err_typecheck_call_too_many_args_at_most)
4892 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4893 << TheCall->getSourceRange();
4894 }
4895 unsigned i = 0;
4896
4897 // For formatting call, check buffer arg.
4898 if (!IsSizeCall) {
4899 ExprResult Arg(TheCall->getArg(i));
4900 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4901 Context, Context.VoidPtrTy, false);
4902 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4903 if (Arg.isInvalid())
4904 return true;
4905 TheCall->setArg(i, Arg.get());
4906 i++;
4907 }
4908
4909 // Check string literal arg.
4910 unsigned FormatIdx = i;
4911 {
4912 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4913 if (Arg.isInvalid())
4914 return true;
4915 TheCall->setArg(i, Arg.get());
4916 i++;
4917 }
4918
4919 // Make sure variadic args are scalar.
4920 unsigned FirstDataArg = i;
4921 while (i < NumArgs) {
4922 ExprResult Arg = DefaultVariadicArgumentPromotion(
4923 TheCall->getArg(i), VariadicFunction, nullptr);
4924 if (Arg.isInvalid())
4925 return true;
4926 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4927 if (ArgSize.getQuantity() >= 0x100) {
4928 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4929 << i << (int)ArgSize.getQuantity() << 0xff
4930 << TheCall->getSourceRange();
4931 }
4932 TheCall->setArg(i, Arg.get());
4933 i++;
4934 }
4935
4936 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4937 // call to avoid duplicate diagnostics.
4938 if (!IsSizeCall) {
4939 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4940 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4941 bool Success = CheckFormatArguments(
4942 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4943 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4944 CheckedVarArgs);
4945 if (!Success)
4946 return true;
4947 }
4948
4949 if (IsSizeCall) {
4950 TheCall->setType(Context.getSizeType());
4951 } else {
4952 TheCall->setType(Context.VoidPtrTy);
4953 }
4954 return false;
4955}
4956
Eric Christopher8d0c6212010-04-17 02:26:23 +00004957/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4958/// TheCall is a constant expression.
4959bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4960 llvm::APSInt &Result) {
4961 Expr *Arg = TheCall->getArg(ArgNum);
4962 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4963 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4964
4965 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4966
4967 if (!Arg->isIntegerConstantExpr(Result, Context))
4968 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004969 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004970
Chris Lattnerd545ad12009-09-23 06:06:36 +00004971 return false;
4972}
4973
Richard Sandiford28940af2014-04-16 08:47:51 +00004974/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4975/// TheCall is a constant expression in the range [Low, High].
4976bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4977 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004978 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004979
4980 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004981 Expr *Arg = TheCall->getArg(ArgNum);
4982 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004983 return false;
4984
Eric Christopher8d0c6212010-04-17 02:26:23 +00004985 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004986 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004987 return true;
4988
Richard Sandiford28940af2014-04-16 08:47:51 +00004989 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004990 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004991 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004992
4993 return false;
4994}
4995
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004996/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4997/// TheCall is a constant expression is a multiple of Num..
4998bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4999 unsigned Num) {
5000 llvm::APSInt Result;
5001
5002 // We can't check the value of a dependent argument.
5003 Expr *Arg = TheCall->getArg(ArgNum);
5004 if (Arg->isTypeDependent() || Arg->isValueDependent())
5005 return false;
5006
5007 // Check constant-ness first.
5008 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5009 return true;
5010
5011 if (Result.getSExtValue() % Num != 0)
5012 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
5013 << Num << Arg->getSourceRange();
5014
5015 return false;
5016}
5017
Luke Cheeseman59b2d832015-06-15 17:51:01 +00005018/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
5019/// TheCall is an ARM/AArch64 special register string literal.
5020bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
5021 int ArgNum, unsigned ExpectedFieldNum,
5022 bool AllowName) {
5023 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
5024 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
5025 BuiltinID == ARM::BI__builtin_arm_rsr ||
5026 BuiltinID == ARM::BI__builtin_arm_rsrp ||
5027 BuiltinID == ARM::BI__builtin_arm_wsr ||
5028 BuiltinID == ARM::BI__builtin_arm_wsrp;
5029 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
5030 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
5031 BuiltinID == AArch64::BI__builtin_arm_rsr ||
5032 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
5033 BuiltinID == AArch64::BI__builtin_arm_wsr ||
5034 BuiltinID == AArch64::BI__builtin_arm_wsrp;
5035 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
5036
5037 // We can't check the value of a dependent argument.
5038 Expr *Arg = TheCall->getArg(ArgNum);
5039 if (Arg->isTypeDependent() || Arg->isValueDependent())
5040 return false;
5041
5042 // Check if the argument is a string literal.
5043 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
5044 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
5045 << Arg->getSourceRange();
5046
5047 // Check the type of special register given.
5048 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
5049 SmallVector<StringRef, 6> Fields;
5050 Reg.split(Fields, ":");
5051
5052 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
5053 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
5054 << Arg->getSourceRange();
5055
5056 // If the string is the name of a register then we cannot check that it is
5057 // valid here but if the string is of one the forms described in ACLE then we
5058 // can check that the supplied fields are integers and within the valid
5059 // ranges.
5060 if (Fields.size() > 1) {
5061 bool FiveFields = Fields.size() == 5;
5062
5063 bool ValidString = true;
5064 if (IsARMBuiltin) {
5065 ValidString &= Fields[0].startswith_lower("cp") ||
5066 Fields[0].startswith_lower("p");
5067 if (ValidString)
5068 Fields[0] =
5069 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
5070
5071 ValidString &= Fields[2].startswith_lower("c");
5072 if (ValidString)
5073 Fields[2] = Fields[2].drop_front(1);
5074
5075 if (FiveFields) {
5076 ValidString &= Fields[3].startswith_lower("c");
5077 if (ValidString)
5078 Fields[3] = Fields[3].drop_front(1);
5079 }
5080 }
5081
5082 SmallVector<int, 5> Ranges;
5083 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00005084 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00005085 else
5086 Ranges.append({15, 7, 15});
5087
5088 for (unsigned i=0; i<Fields.size(); ++i) {
5089 int IntField;
5090 ValidString &= !Fields[i].getAsInteger(10, IntField);
5091 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
5092 }
5093
5094 if (!ValidString)
5095 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
5096 << Arg->getSourceRange();
Luke Cheeseman59b2d832015-06-15 17:51:01 +00005097 } else if (IsAArch64Builtin && Fields.size() == 1) {
5098 // If the register name is one of those that appear in the condition below
5099 // and the special register builtin being used is one of the write builtins,
5100 // then we require that the argument provided for writing to the register
5101 // is an integer constant expression. This is because it will be lowered to
5102 // an MSR (immediate) instruction, so we need to know the immediate at
5103 // compile time.
5104 if (TheCall->getNumArgs() != 2)
5105 return false;
5106
5107 std::string RegLower = Reg.lower();
5108 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
5109 RegLower != "pan" && RegLower != "uao")
5110 return false;
5111
5112 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
5113 }
5114
5115 return false;
5116}
5117
Eli Friedmanc97d0142009-05-03 06:04:26 +00005118/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00005119/// This checks that the target supports __builtin_longjmp and
5120/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00005121bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00005122 if (!Context.getTargetInfo().hasSjLjLowering())
5123 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
5124 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
5125
Eli Friedmaneed8ad22009-05-03 04:46:36 +00005126 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00005127 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00005128
Eric Christopher8d0c6212010-04-17 02:26:23 +00005129 // TODO: This is less than ideal. Overload this to take a value.
5130 if (SemaBuiltinConstantArg(TheCall, 1, Result))
5131 return true;
5132
5133 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00005134 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
5135 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
5136
5137 return false;
5138}
5139
Joerg Sonnenberger27173282015-03-11 23:46:32 +00005140/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
5141/// This checks that the target supports __builtin_setjmp.
5142bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
5143 if (!Context.getTargetInfo().hasSjLjLowering())
5144 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
5145 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
5146 return false;
5147}
5148
Richard Smithd7293d72013-08-05 18:49:43 +00005149namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005150
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005151class UncoveredArgHandler {
5152 enum { Unknown = -1, AllCovered = -2 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005153
5154 signed FirstUncoveredArg = Unknown;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005155 SmallVector<const Expr *, 4> DiagnosticExprs;
5156
5157public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005158 UncoveredArgHandler() = default;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005159
5160 bool hasUncoveredArg() const {
5161 return (FirstUncoveredArg >= 0);
5162 }
5163
5164 unsigned getUncoveredArg() const {
5165 assert(hasUncoveredArg() && "no uncovered argument");
5166 return FirstUncoveredArg;
5167 }
5168
5169 void setAllCovered() {
5170 // A string has been found with all arguments covered, so clear out
5171 // the diagnostics.
5172 DiagnosticExprs.clear();
5173 FirstUncoveredArg = AllCovered;
5174 }
5175
5176 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
5177 assert(NewFirstUncoveredArg >= 0 && "Outside range");
5178
5179 // Don't update if a previous string covers all arguments.
5180 if (FirstUncoveredArg == AllCovered)
5181 return;
5182
5183 // UncoveredArgHandler tracks the highest uncovered argument index
5184 // and with it all the strings that match this index.
5185 if (NewFirstUncoveredArg == FirstUncoveredArg)
5186 DiagnosticExprs.push_back(StrExpr);
5187 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
5188 DiagnosticExprs.clear();
5189 DiagnosticExprs.push_back(StrExpr);
5190 FirstUncoveredArg = NewFirstUncoveredArg;
5191 }
5192 }
5193
5194 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
5195};
5196
Richard Smithd7293d72013-08-05 18:49:43 +00005197enum StringLiteralCheckType {
5198 SLCT_NotALiteral,
5199 SLCT_UncheckedLiteral,
5200 SLCT_CheckedLiteral
5201};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005202
5203} // namespace
Richard Smithd7293d72013-08-05 18:49:43 +00005204
Stephen Hines648c3692016-09-16 01:07:04 +00005205static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
5206 BinaryOperatorKind BinOpKind,
5207 bool AddendIsRight) {
5208 unsigned BitWidth = Offset.getBitWidth();
5209 unsigned AddendBitWidth = Addend.getBitWidth();
5210 // There might be negative interim results.
5211 if (Addend.isUnsigned()) {
5212 Addend = Addend.zext(++AddendBitWidth);
5213 Addend.setIsSigned(true);
5214 }
5215 // Adjust the bit width of the APSInts.
5216 if (AddendBitWidth > BitWidth) {
5217 Offset = Offset.sext(AddendBitWidth);
5218 BitWidth = AddendBitWidth;
5219 } else if (BitWidth > AddendBitWidth) {
5220 Addend = Addend.sext(BitWidth);
5221 }
5222
5223 bool Ov = false;
5224 llvm::APSInt ResOffset = Offset;
5225 if (BinOpKind == BO_Add)
5226 ResOffset = Offset.sadd_ov(Addend, Ov);
5227 else {
5228 assert(AddendIsRight && BinOpKind == BO_Sub &&
5229 "operator must be add or sub with addend on the right");
5230 ResOffset = Offset.ssub_ov(Addend, Ov);
5231 }
5232
5233 // We add an offset to a pointer here so we should support an offset as big as
5234 // possible.
5235 if (Ov) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005236 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
5237 "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00005238 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00005239 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
5240 return;
5241 }
5242
5243 Offset = ResOffset;
5244}
5245
5246namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005247
Stephen Hines648c3692016-09-16 01:07:04 +00005248// This is a wrapper class around StringLiteral to support offsetted string
5249// literals as format strings. It takes the offset into account when returning
5250// the string and its length or the source locations to display notes correctly.
5251class FormatStringLiteral {
5252 const StringLiteral *FExpr;
5253 int64_t Offset;
5254
5255 public:
5256 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
5257 : FExpr(fexpr), Offset(Offset) {}
5258
5259 StringRef getString() const {
5260 return FExpr->getString().drop_front(Offset);
5261 }
5262
5263 unsigned getByteLength() const {
5264 return FExpr->getByteLength() - getCharByteWidth() * Offset;
5265 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005266
Stephen Hines648c3692016-09-16 01:07:04 +00005267 unsigned getLength() const { return FExpr->getLength() - Offset; }
5268 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
5269
5270 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
5271
5272 QualType getType() const { return FExpr->getType(); }
5273
5274 bool isAscii() const { return FExpr->isAscii(); }
5275 bool isWide() const { return FExpr->isWide(); }
5276 bool isUTF8() const { return FExpr->isUTF8(); }
5277 bool isUTF16() const { return FExpr->isUTF16(); }
5278 bool isUTF32() const { return FExpr->isUTF32(); }
5279 bool isPascal() const { return FExpr->isPascal(); }
5280
5281 SourceLocation getLocationOfByte(
5282 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
5283 const TargetInfo &Target, unsigned *StartToken = nullptr,
5284 unsigned *StartTokenByteOffset = nullptr) const {
5285 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
5286 StartToken, StartTokenByteOffset);
5287 }
5288
5289 SourceLocation getLocStart() const LLVM_READONLY {
5290 return FExpr->getLocStart().getLocWithOffset(Offset);
5291 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005292
Stephen Hines648c3692016-09-16 01:07:04 +00005293 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
5294};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005295
5296} // namespace
Stephen Hines648c3692016-09-16 01:07:04 +00005297
5298static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005299 const Expr *OrigFormatExpr,
5300 ArrayRef<const Expr *> Args,
5301 bool HasVAListArg, unsigned format_idx,
5302 unsigned firstDataArg,
5303 Sema::FormatStringType Type,
5304 bool inFunctionCall,
5305 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005306 llvm::SmallBitVector &CheckedVarArgs,
5307 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005308
Richard Smith55ce3522012-06-25 20:30:08 +00005309// Determine if an expression is a string literal or constant string.
5310// If this function returns false on the arguments to a function expecting a
5311// format string, we will usually need to emit a warning.
5312// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00005313static StringLiteralCheckType
5314checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
5315 bool HasVAListArg, unsigned format_idx,
5316 unsigned firstDataArg, Sema::FormatStringType Type,
5317 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005318 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005319 UncoveredArgHandler &UncoveredArg,
5320 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00005321 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00005322 assert(Offset.isSigned() && "invalid offset");
5323
Douglas Gregorc25f7662009-05-19 22:10:17 +00005324 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00005325 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005326
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005327 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00005328
Richard Smithd7293d72013-08-05 18:49:43 +00005329 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00005330 // Technically -Wformat-nonliteral does not warn about this case.
5331 // The behavior of printf and friends in this case is implementation
5332 // dependent. Ideally if the format string cannot be null then
5333 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00005334 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00005335
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005336 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00005337 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005338 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00005339 // The expression is a literal if both sub-expressions were, and it was
5340 // completely checked only if both sub-expressions were checked.
5341 const AbstractConditionalOperator *C =
5342 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005343
5344 // Determine whether it is necessary to check both sub-expressions, for
5345 // example, because the condition expression is a constant that can be
5346 // evaluated at compile time.
5347 bool CheckLeft = true, CheckRight = true;
5348
5349 bool Cond;
5350 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
5351 if (Cond)
5352 CheckRight = false;
5353 else
5354 CheckLeft = false;
5355 }
5356
Stephen Hines648c3692016-09-16 01:07:04 +00005357 // We need to maintain the offsets for the right and the left hand side
5358 // separately to check if every possible indexed expression is a valid
5359 // string literal. They might have different offsets for different string
5360 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005361 StringLiteralCheckType Left;
5362 if (!CheckLeft)
5363 Left = SLCT_UncheckedLiteral;
5364 else {
5365 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
5366 HasVAListArg, format_idx, firstDataArg,
5367 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00005368 CheckedVarArgs, UncoveredArg, Offset);
5369 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005370 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00005371 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005372 }
5373
Richard Smith55ce3522012-06-25 20:30:08 +00005374 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00005375 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005376 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005377 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005378 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005379
5380 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005381 }
5382
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005383 case Stmt::ImplicitCastExprClass:
Ted Kremenek808829352010-09-09 03:51:39 +00005384 E = cast<ImplicitCastExpr>(E)->getSubExpr();
5385 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005386
John McCallc07a0c72011-02-17 10:25:35 +00005387 case Stmt::OpaqueValueExprClass:
5388 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
5389 E = src;
5390 goto tryAgain;
5391 }
Richard Smith55ce3522012-06-25 20:30:08 +00005392 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00005393
Ted Kremeneka8890832011-02-24 23:03:04 +00005394 case Stmt::PredefinedExprClass:
5395 // While __func__, etc., are technically not string literals, they
5396 // cannot contain format specifiers and thus are not a security
5397 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00005398 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00005399
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005400 case Stmt::DeclRefExprClass: {
5401 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005402
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005403 // As an exception, do not flag errors for variables binding to
5404 // const string literals.
5405 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
5406 bool isConstant = false;
5407 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005408
Richard Smithd7293d72013-08-05 18:49:43 +00005409 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
5410 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00005411 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00005412 isConstant = T.isConstant(S.Context) &&
5413 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00005414 } else if (T->isObjCObjectPointerType()) {
5415 // In ObjC, there is usually no "const ObjectPointer" type,
5416 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00005417 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005418 }
Mike Stump11289f42009-09-09 15:08:12 +00005419
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005420 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00005421 if (const Expr *Init = VD->getAnyInitializer()) {
5422 // Look through initializers like const char c[] = { "foo" }
5423 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
5424 if (InitList->isStringLiteralInit())
5425 Init = InitList->getInit(0)->IgnoreParenImpCasts();
5426 }
Richard Smithd7293d72013-08-05 18:49:43 +00005427 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005428 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005429 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005430 /*InFunctionCall*/ false, CheckedVarArgs,
5431 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00005432 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005433 }
Mike Stump11289f42009-09-09 15:08:12 +00005434
Anders Carlssonb012ca92009-06-28 19:55:58 +00005435 // For vprintf* functions (i.e., HasVAListArg==true), we add a
5436 // special check to see if the format string is a function parameter
5437 // of the function calling the printf function. If the function
5438 // has an attribute indicating it is a printf-like function, then we
5439 // should suppress warnings concerning non-literals being used in a call
5440 // to a vprintf function. For example:
5441 //
5442 // void
5443 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
5444 // va_list ap;
5445 // va_start(ap, fmt);
5446 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
5447 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00005448 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005449 if (HasVAListArg) {
5450 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
5451 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
5452 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00005453 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005454 // adjust for implicit parameter
5455 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5456 if (MD->isInstance())
5457 ++PVIndex;
5458 // We also check if the formats are compatible.
5459 // We can't pass a 'scanf' string to a 'printf' function.
5460 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00005461 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00005462 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005463 }
5464 }
5465 }
5466 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005467 }
Mike Stump11289f42009-09-09 15:08:12 +00005468
Richard Smith55ce3522012-06-25 20:30:08 +00005469 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005470 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005471
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005472 case Stmt::CallExprClass:
5473 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005474 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005475 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
5476 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00005477 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
Richard Smithd7293d72013-08-05 18:49:43 +00005478 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005479 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00005480 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00005481 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005482 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5483 unsigned BuiltinID = FD->getBuiltinID();
5484 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5485 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5486 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00005487 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005488 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005489 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005490 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005491 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005492 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005493 }
5494 }
Mike Stump11289f42009-09-09 15:08:12 +00005495
Richard Smith55ce3522012-06-25 20:30:08 +00005496 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005497 }
Alex Lorenzd9007142016-10-24 09:42:34 +00005498 case Stmt::ObjCMessageExprClass: {
5499 const auto *ME = cast<ObjCMessageExpr>(E);
5500 if (const auto *ND = ME->getMethodDecl()) {
5501 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00005502 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
Alex Lorenzd9007142016-10-24 09:42:34 +00005503 return checkFormatStringExpr(
5504 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5505 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5506 }
5507 }
5508
5509 return SLCT_NotALiteral;
5510 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005511 case Stmt::ObjCStringLiteralClass:
5512 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00005513 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005514
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005515 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005516 StrE = ObjCFExpr->getString();
5517 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005518 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005519
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005520 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005521 if (Offset.isNegative() || Offset > StrE->getLength()) {
5522 // TODO: It would be better to have an explicit warning for out of
5523 // bounds literals.
5524 return SLCT_NotALiteral;
5525 }
5526 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5527 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005528 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005529 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00005530 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005531 }
Mike Stump11289f42009-09-09 15:08:12 +00005532
Richard Smith55ce3522012-06-25 20:30:08 +00005533 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005534 }
Stephen Hines648c3692016-09-16 01:07:04 +00005535 case Stmt::BinaryOperatorClass: {
5536 llvm::APSInt LResult;
5537 llvm::APSInt RResult;
5538
5539 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5540
5541 // A string literal + an int offset is still a string literal.
5542 if (BinOp->isAdditiveOp()) {
5543 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5544 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5545
5546 if (LIsInt != RIsInt) {
5547 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5548
5549 if (LIsInt) {
5550 if (BinOpKind == BO_Add) {
5551 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5552 E = BinOp->getRHS();
5553 goto tryAgain;
5554 }
5555 } else {
5556 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5557 E = BinOp->getLHS();
5558 goto tryAgain;
5559 }
5560 }
Stephen Hines648c3692016-09-16 01:07:04 +00005561 }
George Burgess IVd273aab2016-09-22 00:00:26 +00005562
5563 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00005564 }
5565 case Stmt::UnaryOperatorClass: {
5566 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5567 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005568 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005569 llvm::APSInt IndexResult;
5570 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5571 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5572 E = ASE->getBase();
5573 goto tryAgain;
5574 }
5575 }
5576
5577 return SLCT_NotALiteral;
5578 }
Mike Stump11289f42009-09-09 15:08:12 +00005579
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005580 default:
Richard Smith55ce3522012-06-25 20:30:08 +00005581 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005582 }
5583}
5584
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005585Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00005586 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00005587 .Case("scanf", FST_Scanf)
5588 .Cases("printf", "printf0", FST_Printf)
5589 .Cases("NSString", "CFString", FST_NSString)
5590 .Case("strftime", FST_Strftime)
5591 .Case("strfmon", FST_Strfmon)
5592 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5593 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5594 .Case("os_trace", FST_OSLog)
5595 .Case("os_log", FST_OSLog)
5596 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005597}
5598
Jordan Rose3e0ec582012-07-19 18:10:23 +00005599/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00005600/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00005601/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005602bool Sema::CheckFormatArguments(const FormatAttr *Format,
5603 ArrayRef<const Expr *> Args,
5604 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005605 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005606 SourceLocation Loc, SourceRange Range,
5607 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00005608 FormatStringInfo FSI;
5609 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005610 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00005611 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00005612 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00005613 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005614}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00005615
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005616bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005617 bool HasVAListArg, unsigned format_idx,
5618 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005619 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005620 SourceLocation Loc, SourceRange Range,
5621 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00005622 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005623 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005624 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00005625 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005626 }
Mike Stump11289f42009-09-09 15:08:12 +00005627
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005628 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005629
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005630 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00005631 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005632 // Dynamically generated format strings are difficult to
5633 // automatically vet at compile time. Requiring that format strings
5634 // are string literals: (1) permits the checking of format strings by
5635 // the compiler and thereby (2) can practically remove the source of
5636 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00005637
Mike Stump11289f42009-09-09 15:08:12 +00005638 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00005639 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00005640 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00005641 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005642 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00005643 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00005644 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5645 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005646 /*IsFunctionCall*/ true, CheckedVarArgs,
5647 UncoveredArg,
5648 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005649
5650 // Generate a diagnostic where an uncovered argument is detected.
5651 if (UncoveredArg.hasUncoveredArg()) {
5652 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5653 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5654 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5655 }
5656
Richard Smith55ce3522012-06-25 20:30:08 +00005657 if (CT != SLCT_NotALiteral)
5658 // Literal format string found, check done!
5659 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00005660
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005661 // Strftime is particular as it always uses a single 'time' argument,
5662 // so it is safe to pass a non-literal string.
5663 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00005664 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005665
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005666 // Do not emit diag when the string param is a macro expansion and the
5667 // format is either NSString or CFString. This is a hack to prevent
5668 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5669 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005670 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5671 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00005672 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005673
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005674 // If there are no arguments specified, warn with -Wformat-security, otherwise
5675 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005676 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00005677 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5678 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005679 switch (Type) {
5680 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005681 break;
5682 case FST_Kprintf:
5683 case FST_FreeBSDKPrintf:
5684 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00005685 Diag(FormatLoc, diag::note_format_security_fixit)
5686 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005687 break;
5688 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00005689 Diag(FormatLoc, diag::note_format_security_fixit)
5690 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005691 break;
5692 }
5693 } else {
5694 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005695 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005696 }
Richard Smith55ce3522012-06-25 20:30:08 +00005697 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005698}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005699
Ted Kremenekab278de2010-01-28 23:39:18 +00005700namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005701
Ted Kremenek02087932010-07-16 02:11:22 +00005702class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5703protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00005704 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00005705 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00005706 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005707 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00005708 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00005709 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00005710 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00005711 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005712 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00005713 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00005714 llvm::SmallBitVector CoveredArgs;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005715 bool usesPositionalArgs = false;
5716 bool atFirstArg = true;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005717 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00005718 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00005719 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005720 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005721
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005722public:
Stephen Hines648c3692016-09-16 01:07:04 +00005723 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005724 const Expr *origFormatExpr,
5725 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005726 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005727 ArrayRef<const Expr *> Args, unsigned formatIdx,
5728 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005729 llvm::SmallBitVector &CheckedVarArgs,
5730 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005731 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5732 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5733 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
Mehdi Amini06d367c2016-10-24 20:39:34 +00005734 inFunctionCall(inFunctionCall), CallType(callType),
5735 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00005736 CoveredArgs.resize(numDataArgs);
5737 CoveredArgs.reset();
5738 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005739
Ted Kremenek019d2242010-01-29 01:50:07 +00005740 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005741
Ted Kremenek02087932010-07-16 02:11:22 +00005742 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005743 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005744
Jordan Rose92303592012-09-08 04:00:03 +00005745 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005746 const analyze_format_string::FormatSpecifier &FS,
5747 const analyze_format_string::ConversionSpecifier &CS,
5748 const char *startSpecifier, unsigned specifierLen,
5749 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00005750
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005751 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005752 const analyze_format_string::FormatSpecifier &FS,
5753 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005754
5755 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005756 const analyze_format_string::ConversionSpecifier &CS,
5757 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005758
Craig Toppere14c0f82014-03-12 04:55:44 +00005759 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005760
Craig Toppere14c0f82014-03-12 04:55:44 +00005761 void HandleInvalidPosition(const char *startSpecifier,
5762 unsigned specifierLen,
5763 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005764
Craig Toppere14c0f82014-03-12 04:55:44 +00005765 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005766
Craig Toppere14c0f82014-03-12 04:55:44 +00005767 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005768
Richard Trieu03cf7b72011-10-28 00:41:25 +00005769 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00005770 static void
5771 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5772 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5773 bool IsStringLocation, Range StringRange,
5774 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005775
Ted Kremenek02087932010-07-16 02:11:22 +00005776protected:
Ted Kremenekce815422010-07-19 21:25:57 +00005777 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5778 const char *startSpec,
5779 unsigned specifierLen,
5780 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005781
5782 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5783 const char *startSpec,
5784 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00005785
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005786 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00005787 CharSourceRange getSpecifierRange(const char *startSpecifier,
5788 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00005789 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005790
Ted Kremenek5739de72010-01-29 01:06:55 +00005791 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005792
5793 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5794 const analyze_format_string::ConversionSpecifier &CS,
5795 const char *startSpecifier, unsigned specifierLen,
5796 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005797
5798 template <typename Range>
5799 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5800 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005801 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00005802};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005803
5804} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005805
Ted Kremenek02087932010-07-16 02:11:22 +00005806SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00005807 return OrigFormatExpr->getSourceRange();
5808}
5809
Ted Kremenek02087932010-07-16 02:11:22 +00005810CharSourceRange CheckFormatHandler::
5811getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00005812 SourceLocation Start = getLocationOfByte(startSpecifier);
5813 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5814
5815 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00005816 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00005817
5818 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005819}
5820
Ted Kremenek02087932010-07-16 02:11:22 +00005821SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00005822 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5823 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00005824}
5825
Ted Kremenek02087932010-07-16 02:11:22 +00005826void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5827 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00005828 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5829 getLocationOfByte(startSpecifier),
5830 /*IsStringLocation*/true,
5831 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00005832}
5833
Jordan Rose92303592012-09-08 04:00:03 +00005834void CheckFormatHandler::HandleInvalidLengthModifier(
5835 const analyze_format_string::FormatSpecifier &FS,
5836 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00005837 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00005838 using namespace analyze_format_string;
5839
5840 const LengthModifier &LM = FS.getLengthModifier();
5841 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5842
5843 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005844 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00005845 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005846 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005847 getLocationOfByte(LM.getStart()),
5848 /*IsStringLocation*/true,
5849 getSpecifierRange(startSpecifier, specifierLen));
5850
5851 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5852 << FixedLM->toString()
5853 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5854
5855 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005856 FixItHint Hint;
5857 if (DiagID == diag::warn_format_nonsensical_length)
5858 Hint = FixItHint::CreateRemoval(LMRange);
5859
5860 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005861 getLocationOfByte(LM.getStart()),
5862 /*IsStringLocation*/true,
5863 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00005864 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00005865 }
5866}
5867
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005868void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005869 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005870 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005871 using namespace analyze_format_string;
5872
5873 const LengthModifier &LM = FS.getLengthModifier();
5874 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5875
5876 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005877 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005878 if (FixedLM) {
5879 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5880 << LM.toString() << 0,
5881 getLocationOfByte(LM.getStart()),
5882 /*IsStringLocation*/true,
5883 getSpecifierRange(startSpecifier, specifierLen));
5884
5885 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5886 << FixedLM->toString()
5887 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5888
5889 } else {
5890 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5891 << LM.toString() << 0,
5892 getLocationOfByte(LM.getStart()),
5893 /*IsStringLocation*/true,
5894 getSpecifierRange(startSpecifier, specifierLen));
5895 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005896}
5897
5898void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5899 const analyze_format_string::ConversionSpecifier &CS,
5900 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005901 using namespace analyze_format_string;
5902
5903 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005904 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005905 if (FixedCS) {
5906 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5907 << CS.toString() << /*conversion specifier*/1,
5908 getLocationOfByte(CS.getStart()),
5909 /*IsStringLocation*/true,
5910 getSpecifierRange(startSpecifier, specifierLen));
5911
5912 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5913 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5914 << FixedCS->toString()
5915 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5916 } else {
5917 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5918 << CS.toString() << /*conversion specifier*/1,
5919 getLocationOfByte(CS.getStart()),
5920 /*IsStringLocation*/true,
5921 getSpecifierRange(startSpecifier, specifierLen));
5922 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005923}
5924
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005925void CheckFormatHandler::HandlePosition(const char *startPos,
5926 unsigned posLen) {
5927 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5928 getLocationOfByte(startPos),
5929 /*IsStringLocation*/true,
5930 getSpecifierRange(startPos, posLen));
5931}
5932
Ted Kremenekd1668192010-02-27 01:41:03 +00005933void
Ted Kremenek02087932010-07-16 02:11:22 +00005934CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5935 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005936 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5937 << (unsigned) p,
5938 getLocationOfByte(startPos), /*IsStringLocation*/true,
5939 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005940}
5941
Ted Kremenek02087932010-07-16 02:11:22 +00005942void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005943 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005944 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5945 getLocationOfByte(startPos),
5946 /*IsStringLocation*/true,
5947 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005948}
5949
Ted Kremenek02087932010-07-16 02:11:22 +00005950void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005951 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005952 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005953 EmitFormatDiagnostic(
5954 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5955 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5956 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005957 }
Ted Kremenek02087932010-07-16 02:11:22 +00005958}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005959
Jordan Rose58bbe422012-07-19 18:10:08 +00005960// Note that this may return NULL if there was an error parsing or building
5961// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005962const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005963 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005964}
5965
5966void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005967 // Does the number of data arguments exceed the number of
5968 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005969 if (!HasVAListArg) {
5970 // Find any arguments that weren't covered.
5971 CoveredArgs.flip();
5972 signed notCoveredArg = CoveredArgs.find_first();
5973 if (notCoveredArg >= 0) {
5974 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005975 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5976 } else {
5977 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005978 }
5979 }
5980}
5981
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005982void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5983 const Expr *ArgExpr) {
5984 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5985 "Invalid state");
5986
5987 if (!ArgExpr)
5988 return;
5989
5990 SourceLocation Loc = ArgExpr->getLocStart();
5991
5992 if (S.getSourceManager().isInSystemMacro(Loc))
5993 return;
5994
5995 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5996 for (auto E : DiagnosticExprs)
5997 PDiag << E->getSourceRange();
5998
5999 CheckFormatHandler::EmitFormatDiagnostic(
6000 S, IsFunctionCall, DiagnosticExprs[0],
6001 PDiag, Loc, /*IsStringLocation*/false,
6002 DiagnosticExprs[0]->getSourceRange());
6003}
6004
Ted Kremenekce815422010-07-19 21:25:57 +00006005bool
6006CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
6007 SourceLocation Loc,
6008 const char *startSpec,
6009 unsigned specifierLen,
6010 const char *csStart,
6011 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00006012 bool keepGoing = true;
6013 if (argIndex < NumDataArgs) {
6014 // Consider the argument coverered, even though the specifier doesn't
6015 // make sense.
6016 CoveredArgs.set(argIndex);
6017 }
6018 else {
6019 // If argIndex exceeds the number of data arguments we
6020 // don't issue a warning because that is just a cascade of warnings (and
6021 // they may have intended '%%' anyway). We don't want to continue processing
6022 // the format string after this point, however, as we will like just get
6023 // gibberish when trying to match arguments.
6024 keepGoing = false;
6025 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00006026
6027 StringRef Specifier(csStart, csLen);
6028
6029 // If the specifier in non-printable, it could be the first byte of a UTF-8
6030 // sequence. In that case, print the UTF-8 code point. If not, print the byte
6031 // hex value.
6032 std::string CodePointStr;
6033 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00006034 llvm::UTF32 CodePoint;
6035 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
6036 const llvm::UTF8 *E =
6037 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
6038 llvm::ConversionResult Result =
6039 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00006040
Justin Lebar90910552016-09-30 00:38:45 +00006041 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00006042 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00006043 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00006044 }
6045
6046 llvm::raw_string_ostream OS(CodePointStr);
6047 if (CodePoint < 256)
6048 OS << "\\x" << llvm::format("%02x", CodePoint);
6049 else if (CodePoint <= 0xFFFF)
6050 OS << "\\u" << llvm::format("%04x", CodePoint);
6051 else
6052 OS << "\\U" << llvm::format("%08x", CodePoint);
6053 OS.flush();
6054 Specifier = CodePointStr;
6055 }
6056
6057 EmitFormatDiagnostic(
6058 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
6059 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
6060
Ted Kremenekce815422010-07-19 21:25:57 +00006061 return keepGoing;
6062}
6063
Richard Trieu03cf7b72011-10-28 00:41:25 +00006064void
6065CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
6066 const char *startSpec,
6067 unsigned specifierLen) {
6068 EmitFormatDiagnostic(
6069 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
6070 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
6071}
6072
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006073bool
6074CheckFormatHandler::CheckNumArgs(
6075 const analyze_format_string::FormatSpecifier &FS,
6076 const analyze_format_string::ConversionSpecifier &CS,
6077 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
6078
6079 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006080 PartialDiagnostic PDiag = FS.usesPositionalArg()
6081 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
6082 << (argIndex+1) << NumDataArgs)
6083 : S.PDiag(diag::warn_printf_insufficient_data_args);
6084 EmitFormatDiagnostic(
6085 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
6086 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006087
6088 // Since more arguments than conversion tokens are given, by extension
6089 // all arguments are covered, so mark this as so.
6090 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006091 return false;
6092 }
6093 return true;
6094}
6095
Richard Trieu03cf7b72011-10-28 00:41:25 +00006096template<typename Range>
6097void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
6098 SourceLocation Loc,
6099 bool IsStringLocation,
6100 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00006101 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00006102 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00006103 Loc, IsStringLocation, StringRange, FixIt);
6104}
6105
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006106/// If the format string is not within the function call, emit a note
Richard Trieu03cf7b72011-10-28 00:41:25 +00006107/// so that the function call and string are in diagnostic messages.
6108///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00006109/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00006110/// call and only one diagnostic message will be produced. Otherwise, an
6111/// extra note will be emitted pointing to location of the format string.
6112///
6113/// \param ArgumentExpr the expression that is passed as the format string
6114/// argument in the function call. Used for getting locations when two
6115/// diagnostics are emitted.
6116///
6117/// \param PDiag the callee should already have provided any strings for the
6118/// diagnostic message. This function only adds locations and fixits
6119/// to diagnostics.
6120///
6121/// \param Loc primary location for diagnostic. If two diagnostics are
6122/// required, one will be at Loc and a new SourceLocation will be created for
6123/// the other one.
6124///
6125/// \param IsStringLocation if true, Loc points to the format string should be
6126/// used for the note. Otherwise, Loc points to the argument list and will
6127/// be used with PDiag.
6128///
6129/// \param StringRange some or all of the string to highlight. This is
6130/// templated so it can accept either a CharSourceRange or a SourceRange.
6131///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00006132/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00006133template <typename Range>
6134void CheckFormatHandler::EmitFormatDiagnostic(
6135 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
6136 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
6137 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00006138 if (InFunctionCall) {
6139 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
6140 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00006141 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00006142 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006143 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
6144 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00006145
6146 const Sema::SemaDiagnosticBuilder &Note =
6147 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
6148 diag::note_format_string_defined);
6149
6150 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00006151 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00006152 }
6153}
6154
Ted Kremenek02087932010-07-16 02:11:22 +00006155//===--- CHECK: Printf format string checking ------------------------------===//
6156
6157namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006158
Ted Kremenek02087932010-07-16 02:11:22 +00006159class CheckPrintfHandler : public CheckFormatHandler {
6160public:
Stephen Hines648c3692016-09-16 01:07:04 +00006161 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006162 const Expr *origFormatExpr,
6163 const Sema::FormatStringType type, unsigned firstDataArg,
6164 unsigned numDataArgs, bool isObjC, const char *beg,
6165 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006166 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00006167 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006168 llvm::SmallBitVector &CheckedVarArgs,
6169 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006170 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6171 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6172 inFunctionCall, CallType, CheckedVarArgs,
6173 UncoveredArg) {}
6174
6175 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
6176
6177 /// Returns true if '%@' specifiers are allowed in the format string.
6178 bool allowsObjCArg() const {
6179 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
6180 FSType == Sema::FST_OSTrace;
6181 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00006182
Ted Kremenek02087932010-07-16 02:11:22 +00006183 bool HandleInvalidPrintfConversionSpecifier(
6184 const analyze_printf::PrintfSpecifier &FS,
6185 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006186 unsigned specifierLen) override;
6187
Ted Kremenek02087932010-07-16 02:11:22 +00006188 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
6189 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006190 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00006191 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6192 const char *StartSpecifier,
6193 unsigned SpecifierLen,
6194 const Expr *E);
6195
Ted Kremenek02087932010-07-16 02:11:22 +00006196 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
6197 const char *startSpecifier, unsigned specifierLen);
6198 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
6199 const analyze_printf::OptionalAmount &Amt,
6200 unsigned type,
6201 const char *startSpecifier, unsigned specifierLen);
6202 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
6203 const analyze_printf::OptionalFlag &flag,
6204 const char *startSpecifier, unsigned specifierLen);
6205 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
6206 const analyze_printf::OptionalFlag &ignoredFlag,
6207 const analyze_printf::OptionalFlag &flag,
6208 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006209 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00006210 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00006211
6212 void HandleEmptyObjCModifierFlag(const char *startFlag,
6213 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00006214
Ted Kremenek2b417712015-07-02 05:39:16 +00006215 void HandleInvalidObjCModifierFlag(const char *startFlag,
6216 unsigned flagLen) override;
6217
6218 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
6219 const char *flagsEnd,
6220 const char *conversionPosition)
6221 override;
6222};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006223
6224} // namespace
Ted Kremenek02087932010-07-16 02:11:22 +00006225
6226bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
6227 const analyze_printf::PrintfSpecifier &FS,
6228 const char *startSpecifier,
6229 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006230 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006231 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006232
Ted Kremenekce815422010-07-19 21:25:57 +00006233 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6234 getLocationOfByte(CS.getStart()),
6235 startSpecifier, specifierLen,
6236 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00006237}
6238
Ted Kremenek02087932010-07-16 02:11:22 +00006239bool CheckPrintfHandler::HandleAmount(
6240 const analyze_format_string::OptionalAmount &Amt,
6241 unsigned k, const char *startSpecifier,
6242 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006243 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006244 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00006245 unsigned argIndex = Amt.getArgIndex();
6246 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006247 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
6248 << k,
6249 getLocationOfByte(Amt.getStart()),
6250 /*IsStringLocation*/true,
6251 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00006252 // Don't do any more checking. We will just emit
6253 // spurious errors.
6254 return false;
6255 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006256
Ted Kremenek5739de72010-01-29 01:06:55 +00006257 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00006258 // Although not in conformance with C99, we also allow the argument to be
6259 // an 'unsigned int' as that is a reasonably safe case. GCC also
6260 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00006261 CoveredArgs.set(argIndex);
6262 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006263 if (!Arg)
6264 return false;
6265
Ted Kremenek5739de72010-01-29 01:06:55 +00006266 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006267
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006268 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
6269 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006270
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006271 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006272 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006273 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00006274 << T << Arg->getSourceRange(),
6275 getLocationOfByte(Amt.getStart()),
6276 /*IsStringLocation*/true,
6277 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00006278 // Don't do any more checking. We will just emit
6279 // spurious errors.
6280 return false;
6281 }
6282 }
6283 }
6284 return true;
6285}
Ted Kremenek5739de72010-01-29 01:06:55 +00006286
Tom Careb49ec692010-06-17 19:00:27 +00006287void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00006288 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006289 const analyze_printf::OptionalAmount &Amt,
6290 unsigned type,
6291 const char *startSpecifier,
6292 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006293 const analyze_printf::PrintfConversionSpecifier &CS =
6294 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00006295
Richard Trieu03cf7b72011-10-28 00:41:25 +00006296 FixItHint fixit =
6297 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
6298 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
6299 Amt.getConstantLength()))
6300 : FixItHint();
6301
6302 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
6303 << type << CS.toString(),
6304 getLocationOfByte(Amt.getStart()),
6305 /*IsStringLocation*/true,
6306 getSpecifierRange(startSpecifier, specifierLen),
6307 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00006308}
6309
Ted Kremenek02087932010-07-16 02:11:22 +00006310void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006311 const analyze_printf::OptionalFlag &flag,
6312 const char *startSpecifier,
6313 unsigned specifierLen) {
6314 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006315 const analyze_printf::PrintfConversionSpecifier &CS =
6316 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00006317 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
6318 << flag.toString() << CS.toString(),
6319 getLocationOfByte(flag.getPosition()),
6320 /*IsStringLocation*/true,
6321 getSpecifierRange(startSpecifier, specifierLen),
6322 FixItHint::CreateRemoval(
6323 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00006324}
6325
6326void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00006327 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006328 const analyze_printf::OptionalFlag &ignoredFlag,
6329 const analyze_printf::OptionalFlag &flag,
6330 const char *startSpecifier,
6331 unsigned specifierLen) {
6332 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00006333 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
6334 << ignoredFlag.toString() << flag.toString(),
6335 getLocationOfByte(ignoredFlag.getPosition()),
6336 /*IsStringLocation*/true,
6337 getSpecifierRange(startSpecifier, specifierLen),
6338 FixItHint::CreateRemoval(
6339 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00006340}
6341
Ted Kremenek2b417712015-07-02 05:39:16 +00006342void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
6343 unsigned flagLen) {
6344 // Warn about an empty flag.
6345 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
6346 getLocationOfByte(startFlag),
6347 /*IsStringLocation*/true,
6348 getSpecifierRange(startFlag, flagLen));
6349}
6350
6351void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
6352 unsigned flagLen) {
6353 // Warn about an invalid flag.
6354 auto Range = getSpecifierRange(startFlag, flagLen);
6355 StringRef flag(startFlag, flagLen);
6356 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
6357 getLocationOfByte(startFlag),
6358 /*IsStringLocation*/true,
6359 Range, FixItHint::CreateRemoval(Range));
6360}
6361
6362void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
6363 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
6364 // Warn about using '[...]' without a '@' conversion.
6365 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
6366 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
6367 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
6368 getLocationOfByte(conversionPosition),
6369 /*IsStringLocation*/true,
6370 Range, FixItHint::CreateRemoval(Range));
6371}
6372
Richard Smith55ce3522012-06-25 20:30:08 +00006373// Determines if the specified is a C++ class or struct containing
6374// a member with the specified name and kind (e.g. a CXXMethodDecl named
6375// "c_str()").
6376template<typename MemberKind>
6377static llvm::SmallPtrSet<MemberKind*, 1>
6378CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
6379 const RecordType *RT = Ty->getAs<RecordType>();
6380 llvm::SmallPtrSet<MemberKind*, 1> Results;
6381
6382 if (!RT)
6383 return Results;
6384 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00006385 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00006386 return Results;
6387
Alp Tokerb6cc5922014-05-03 03:45:55 +00006388 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00006389 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00006390 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00006391
6392 // We just need to include all members of the right kind turned up by the
6393 // filter, at this point.
6394 if (S.LookupQualifiedName(R, RT->getDecl()))
6395 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6396 NamedDecl *decl = (*I)->getUnderlyingDecl();
6397 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
6398 Results.insert(FK);
6399 }
6400 return Results;
6401}
6402
Richard Smith2868a732014-02-28 01:36:39 +00006403/// Check if we could call '.c_str()' on an object.
6404///
6405/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
6406/// allow the call, or if it would be ambiguous).
6407bool Sema::hasCStrMethod(const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006408 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
6409
Richard Smith2868a732014-02-28 01:36:39 +00006410 MethodSet Results =
6411 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
6412 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6413 MI != ME; ++MI)
6414 if ((*MI)->getMinRequiredArguments() == 0)
6415 return true;
6416 return false;
6417}
6418
Richard Smith55ce3522012-06-25 20:30:08 +00006419// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006420// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00006421// Returns true when a c_str() conversion method is found.
6422bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00006423 const analyze_printf::ArgType &AT, const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006424 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
Richard Smith55ce3522012-06-25 20:30:08 +00006425
6426 MethodSet Results =
6427 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
6428
6429 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6430 MI != ME; ++MI) {
6431 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00006432 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00006433 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00006434 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00006435 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00006436 S.Diag(E->getLocStart(), diag::note_printf_c_str)
6437 << "c_str()"
6438 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
6439 return true;
6440 }
6441 }
6442
6443 return false;
6444}
6445
Ted Kremenekab278de2010-01-28 23:39:18 +00006446bool
Ted Kremenek02087932010-07-16 02:11:22 +00006447CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00006448 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00006449 const char *startSpecifier,
6450 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006451 using namespace analyze_format_string;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006452 using namespace analyze_printf;
6453
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006454 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00006455
Ted Kremenek6cd69422010-07-19 22:01:06 +00006456 if (FS.consumesDataArgument()) {
6457 if (atFirstArg) {
6458 atFirstArg = false;
6459 usesPositionalArgs = FS.usesPositionalArg();
6460 }
6461 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006462 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6463 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006464 return false;
6465 }
Ted Kremenek5739de72010-01-29 01:06:55 +00006466 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006467
Ted Kremenekd1668192010-02-27 01:41:03 +00006468 // First check if the field width, precision, and conversion specifier
6469 // have matching data arguments.
6470 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
6471 startSpecifier, specifierLen)) {
6472 return false;
6473 }
6474
6475 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
6476 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006477 return false;
6478 }
6479
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006480 if (!CS.consumesDataArgument()) {
6481 // FIXME: Technically specifying a precision or field width here
6482 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00006483 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006484 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006485
Ted Kremenek4a49d982010-02-26 19:18:41 +00006486 // Consume the argument.
6487 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00006488 if (argIndex < NumDataArgs) {
6489 // The check to see if the argIndex is valid will come later.
6490 // We set the bit here because we may exit early from this
6491 // function if we encounter some other error.
6492 CoveredArgs.set(argIndex);
6493 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00006494
Dimitry Andric6b5ed342015-02-19 22:32:33 +00006495 // FreeBSD kernel extensions.
6496 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6497 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6498 // We need at least two arguments.
6499 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6500 return false;
6501
6502 // Claim the second argument.
6503 CoveredArgs.set(argIndex + 1);
6504
6505 // Type check the first argument (int for %b, pointer for %D)
6506 const Expr *Ex = getDataArg(argIndex);
6507 const analyze_printf::ArgType &AT =
6508 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6509 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6510 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6511 EmitFormatDiagnostic(
6512 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6513 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6514 << false << Ex->getSourceRange(),
6515 Ex->getLocStart(), /*IsStringLocation*/false,
6516 getSpecifierRange(startSpecifier, specifierLen));
6517
6518 // Type check the second argument (char * for both %b and %D)
6519 Ex = getDataArg(argIndex + 1);
6520 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6521 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6522 EmitFormatDiagnostic(
6523 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6524 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6525 << false << Ex->getSourceRange(),
6526 Ex->getLocStart(), /*IsStringLocation*/false,
6527 getSpecifierRange(startSpecifier, specifierLen));
6528
6529 return true;
6530 }
6531
Ted Kremenek4a49d982010-02-26 19:18:41 +00006532 // Check for using an Objective-C specific conversion specifier
6533 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006534 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00006535 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6536 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00006537 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006538
Mehdi Amini06d367c2016-10-24 20:39:34 +00006539 // %P can only be used with os_log.
6540 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6541 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6542 specifierLen);
6543 }
6544
6545 // %n is not allowed with os_log.
6546 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6547 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6548 getLocationOfByte(CS.getStart()),
6549 /*IsStringLocation*/ false,
6550 getSpecifierRange(startSpecifier, specifierLen));
6551
6552 return true;
6553 }
6554
6555 // Only scalars are allowed for os_trace.
6556 if (FSType == Sema::FST_OSTrace &&
6557 (CS.getKind() == ConversionSpecifier::PArg ||
6558 CS.getKind() == ConversionSpecifier::sArg ||
6559 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6560 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6561 specifierLen);
6562 }
6563
6564 // Check for use of public/private annotation outside of os_log().
6565 if (FSType != Sema::FST_OSLog) {
6566 if (FS.isPublic().isSet()) {
6567 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6568 << "public",
6569 getLocationOfByte(FS.isPublic().getPosition()),
6570 /*IsStringLocation*/ false,
6571 getSpecifierRange(startSpecifier, specifierLen));
6572 }
6573 if (FS.isPrivate().isSet()) {
6574 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6575 << "private",
6576 getLocationOfByte(FS.isPrivate().getPosition()),
6577 /*IsStringLocation*/ false,
6578 getSpecifierRange(startSpecifier, specifierLen));
6579 }
6580 }
6581
Tom Careb49ec692010-06-17 19:00:27 +00006582 // Check for invalid use of field width
6583 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00006584 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00006585 startSpecifier, specifierLen);
6586 }
6587
6588 // Check for invalid use of precision
6589 if (!FS.hasValidPrecision()) {
6590 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6591 startSpecifier, specifierLen);
6592 }
6593
Mehdi Amini06d367c2016-10-24 20:39:34 +00006594 // Precision is mandatory for %P specifier.
6595 if (CS.getKind() == ConversionSpecifier::PArg &&
6596 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6597 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6598 getLocationOfByte(startSpecifier),
6599 /*IsStringLocation*/ false,
6600 getSpecifierRange(startSpecifier, specifierLen));
6601 }
6602
Tom Careb49ec692010-06-17 19:00:27 +00006603 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00006604 if (!FS.hasValidThousandsGroupingPrefix())
6605 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006606 if (!FS.hasValidLeadingZeros())
6607 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6608 if (!FS.hasValidPlusPrefix())
6609 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00006610 if (!FS.hasValidSpacePrefix())
6611 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006612 if (!FS.hasValidAlternativeForm())
6613 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6614 if (!FS.hasValidLeftJustified())
6615 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6616
6617 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00006618 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6619 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6620 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006621 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6622 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6623 startSpecifier, specifierLen);
6624
6625 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006626 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006627 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6628 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006629 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006630 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006631 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006632 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6633 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00006634
Jordan Rose92303592012-09-08 04:00:03 +00006635 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6636 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6637
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006638 // The remaining checks depend on the data arguments.
6639 if (HasVAListArg)
6640 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006641
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006642 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006643 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006644
Jordan Rose58bbe422012-07-19 18:10:08 +00006645 const Expr *Arg = getDataArg(argIndex);
6646 if (!Arg)
6647 return true;
6648
6649 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00006650}
6651
Jordan Roseaee34382012-09-05 22:56:26 +00006652static bool requiresParensToAddCast(const Expr *E) {
6653 // FIXME: We should have a general way to reason about operator
6654 // precedence and whether parens are actually needed here.
6655 // Take care of a few common cases where they aren't.
6656 const Expr *Inside = E->IgnoreImpCasts();
6657 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6658 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6659
6660 switch (Inside->getStmtClass()) {
6661 case Stmt::ArraySubscriptExprClass:
6662 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006663 case Stmt::CharacterLiteralClass:
6664 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006665 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006666 case Stmt::FloatingLiteralClass:
6667 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006668 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006669 case Stmt::ObjCArrayLiteralClass:
6670 case Stmt::ObjCBoolLiteralExprClass:
6671 case Stmt::ObjCBoxedExprClass:
6672 case Stmt::ObjCDictionaryLiteralClass:
6673 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006674 case Stmt::ObjCIvarRefExprClass:
6675 case Stmt::ObjCMessageExprClass:
6676 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006677 case Stmt::ObjCStringLiteralClass:
6678 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006679 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006680 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006681 case Stmt::UnaryOperatorClass:
6682 return false;
6683 default:
6684 return true;
6685 }
6686}
6687
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006688static std::pair<QualType, StringRef>
6689shouldNotPrintDirectly(const ASTContext &Context,
6690 QualType IntendedTy,
6691 const Expr *E) {
6692 // Use a 'while' to peel off layers of typedefs.
6693 QualType TyTy = IntendedTy;
6694 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6695 StringRef Name = UserTy->getDecl()->getName();
6696 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Saleem Abdulrasoola01ed932017-10-17 17:39:32 +00006697 .Case("CFIndex", Context.getNSIntegerType())
6698 .Case("NSInteger", Context.getNSIntegerType())
6699 .Case("NSUInteger", Context.getNSUIntegerType())
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006700 .Case("SInt32", Context.IntTy)
6701 .Case("UInt32", Context.UnsignedIntTy)
6702 .Default(QualType());
6703
6704 if (!CastTy.isNull())
6705 return std::make_pair(CastTy, Name);
6706
6707 TyTy = UserTy->desugar();
6708 }
6709
6710 // Strip parens if necessary.
6711 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6712 return shouldNotPrintDirectly(Context,
6713 PE->getSubExpr()->getType(),
6714 PE->getSubExpr());
6715
6716 // If this is a conditional expression, then its result type is constructed
6717 // via usual arithmetic conversions and thus there might be no necessary
6718 // typedef sugar there. Recurse to operands to check for NSInteger &
6719 // Co. usage condition.
6720 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6721 QualType TrueTy, FalseTy;
6722 StringRef TrueName, FalseName;
6723
6724 std::tie(TrueTy, TrueName) =
6725 shouldNotPrintDirectly(Context,
6726 CO->getTrueExpr()->getType(),
6727 CO->getTrueExpr());
6728 std::tie(FalseTy, FalseName) =
6729 shouldNotPrintDirectly(Context,
6730 CO->getFalseExpr()->getType(),
6731 CO->getFalseExpr());
6732
6733 if (TrueTy == FalseTy)
6734 return std::make_pair(TrueTy, TrueName);
6735 else if (TrueTy.isNull())
6736 return std::make_pair(FalseTy, FalseName);
6737 else if (FalseTy.isNull())
6738 return std::make_pair(TrueTy, TrueName);
6739 }
6740
6741 return std::make_pair(QualType(), StringRef());
6742}
6743
Richard Smith55ce3522012-06-25 20:30:08 +00006744bool
6745CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6746 const char *StartSpecifier,
6747 unsigned SpecifierLen,
6748 const Expr *E) {
6749 using namespace analyze_format_string;
6750 using namespace analyze_printf;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006751
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006752 // Now type check the data expression that matches the
6753 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006754 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00006755 if (!AT.isValid())
6756 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00006757
Jordan Rose598ec092012-12-05 18:44:40 +00006758 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00006759 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6760 ExprTy = TET->getUnderlyingExpr()->getType();
6761 }
6762
Seth Cantrellb4802962015-03-04 03:12:10 +00006763 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6764
6765 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00006766 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006767 }
Jordan Rose98709982012-06-04 22:48:57 +00006768
Jordan Rose22b74712012-09-05 22:56:19 +00006769 // Look through argument promotions for our error message's reported type.
6770 // This includes the integral and floating promotions, but excludes array
6771 // and function pointer decay; seeing that an argument intended to be a
6772 // string has type 'char [6]' is probably more confusing than 'char *'.
6773 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6774 if (ICE->getCastKind() == CK_IntegralCast ||
6775 ICE->getCastKind() == CK_FloatingCast) {
6776 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006777 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006778
6779 // Check if we didn't match because of an implicit cast from a 'char'
6780 // or 'short' to an 'int'. This is done because printf is a varargs
6781 // function.
6782 if (ICE->getType() == S.Context.IntTy ||
6783 ICE->getType() == S.Context.UnsignedIntTy) {
6784 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006785 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006786 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006787 }
Jordan Rose98709982012-06-04 22:48:57 +00006788 }
Jordan Rose598ec092012-12-05 18:44:40 +00006789 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6790 // Special case for 'a', which has type 'int' in C.
6791 // Note, however, that we do /not/ want to treat multibyte constants like
6792 // 'MooV' as characters! This form is deprecated but still exists.
6793 if (ExprTy == S.Context.IntTy)
6794 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6795 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006796 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006797
Jordan Rosebc53ed12014-05-31 04:12:14 +00006798 // Look through enums to their underlying type.
6799 bool IsEnum = false;
6800 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6801 ExprTy = EnumTy->getDecl()->getIntegerType();
6802 IsEnum = true;
6803 }
6804
Jordan Rose0e5badd2012-12-05 18:44:49 +00006805 // %C in an Objective-C context prints a unichar, not a wchar_t.
6806 // If the argument is an integer of some kind, believe the %C and suggest
6807 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006808 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006809 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006810 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6811 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6812 !ExprTy->isCharType()) {
6813 // 'unichar' is defined as a typedef of unsigned short, but we should
6814 // prefer using the typedef if it is visible.
6815 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006816
6817 // While we are here, check if the value is an IntegerLiteral that happens
6818 // to be within the valid range.
6819 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6820 const llvm::APInt &V = IL->getValue();
6821 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6822 return true;
6823 }
6824
Jordan Rose0e5badd2012-12-05 18:44:49 +00006825 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6826 Sema::LookupOrdinaryName);
6827 if (S.LookupName(Result, S.getCurScope())) {
6828 NamedDecl *ND = Result.getFoundDecl();
6829 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6830 if (TD->getUnderlyingType() == IntendedTy)
6831 IntendedTy = S.Context.getTypedefType(TD);
6832 }
6833 }
6834 }
6835
6836 // Special-case some of Darwin's platform-independence types by suggesting
6837 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006838 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006839 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006840 QualType CastTy;
6841 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6842 if (!CastTy.isNull()) {
6843 IntendedTy = CastTy;
6844 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006845 }
6846 }
6847
Jordan Rose22b74712012-09-05 22:56:19 +00006848 // We may be able to offer a FixItHint if it is a supported type.
6849 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006850 bool success =
6851 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006852
Jordan Rose22b74712012-09-05 22:56:19 +00006853 if (success) {
6854 // Get the fix string from the fixed format specifier
6855 SmallString<16> buf;
6856 llvm::raw_svector_ostream os(buf);
6857 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006858
Jordan Roseaee34382012-09-05 22:56:26 +00006859 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6860
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006861 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00006862 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6863 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6864 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6865 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00006866 // In this case, the specifier is wrong and should be changed to match
6867 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006868 EmitFormatDiagnostic(S.PDiag(diag)
6869 << AT.getRepresentativeTypeName(S.Context)
6870 << IntendedTy << IsEnum << E->getSourceRange(),
6871 E->getLocStart(),
6872 /*IsStringLocation*/ false, SpecRange,
6873 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006874 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006875 // The canonical type for formatting this value is different from the
6876 // actual type of the expression. (This occurs, for example, with Darwin's
6877 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6878 // should be printed as 'long' for 64-bit compatibility.)
6879 // Rather than emitting a normal format/argument mismatch, we want to
6880 // add a cast to the recommended type (and correct the format string
6881 // if necessary).
6882 SmallString<16> CastBuf;
6883 llvm::raw_svector_ostream CastFix(CastBuf);
6884 CastFix << "(";
6885 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6886 CastFix << ")";
6887
6888 SmallVector<FixItHint,4> Hints;
Alexander Shaposhnikov1788a9b2017-09-22 18:36:06 +00006889 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
Jordan Roseaee34382012-09-05 22:56:26 +00006890 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6891
6892 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6893 // If there's already a cast present, just replace it.
6894 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6895 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6896
6897 } else if (!requiresParensToAddCast(E)) {
6898 // If the expression has high enough precedence,
6899 // just write the C-style cast.
6900 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6901 CastFix.str()));
6902 } else {
6903 // Otherwise, add parens around the expression as well as the cast.
6904 CastFix << "(";
6905 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6906 CastFix.str()));
6907
Alp Tokerb6cc5922014-05-03 03:45:55 +00006908 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006909 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6910 }
6911
Jordan Rose0e5badd2012-12-05 18:44:49 +00006912 if (ShouldNotPrintDirectly) {
6913 // The expression has a type that should not be printed directly.
6914 // We extract the name from the typedef because we don't want to show
6915 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006916 StringRef Name;
6917 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6918 Name = TypedefTy->getDecl()->getName();
6919 else
6920 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006921 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006922 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006923 << E->getSourceRange(),
6924 E->getLocStart(), /*IsStringLocation=*/false,
6925 SpecRange, Hints);
6926 } else {
6927 // In this case, the expression could be printed using a different
6928 // specifier, but we've decided that the specifier is probably correct
6929 // and we should cast instead. Just use the normal warning message.
6930 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006931 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6932 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006933 << E->getSourceRange(),
6934 E->getLocStart(), /*IsStringLocation*/false,
6935 SpecRange, Hints);
6936 }
Jordan Roseaee34382012-09-05 22:56:26 +00006937 }
Jordan Rose22b74712012-09-05 22:56:19 +00006938 } else {
6939 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6940 SpecifierLen);
6941 // Since the warning for passing non-POD types to variadic functions
6942 // was deferred until now, we emit a warning for non-POD
6943 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006944 switch (S.isValidVarArgType(ExprTy)) {
6945 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006946 case Sema::VAK_ValidInCXX11: {
6947 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6948 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6949 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6950 }
Richard Smithd7293d72013-08-05 18:49:43 +00006951
Seth Cantrellb4802962015-03-04 03:12:10 +00006952 EmitFormatDiagnostic(
6953 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6954 << IsEnum << CSR << E->getSourceRange(),
6955 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6956 break;
6957 }
Richard Smithd7293d72013-08-05 18:49:43 +00006958 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006959 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006960 EmitFormatDiagnostic(
6961 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006962 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006963 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006964 << CallType
6965 << AT.getRepresentativeTypeName(S.Context)
6966 << CSR
6967 << E->getSourceRange(),
6968 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006969 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006970 break;
6971
6972 case Sema::VAK_Invalid:
6973 if (ExprTy->isObjCObjectType())
6974 EmitFormatDiagnostic(
6975 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6976 << S.getLangOpts().CPlusPlus11
6977 << ExprTy
6978 << CallType
6979 << AT.getRepresentativeTypeName(S.Context)
6980 << CSR
6981 << E->getSourceRange(),
6982 E->getLocStart(), /*IsStringLocation*/false, CSR);
6983 else
6984 // FIXME: If this is an initializer list, suggest removing the braces
6985 // or inserting a cast to the target type.
6986 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6987 << isa<InitListExpr>(E) << ExprTy << CallType
6988 << AT.getRepresentativeTypeName(S.Context)
6989 << E->getSourceRange();
6990 break;
6991 }
6992
6993 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6994 "format string specifier index out of range");
6995 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006996 }
6997
Ted Kremenekab278de2010-01-28 23:39:18 +00006998 return true;
6999}
7000
Ted Kremenek02087932010-07-16 02:11:22 +00007001//===--- CHECK: Scanf format string checking ------------------------------===//
7002
7003namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007004
Ted Kremenek02087932010-07-16 02:11:22 +00007005class CheckScanfHandler : public CheckFormatHandler {
7006public:
Stephen Hines648c3692016-09-16 01:07:04 +00007007 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00007008 const Expr *origFormatExpr, Sema::FormatStringType type,
7009 unsigned firstDataArg, unsigned numDataArgs,
7010 const char *beg, bool hasVAListArg,
7011 ArrayRef<const Expr *> Args, unsigned formatIdx,
7012 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007013 llvm::SmallBitVector &CheckedVarArgs,
7014 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00007015 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7016 numDataArgs, beg, hasVAListArg, Args, formatIdx,
7017 inFunctionCall, CallType, CheckedVarArgs,
7018 UncoveredArg) {}
7019
Ted Kremenek02087932010-07-16 02:11:22 +00007020 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
7021 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007022 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00007023
7024 bool HandleInvalidScanfConversionSpecifier(
7025 const analyze_scanf::ScanfSpecifier &FS,
7026 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007027 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00007028
Craig Toppere14c0f82014-03-12 04:55:44 +00007029 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00007030};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007031
7032} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00007033
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00007034void CheckScanfHandler::HandleIncompleteScanList(const char *start,
7035 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007036 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
7037 getLocationOfByte(end), /*IsStringLocation*/true,
7038 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00007039}
7040
Ted Kremenekce815422010-07-19 21:25:57 +00007041bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
7042 const analyze_scanf::ScanfSpecifier &FS,
7043 const char *startSpecifier,
7044 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007045 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00007046 FS.getConversionSpecifier();
7047
7048 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7049 getLocationOfByte(CS.getStart()),
7050 startSpecifier, specifierLen,
7051 CS.getStart(), CS.getLength());
7052}
7053
Ted Kremenek02087932010-07-16 02:11:22 +00007054bool CheckScanfHandler::HandleScanfSpecifier(
7055 const analyze_scanf::ScanfSpecifier &FS,
7056 const char *startSpecifier,
7057 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00007058 using namespace analyze_scanf;
7059 using namespace analyze_format_string;
7060
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007061 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00007062
Ted Kremenek6cd69422010-07-19 22:01:06 +00007063 // Handle case where '%' and '*' don't consume an argument. These shouldn't
7064 // be used to decide if we are using positional arguments consistently.
7065 if (FS.consumesDataArgument()) {
7066 if (atFirstArg) {
7067 atFirstArg = false;
7068 usesPositionalArgs = FS.usesPositionalArg();
7069 }
7070 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007071 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7072 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00007073 return false;
7074 }
Ted Kremenek02087932010-07-16 02:11:22 +00007075 }
7076
7077 // Check if the field with is non-zero.
7078 const OptionalAmount &Amt = FS.getFieldWidth();
7079 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
7080 if (Amt.getConstantAmount() == 0) {
7081 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
7082 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00007083 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
7084 getLocationOfByte(Amt.getStart()),
7085 /*IsStringLocation*/true, R,
7086 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00007087 }
7088 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007089
Ted Kremenek02087932010-07-16 02:11:22 +00007090 if (!FS.consumesDataArgument()) {
7091 // FIXME: Technically specifying a precision or field width here
7092 // makes no sense. Worth issuing a warning at some point.
7093 return true;
7094 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007095
Ted Kremenek02087932010-07-16 02:11:22 +00007096 // Consume the argument.
7097 unsigned argIndex = FS.getArgIndex();
7098 if (argIndex < NumDataArgs) {
7099 // The check to see if the argIndex is valid will come later.
7100 // We set the bit here because we may exit early from this
7101 // function if we encounter some other error.
7102 CoveredArgs.set(argIndex);
7103 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007104
Ted Kremenek4407ea42010-07-20 20:04:47 +00007105 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00007106 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00007107 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7108 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00007109 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00007110 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00007111 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00007112 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7113 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007114
Jordan Rose92303592012-09-08 04:00:03 +00007115 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7116 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7117
Ted Kremenek02087932010-07-16 02:11:22 +00007118 // The remaining checks depend on the data arguments.
7119 if (HasVAListArg)
7120 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00007121
Ted Kremenek6adb7e32010-07-26 19:45:42 +00007122 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00007123 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00007124
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007125 // Check that the argument type matches the format specifier.
7126 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00007127 if (!Ex)
7128 return true;
7129
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00007130 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00007131
7132 if (!AT.isValid()) {
7133 return true;
7134 }
7135
Seth Cantrellb4802962015-03-04 03:12:10 +00007136 analyze_format_string::ArgType::MatchKind match =
7137 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00007138 if (match == analyze_format_string::ArgType::Match) {
7139 return true;
7140 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007141
Seth Cantrell79340072015-03-04 05:58:08 +00007142 ScanfSpecifier fixedFS = FS;
7143 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
7144 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007145
Seth Cantrell79340072015-03-04 05:58:08 +00007146 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
7147 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
7148 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
7149 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007150
Seth Cantrell79340072015-03-04 05:58:08 +00007151 if (success) {
7152 // Get the fix string from the fixed format specifier.
7153 SmallString<128> buf;
7154 llvm::raw_svector_ostream os(buf);
7155 fixedFS.toString(os);
7156
7157 EmitFormatDiagnostic(
7158 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
7159 << Ex->getType() << false << Ex->getSourceRange(),
7160 Ex->getLocStart(),
7161 /*IsStringLocation*/ false,
7162 getSpecifierRange(startSpecifier, specifierLen),
7163 FixItHint::CreateReplacement(
7164 getSpecifierRange(startSpecifier, specifierLen), os.str()));
7165 } else {
7166 EmitFormatDiagnostic(S.PDiag(diag)
7167 << AT.getRepresentativeTypeName(S.Context)
7168 << Ex->getType() << false << Ex->getSourceRange(),
7169 Ex->getLocStart(),
7170 /*IsStringLocation*/ false,
7171 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007172 }
7173
Ted Kremenek02087932010-07-16 02:11:22 +00007174 return true;
7175}
7176
Stephen Hines648c3692016-09-16 01:07:04 +00007177static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007178 const Expr *OrigFormatExpr,
7179 ArrayRef<const Expr *> Args,
7180 bool HasVAListArg, unsigned format_idx,
7181 unsigned firstDataArg,
7182 Sema::FormatStringType Type,
7183 bool inFunctionCall,
7184 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007185 llvm::SmallBitVector &CheckedVarArgs,
7186 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00007187 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00007188 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007189 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007190 S, inFunctionCall, Args[format_idx],
7191 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00007192 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00007193 return;
7194 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007195
Ted Kremenekab278de2010-01-28 23:39:18 +00007196 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007197 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00007198 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007199 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007200 const ConstantArrayType *T =
7201 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007202 assert(T && "String literal not of constant array type!");
7203 size_t TypeSize = T->getSize().getZExtValue();
7204 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00007205 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007206
7207 // Emit a warning if the string literal is truncated and does not contain an
7208 // embedded null character.
7209 if (TypeSize <= StrRef.size() &&
7210 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
7211 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007212 S, inFunctionCall, Args[format_idx],
7213 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007214 FExpr->getLocStart(),
7215 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
7216 return;
7217 }
7218
Ted Kremenekab278de2010-01-28 23:39:18 +00007219 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00007220 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007221 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007222 S, inFunctionCall, Args[format_idx],
7223 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00007224 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00007225 return;
7226 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007227
7228 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00007229 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
7230 Type == Sema::FST_OSTrace) {
7231 CheckPrintfHandler H(
7232 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
7233 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
7234 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
7235 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007236
Hans Wennborg23926bd2011-12-15 10:25:47 +00007237 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007238 S.getLangOpts(),
7239 S.Context.getTargetInfo(),
7240 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00007241 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007242 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00007243 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
7244 numDataArgs, Str, HasVAListArg, Args, format_idx,
7245 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007246
Hans Wennborg23926bd2011-12-15 10:25:47 +00007247 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007248 S.getLangOpts(),
7249 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00007250 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00007251 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00007252}
7253
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00007254bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
7255 // Str - The format string. NOTE: this is NOT null-terminated!
7256 StringRef StrRef = FExpr->getString();
7257 const char *Str = StrRef.data();
7258 // Account for cases where the string literal is truncated in a declaration.
7259 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
7260 assert(T && "String literal not of constant array type!");
7261 size_t TypeSize = T->getSize().getZExtValue();
7262 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
7263 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
7264 getLangOpts(),
7265 Context.getTargetInfo());
7266}
7267
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007268//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
7269
7270// Returns the related absolute value function that is larger, of 0 if one
7271// does not exist.
7272static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
7273 switch (AbsFunction) {
7274 default:
7275 return 0;
7276
7277 case Builtin::BI__builtin_abs:
7278 return Builtin::BI__builtin_labs;
7279 case Builtin::BI__builtin_labs:
7280 return Builtin::BI__builtin_llabs;
7281 case Builtin::BI__builtin_llabs:
7282 return 0;
7283
7284 case Builtin::BI__builtin_fabsf:
7285 return Builtin::BI__builtin_fabs;
7286 case Builtin::BI__builtin_fabs:
7287 return Builtin::BI__builtin_fabsl;
7288 case Builtin::BI__builtin_fabsl:
7289 return 0;
7290
7291 case Builtin::BI__builtin_cabsf:
7292 return Builtin::BI__builtin_cabs;
7293 case Builtin::BI__builtin_cabs:
7294 return Builtin::BI__builtin_cabsl;
7295 case Builtin::BI__builtin_cabsl:
7296 return 0;
7297
7298 case Builtin::BIabs:
7299 return Builtin::BIlabs;
7300 case Builtin::BIlabs:
7301 return Builtin::BIllabs;
7302 case Builtin::BIllabs:
7303 return 0;
7304
7305 case Builtin::BIfabsf:
7306 return Builtin::BIfabs;
7307 case Builtin::BIfabs:
7308 return Builtin::BIfabsl;
7309 case Builtin::BIfabsl:
7310 return 0;
7311
7312 case Builtin::BIcabsf:
7313 return Builtin::BIcabs;
7314 case Builtin::BIcabs:
7315 return Builtin::BIcabsl;
7316 case Builtin::BIcabsl:
7317 return 0;
7318 }
7319}
7320
7321// Returns the argument type of the absolute value function.
7322static QualType getAbsoluteValueArgumentType(ASTContext &Context,
7323 unsigned AbsType) {
7324 if (AbsType == 0)
7325 return QualType();
7326
7327 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
7328 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
7329 if (Error != ASTContext::GE_None)
7330 return QualType();
7331
7332 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
7333 if (!FT)
7334 return QualType();
7335
7336 if (FT->getNumParams() != 1)
7337 return QualType();
7338
7339 return FT->getParamType(0);
7340}
7341
7342// Returns the best absolute value function, or zero, based on type and
7343// current absolute value function.
7344static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
7345 unsigned AbsFunctionKind) {
7346 unsigned BestKind = 0;
7347 uint64_t ArgSize = Context.getTypeSize(ArgType);
7348 for (unsigned Kind = AbsFunctionKind; Kind != 0;
7349 Kind = getLargerAbsoluteValueFunction(Kind)) {
7350 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
7351 if (Context.getTypeSize(ParamType) >= ArgSize) {
7352 if (BestKind == 0)
7353 BestKind = Kind;
7354 else if (Context.hasSameType(ParamType, ArgType)) {
7355 BestKind = Kind;
7356 break;
7357 }
7358 }
7359 }
7360 return BestKind;
7361}
7362
7363enum AbsoluteValueKind {
7364 AVK_Integer,
7365 AVK_Floating,
7366 AVK_Complex
7367};
7368
7369static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
7370 if (T->isIntegralOrEnumerationType())
7371 return AVK_Integer;
7372 if (T->isRealFloatingType())
7373 return AVK_Floating;
7374 if (T->isAnyComplexType())
7375 return AVK_Complex;
7376
7377 llvm_unreachable("Type not integer, floating, or complex");
7378}
7379
7380// Changes the absolute value function to a different type. Preserves whether
7381// the function is a builtin.
7382static unsigned changeAbsFunction(unsigned AbsKind,
7383 AbsoluteValueKind ValueKind) {
7384 switch (ValueKind) {
7385 case AVK_Integer:
7386 switch (AbsKind) {
7387 default:
7388 return 0;
7389 case Builtin::BI__builtin_fabsf:
7390 case Builtin::BI__builtin_fabs:
7391 case Builtin::BI__builtin_fabsl:
7392 case Builtin::BI__builtin_cabsf:
7393 case Builtin::BI__builtin_cabs:
7394 case Builtin::BI__builtin_cabsl:
7395 return Builtin::BI__builtin_abs;
7396 case Builtin::BIfabsf:
7397 case Builtin::BIfabs:
7398 case Builtin::BIfabsl:
7399 case Builtin::BIcabsf:
7400 case Builtin::BIcabs:
7401 case Builtin::BIcabsl:
7402 return Builtin::BIabs;
7403 }
7404 case AVK_Floating:
7405 switch (AbsKind) {
7406 default:
7407 return 0;
7408 case Builtin::BI__builtin_abs:
7409 case Builtin::BI__builtin_labs:
7410 case Builtin::BI__builtin_llabs:
7411 case Builtin::BI__builtin_cabsf:
7412 case Builtin::BI__builtin_cabs:
7413 case Builtin::BI__builtin_cabsl:
7414 return Builtin::BI__builtin_fabsf;
7415 case Builtin::BIabs:
7416 case Builtin::BIlabs:
7417 case Builtin::BIllabs:
7418 case Builtin::BIcabsf:
7419 case Builtin::BIcabs:
7420 case Builtin::BIcabsl:
7421 return Builtin::BIfabsf;
7422 }
7423 case AVK_Complex:
7424 switch (AbsKind) {
7425 default:
7426 return 0;
7427 case Builtin::BI__builtin_abs:
7428 case Builtin::BI__builtin_labs:
7429 case Builtin::BI__builtin_llabs:
7430 case Builtin::BI__builtin_fabsf:
7431 case Builtin::BI__builtin_fabs:
7432 case Builtin::BI__builtin_fabsl:
7433 return Builtin::BI__builtin_cabsf;
7434 case Builtin::BIabs:
7435 case Builtin::BIlabs:
7436 case Builtin::BIllabs:
7437 case Builtin::BIfabsf:
7438 case Builtin::BIfabs:
7439 case Builtin::BIfabsl:
7440 return Builtin::BIcabsf;
7441 }
7442 }
7443 llvm_unreachable("Unable to convert function");
7444}
7445
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00007446static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007447 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
7448 if (!FnInfo)
7449 return 0;
7450
7451 switch (FDecl->getBuiltinID()) {
7452 default:
7453 return 0;
7454 case Builtin::BI__builtin_abs:
7455 case Builtin::BI__builtin_fabs:
7456 case Builtin::BI__builtin_fabsf:
7457 case Builtin::BI__builtin_fabsl:
7458 case Builtin::BI__builtin_labs:
7459 case Builtin::BI__builtin_llabs:
7460 case Builtin::BI__builtin_cabs:
7461 case Builtin::BI__builtin_cabsf:
7462 case Builtin::BI__builtin_cabsl:
7463 case Builtin::BIabs:
7464 case Builtin::BIlabs:
7465 case Builtin::BIllabs:
7466 case Builtin::BIfabs:
7467 case Builtin::BIfabsf:
7468 case Builtin::BIfabsl:
7469 case Builtin::BIcabs:
7470 case Builtin::BIcabsf:
7471 case Builtin::BIcabsl:
7472 return FDecl->getBuiltinID();
7473 }
7474 llvm_unreachable("Unknown Builtin type");
7475}
7476
7477// If the replacement is valid, emit a note with replacement function.
7478// Additionally, suggest including the proper header if not already included.
7479static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00007480 unsigned AbsKind, QualType ArgType) {
7481 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007482 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00007483 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007484 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
7485 FunctionName = "std::abs";
7486 if (ArgType->isIntegralOrEnumerationType()) {
7487 HeaderName = "cstdlib";
7488 } else if (ArgType->isRealFloatingType()) {
7489 HeaderName = "cmath";
7490 } else {
7491 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007492 }
Richard Trieubeffb832014-04-15 23:47:53 +00007493
7494 // Lookup all std::abs
7495 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00007496 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00007497 R.suppressDiagnostics();
7498 S.LookupQualifiedName(R, Std);
7499
7500 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007501 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007502 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
7503 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
7504 } else {
7505 FDecl = dyn_cast<FunctionDecl>(I);
7506 }
7507 if (!FDecl)
7508 continue;
7509
7510 // Found std::abs(), check that they are the right ones.
7511 if (FDecl->getNumParams() != 1)
7512 continue;
7513
7514 // Check that the parameter type can handle the argument.
7515 QualType ParamType = FDecl->getParamDecl(0)->getType();
7516 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
7517 S.Context.getTypeSize(ArgType) <=
7518 S.Context.getTypeSize(ParamType)) {
7519 // Found a function, don't need the header hint.
7520 EmitHeaderHint = false;
7521 break;
7522 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007523 }
Richard Trieubeffb832014-04-15 23:47:53 +00007524 }
7525 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00007526 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00007527 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7528
7529 if (HeaderName) {
7530 DeclarationName DN(&S.Context.Idents.get(FunctionName));
7531 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7532 R.suppressDiagnostics();
7533 S.LookupName(R, S.getCurScope());
7534
7535 if (R.isSingleResult()) {
7536 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7537 if (FD && FD->getBuiltinID() == AbsKind) {
7538 EmitHeaderHint = false;
7539 } else {
7540 return;
7541 }
7542 } else if (!R.empty()) {
7543 return;
7544 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007545 }
7546 }
7547
7548 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00007549 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007550
Richard Trieubeffb832014-04-15 23:47:53 +00007551 if (!HeaderName)
7552 return;
7553
7554 if (!EmitHeaderHint)
7555 return;
7556
Alp Toker5d96e0a2014-07-11 20:53:51 +00007557 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7558 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00007559}
7560
Richard Trieua7f30b12016-12-06 01:42:28 +00007561template <std::size_t StrLen>
7562static bool IsStdFunction(const FunctionDecl *FDecl,
7563 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00007564 if (!FDecl)
7565 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007566 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00007567 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007568 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00007569 return false;
7570
7571 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007572}
7573
7574// Warn when using the wrong abs() function.
7575void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00007576 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007577 if (Call->getNumArgs() != 1)
7578 return;
7579
7580 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00007581 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00007582 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007583 return;
7584
7585 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7586 QualType ParamType = Call->getArg(0)->getType();
7587
Alp Toker5d96e0a2014-07-11 20:53:51 +00007588 // Unsigned types cannot be negative. Suggest removing the absolute value
7589 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007590 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00007591 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00007592 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007593 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7594 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00007595 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007596 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7597 return;
7598 }
7599
David Majnemer7f77eb92015-11-15 03:04:34 +00007600 // Taking the absolute value of a pointer is very suspicious, they probably
7601 // wanted to index into an array, dereference a pointer, call a function, etc.
7602 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7603 unsigned DiagType = 0;
7604 if (ArgType->isFunctionType())
7605 DiagType = 1;
7606 else if (ArgType->isArrayType())
7607 DiagType = 2;
7608
7609 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7610 return;
7611 }
7612
Richard Trieubeffb832014-04-15 23:47:53 +00007613 // std::abs has overloads which prevent most of the absolute value problems
7614 // from occurring.
7615 if (IsStdAbs)
7616 return;
7617
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007618 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7619 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7620
7621 // The argument and parameter are the same kind. Check if they are the right
7622 // size.
7623 if (ArgValueKind == ParamValueKind) {
7624 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7625 return;
7626
7627 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7628 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7629 << FDecl << ArgType << ParamType;
7630
7631 if (NewAbsKind == 0)
7632 return;
7633
7634 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007635 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007636 return;
7637 }
7638
7639 // ArgValueKind != ParamValueKind
7640 // The wrong type of absolute value function was used. Attempt to find the
7641 // proper one.
7642 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7643 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7644 if (NewAbsKind == 0)
7645 return;
7646
7647 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7648 << FDecl << ParamValueKind << ArgValueKind;
7649
7650 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007651 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007652}
7653
Richard Trieu67c00712016-12-05 23:41:46 +00007654//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00007655void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7656 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00007657 if (!Call || !FDecl) return;
7658
7659 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00007660 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007661 if (Call->getExprLoc().isMacroID()) return;
7662
7663 // Only care about the one template argument, two function parameter std::max
7664 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00007665 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007666 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7667 if (!ArgList) return;
7668 if (ArgList->size() != 1) return;
7669
7670 // Check that template type argument is unsigned integer.
7671 const auto& TA = ArgList->get(0);
7672 if (TA.getKind() != TemplateArgument::Type) return;
7673 QualType ArgType = TA.getAsType();
7674 if (!ArgType->isUnsignedIntegerType()) return;
7675
7676 // See if either argument is a literal zero.
7677 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7678 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7679 if (!MTE) return false;
7680 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7681 if (!Num) return false;
7682 if (Num->getValue() != 0) return false;
7683 return true;
7684 };
7685
7686 const Expr *FirstArg = Call->getArg(0);
7687 const Expr *SecondArg = Call->getArg(1);
7688 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7689 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7690
7691 // Only warn when exactly one argument is zero.
7692 if (IsFirstArgZero == IsSecondArgZero) return;
7693
7694 SourceRange FirstRange = FirstArg->getSourceRange();
7695 SourceRange SecondRange = SecondArg->getSourceRange();
7696
7697 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7698
7699 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7700 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7701
7702 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7703 SourceRange RemovalRange;
7704 if (IsFirstArgZero) {
7705 RemovalRange = SourceRange(FirstRange.getBegin(),
7706 SecondRange.getBegin().getLocWithOffset(-1));
7707 } else {
7708 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7709 SecondRange.getEnd());
7710 }
7711
7712 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7713 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7714 << FixItHint::CreateRemoval(RemovalRange);
7715}
7716
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007717//===--- CHECK: Standard memory functions ---------------------------------===//
7718
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007719/// Takes the expression passed to the size_t parameter of functions
Nico Weber0e6daef2013-12-26 23:38:39 +00007720/// such as memcmp, strncat, etc and warns if it's a comparison.
7721///
7722/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7723static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7724 IdentifierInfo *FnName,
7725 SourceLocation FnLoc,
7726 SourceLocation RParenLoc) {
7727 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7728 if (!Size)
7729 return false;
7730
Richard Smithc70f1d62017-12-14 15:16:18 +00007731 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
7732 if (!Size->isComparisonOp() && !Size->isLogicalOp())
Nico Weber0e6daef2013-12-26 23:38:39 +00007733 return false;
7734
Nico Weber0e6daef2013-12-26 23:38:39 +00007735 SourceRange SizeRange = Size->getSourceRange();
7736 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7737 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00007738 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007739 << FnName << FixItHint::CreateInsertion(
7740 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00007741 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00007742 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00007743 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00007744 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7745 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00007746
7747 return true;
7748}
7749
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007750/// Determine whether the given type is or contains a dynamic class type
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007751/// (e.g., whether it has a vtable).
7752static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7753 bool &IsContained) {
7754 // Look through array types while ignoring qualifiers.
7755 const Type *Ty = T->getBaseElementTypeUnsafe();
7756 IsContained = false;
7757
7758 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7759 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00007760 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007761 return nullptr;
7762
7763 if (RD->isDynamicClass())
7764 return RD;
7765
7766 // Check all the fields. If any bases were dynamic, the class is dynamic.
7767 // It's impossible for a class to transitively contain itself by value, so
7768 // infinite recursion is impossible.
7769 for (auto *FD : RD->fields()) {
7770 bool SubContained;
7771 if (const CXXRecordDecl *ContainedRD =
7772 getContainedDynamicClass(FD->getType(), SubContained)) {
7773 IsContained = true;
7774 return ContainedRD;
7775 }
7776 }
7777
7778 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007779}
7780
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007781/// If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007782/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007783static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007784 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007785 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007786 if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007787 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007788
Craig Topperc3ec1492014-05-26 06:22:03 +00007789 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007790}
7791
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007792/// If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007793static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007794 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7795 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007796 if (SizeOf->getKind() == UETT_SizeOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007797 return SizeOf->getTypeOfArgument();
7798
7799 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007800}
7801
Akira Hatanaka2be04412018-04-17 19:13:41 +00007802namespace {
7803
7804struct SearchNonTrivialToInitializeField
7805 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
7806 using Super =
7807 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
7808
7809 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
7810
7811 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
7812 SourceLocation SL) {
7813 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7814 asDerived().visitArray(PDIK, AT, SL);
7815 return;
7816 }
7817
7818 Super::visitWithKind(PDIK, FT, SL);
7819 }
7820
7821 void visitARCStrong(QualType FT, SourceLocation SL) {
7822 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7823 }
7824 void visitARCWeak(QualType FT, SourceLocation SL) {
7825 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7826 }
7827 void visitStruct(QualType FT, SourceLocation SL) {
7828 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7829 visit(FD->getType(), FD->getLocation());
7830 }
7831 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
7832 const ArrayType *AT, SourceLocation SL) {
7833 visit(getContext().getBaseElementType(AT), SL);
7834 }
7835 void visitTrivial(QualType FT, SourceLocation SL) {}
7836
7837 static void diag(QualType RT, const Expr *E, Sema &S) {
7838 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
7839 }
7840
7841 ASTContext &getContext() { return S.getASTContext(); }
7842
7843 const Expr *E;
7844 Sema &S;
7845};
7846
7847struct SearchNonTrivialToCopyField
7848 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
7849 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
7850
7851 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
7852
7853 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
7854 SourceLocation SL) {
7855 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7856 asDerived().visitArray(PCK, AT, SL);
7857 return;
7858 }
7859
7860 Super::visitWithKind(PCK, FT, SL);
7861 }
7862
7863 void visitARCStrong(QualType FT, SourceLocation SL) {
7864 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7865 }
7866 void visitARCWeak(QualType FT, SourceLocation SL) {
7867 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7868 }
7869 void visitStruct(QualType FT, SourceLocation SL) {
7870 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7871 visit(FD->getType(), FD->getLocation());
7872 }
7873 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
7874 SourceLocation SL) {
7875 visit(getContext().getBaseElementType(AT), SL);
7876 }
7877 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
7878 SourceLocation SL) {}
7879 void visitTrivial(QualType FT, SourceLocation SL) {}
7880 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
7881
7882 static void diag(QualType RT, const Expr *E, Sema &S) {
7883 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
7884 }
7885
7886 ASTContext &getContext() { return S.getASTContext(); }
7887
7888 const Expr *E;
7889 Sema &S;
7890};
7891
7892}
7893
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007894/// Check for dangerous or invalid arguments to memset().
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007895///
Chandler Carruthac687262011-06-03 06:23:57 +00007896/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007897/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7898/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007899///
7900/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007901void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007902 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007903 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007904 assert(BId != 0);
7905
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007906 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007907 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007908 unsigned ExpectedNumArgs =
7909 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007910 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007911 return;
7912
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007913 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007914 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007915 unsigned LenArg =
7916 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007917 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007918
Nico Weber0e6daef2013-12-26 23:38:39 +00007919 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7920 Call->getLocStart(), Call->getRParenLoc()))
7921 return;
7922
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007923 // We have special checking when the length is a sizeof expression.
7924 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7925 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7926 llvm::FoldingSetNodeID SizeOfArgID;
7927
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007928 // Although widely used, 'bzero' is not a standard function. Be more strict
7929 // with the argument types before allowing diagnostics and only allow the
7930 // form bzero(ptr, sizeof(...)).
7931 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7932 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7933 return;
7934
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007935 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7936 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007937 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007938
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007939 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007940 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007941 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007942 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007943
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007944 // Never warn about void type pointers. This can be used to suppress
7945 // false positives.
7946 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007947 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007948
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007949 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7950 // actually comparing the expressions for equality. Because computing the
7951 // expression IDs can be expensive, we only do this if the diagnostic is
7952 // enabled.
7953 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007954 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7955 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007956 // We only compute IDs for expressions if the warning is enabled, and
7957 // cache the sizeof arg's ID.
7958 if (SizeOfArgID == llvm::FoldingSetNodeID())
7959 SizeOfArg->Profile(SizeOfArgID, Context, true);
7960 llvm::FoldingSetNodeID DestID;
7961 Dest->Profile(DestID, Context, true);
7962 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007963 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7964 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007965 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007966 StringRef ReadableName = FnName->getName();
7967
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007968 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007969 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007970 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007971 if (!PointeeTy->isIncompleteType() &&
7972 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007973 ActionIdx = 2; // If the pointee's size is sizeof(char),
7974 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007975
7976 // If the function is defined as a builtin macro, do not show macro
7977 // expansion.
7978 SourceLocation SL = SizeOfArg->getExprLoc();
7979 SourceRange DSR = Dest->getSourceRange();
7980 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007981 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007982
7983 if (SM.isMacroArgExpansion(SL)) {
7984 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7985 SL = SM.getSpellingLoc(SL);
7986 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7987 SM.getSpellingLoc(DSR.getEnd()));
7988 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7989 SM.getSpellingLoc(SSR.getEnd()));
7990 }
7991
Anna Zaksd08d9152012-05-30 23:14:52 +00007992 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007993 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007994 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007995 << PointeeTy
7996 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007997 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007998 << SSR);
7999 DiagRuntimeBehavior(SL, SizeOfArg,
8000 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
8001 << ActionIdx
8002 << SSR);
8003
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008004 break;
8005 }
8006 }
8007
8008 // Also check for cases where the sizeof argument is the exact same
8009 // type as the memory argument, and where it points to a user-defined
8010 // record type.
8011 if (SizeOfArgTy != QualType()) {
8012 if (PointeeTy->isRecordType() &&
8013 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
8014 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
8015 PDiag(diag::warn_sizeof_pointer_type_memaccess)
8016 << FnName << SizeOfArgTy << ArgIdx
8017 << PointeeTy << Dest->getSourceRange()
8018 << LenExpr->getSourceRange());
8019 break;
8020 }
Nico Weberc5e73862011-06-14 16:14:58 +00008021 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00008022 } else if (DestTy->isArrayType()) {
8023 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00008024 }
Nico Weberc5e73862011-06-14 16:14:58 +00008025
Nico Weberc44b35e2015-03-21 17:37:46 +00008026 if (PointeeTy == QualType())
8027 continue;
Anna Zaks22122702012-01-17 00:37:07 +00008028
Nico Weberc44b35e2015-03-21 17:37:46 +00008029 // Always complain about dynamic classes.
8030 bool IsContained;
8031 if (const CXXRecordDecl *ContainedRD =
8032 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00008033
Nico Weberc44b35e2015-03-21 17:37:46 +00008034 unsigned OperationType = 0;
8035 // "overwritten" if we're warning about the destination for any call
8036 // but memcmp; otherwise a verb appropriate to the call.
8037 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
8038 if (BId == Builtin::BImemcpy)
8039 OperationType = 1;
8040 else if(BId == Builtin::BImemmove)
8041 OperationType = 2;
8042 else if (BId == Builtin::BImemcmp)
8043 OperationType = 3;
8044 }
8045
John McCall31168b02011-06-15 23:02:42 +00008046 DiagRuntimeBehavior(
8047 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00008048 PDiag(diag::warn_dyn_class_memaccess)
8049 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
8050 << FnName << IsContained << ContainedRD << OperationType
8051 << Call->getCallee()->getSourceRange());
8052 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
8053 BId != Builtin::BImemset)
8054 DiagRuntimeBehavior(
8055 Dest->getExprLoc(), Dest,
8056 PDiag(diag::warn_arc_object_memaccess)
8057 << ArgIdx << FnName << PointeeTy
8058 << Call->getCallee()->getSourceRange());
Akira Hatanaka2be04412018-04-17 19:13:41 +00008059 else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
8060 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
8061 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
8062 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
8063 PDiag(diag::warn_cstruct_memaccess)
8064 << ArgIdx << FnName << PointeeTy << 0);
8065 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
8066 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
8067 RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
8068 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
8069 PDiag(diag::warn_cstruct_memaccess)
8070 << ArgIdx << FnName << PointeeTy << 1);
8071 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
8072 } else {
8073 continue;
8074 }
8075 } else
Nico Weberc44b35e2015-03-21 17:37:46 +00008076 continue;
8077
8078 DiagRuntimeBehavior(
8079 Dest->getExprLoc(), Dest,
8080 PDiag(diag::note_bad_memaccess_silence)
8081 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
8082 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00008083 }
8084}
8085
Ted Kremenek6865f772011-08-18 20:55:45 +00008086// A little helper routine: ignore addition and subtraction of integer literals.
8087// This intentionally does not ignore all integer constant expressions because
8088// we don't want to remove sizeof().
8089static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
8090 Ex = Ex->IgnoreParenCasts();
8091
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008092 while (true) {
Ted Kremenek6865f772011-08-18 20:55:45 +00008093 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
8094 if (!BO || !BO->isAdditiveOp())
8095 break;
8096
8097 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
8098 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
8099
8100 if (isa<IntegerLiteral>(RHS))
8101 Ex = LHS;
8102 else if (isa<IntegerLiteral>(LHS))
8103 Ex = RHS;
8104 else
8105 break;
8106 }
8107
8108 return Ex;
8109}
8110
Anna Zaks13b08572012-08-08 21:42:23 +00008111static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
8112 ASTContext &Context) {
8113 // Only handle constant-sized or VLAs, but not flexible members.
8114 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
8115 // Only issue the FIXIT for arrays of size > 1.
8116 if (CAT->getSize().getSExtValue() <= 1)
8117 return false;
8118 } else if (!Ty->isVariableArrayType()) {
8119 return false;
8120 }
8121 return true;
8122}
8123
Ted Kremenek6865f772011-08-18 20:55:45 +00008124// Warn if the user has made the 'size' argument to strlcpy or strlcat
8125// be the size of the source, instead of the destination.
8126void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
8127 IdentifierInfo *FnName) {
8128
8129 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00008130 unsigned NumArgs = Call->getNumArgs();
8131 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00008132 return;
8133
8134 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
8135 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00008136 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00008137
8138 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
8139 Call->getLocStart(), Call->getRParenLoc()))
8140 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00008141
8142 // Look for 'strlcpy(dst, x, sizeof(x))'
8143 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
8144 CompareWithSrc = Ex;
8145 else {
8146 // Look for 'strlcpy(dst, x, strlen(x))'
8147 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00008148 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
8149 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00008150 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
8151 }
8152 }
8153
8154 if (!CompareWithSrc)
8155 return;
8156
8157 // Determine if the argument to sizeof/strlen is equal to the source
8158 // argument. In principle there's all kinds of things you could do
8159 // here, for instance creating an == expression and evaluating it with
8160 // EvaluateAsBooleanCondition, but this uses a more direct technique:
8161 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
8162 if (!SrcArgDRE)
8163 return;
8164
8165 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
8166 if (!CompareWithSrcDRE ||
8167 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
8168 return;
8169
8170 const Expr *OriginalSizeArg = Call->getArg(2);
8171 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
8172 << OriginalSizeArg->getSourceRange() << FnName;
8173
8174 // Output a FIXIT hint if the destination is an array (rather than a
8175 // pointer to an array). This could be enhanced to handle some
8176 // pointers if we know the actual size, like if DstArg is 'array+2'
8177 // we could say 'sizeof(array)-2'.
8178 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00008179 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00008180 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00008181
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008182 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00008183 llvm::raw_svector_ostream OS(sizeString);
8184 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008185 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00008186 OS << ")";
8187
8188 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
8189 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
8190 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00008191}
8192
Anna Zaks314cd092012-02-01 19:08:57 +00008193/// Check if two expressions refer to the same declaration.
8194static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
8195 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
8196 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
8197 return D1->getDecl() == D2->getDecl();
8198 return false;
8199}
8200
8201static const Expr *getStrlenExprArg(const Expr *E) {
8202 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8203 const FunctionDecl *FD = CE->getDirectCallee();
8204 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00008205 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00008206 return CE->getArg(0)->IgnoreParenCasts();
8207 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008208 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00008209}
8210
8211// Warn on anti-patterns as the 'size' argument to strncat.
8212// The correct size argument should look like following:
8213// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
8214void Sema::CheckStrncatArguments(const CallExpr *CE,
8215 IdentifierInfo *FnName) {
8216 // Don't crash if the user has the wrong number of arguments.
8217 if (CE->getNumArgs() < 3)
8218 return;
8219 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
8220 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
8221 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
8222
Nico Weber0e6daef2013-12-26 23:38:39 +00008223 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
8224 CE->getRParenLoc()))
8225 return;
8226
Anna Zaks314cd092012-02-01 19:08:57 +00008227 // Identify common expressions, which are wrongly used as the size argument
8228 // to strncat and may lead to buffer overflows.
8229 unsigned PatternType = 0;
8230 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
8231 // - sizeof(dst)
8232 if (referToTheSameDecl(SizeOfArg, DstArg))
8233 PatternType = 1;
8234 // - sizeof(src)
8235 else if (referToTheSameDecl(SizeOfArg, SrcArg))
8236 PatternType = 2;
8237 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
8238 if (BE->getOpcode() == BO_Sub) {
8239 const Expr *L = BE->getLHS()->IgnoreParenCasts();
8240 const Expr *R = BE->getRHS()->IgnoreParenCasts();
8241 // - sizeof(dst) - strlen(dst)
8242 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
8243 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
8244 PatternType = 1;
8245 // - sizeof(src) - (anything)
8246 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
8247 PatternType = 2;
8248 }
8249 }
8250
8251 if (PatternType == 0)
8252 return;
8253
Anna Zaks5069aa32012-02-03 01:27:37 +00008254 // Generate the diagnostic.
8255 SourceLocation SL = LenArg->getLocStart();
8256 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00008257 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00008258
8259 // If the function is defined as a builtin macro, do not show macro expansion.
8260 if (SM.isMacroArgExpansion(SL)) {
8261 SL = SM.getSpellingLoc(SL);
8262 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
8263 SM.getSpellingLoc(SR.getEnd()));
8264 }
8265
Anna Zaks13b08572012-08-08 21:42:23 +00008266 // Check if the destination is an array (rather than a pointer to an array).
8267 QualType DstTy = DstArg->getType();
8268 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
8269 Context);
8270 if (!isKnownSizeArray) {
8271 if (PatternType == 1)
8272 Diag(SL, diag::warn_strncat_wrong_size) << SR;
8273 else
8274 Diag(SL, diag::warn_strncat_src_size) << SR;
8275 return;
8276 }
8277
Anna Zaks314cd092012-02-01 19:08:57 +00008278 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00008279 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00008280 else
Anna Zaks5069aa32012-02-03 01:27:37 +00008281 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00008282
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008283 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00008284 llvm::raw_svector_ostream OS(sizeString);
8285 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008286 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00008287 OS << ") - ";
8288 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008289 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00008290 OS << ") - 1";
8291
Anna Zaks5069aa32012-02-03 01:27:37 +00008292 Diag(SL, diag::note_strncat_wrong_size)
8293 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00008294}
8295
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008296//===--- CHECK: Return Address of Stack Variable --------------------------===//
8297
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008298static const Expr *EvalVal(const Expr *E,
8299 SmallVectorImpl<const DeclRefExpr *> &refVars,
8300 const Decl *ParentDecl);
8301static const Expr *EvalAddr(const Expr *E,
8302 SmallVectorImpl<const DeclRefExpr *> &refVars,
8303 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008304
8305/// CheckReturnStackAddr - Check if a return statement returns the address
8306/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008307static void
8308CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
8309 SourceLocation ReturnLoc) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008310 const Expr *stackE = nullptr;
8311 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008312
8313 // Perform checking for returned stack addresses, local blocks,
8314 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00008315 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008316 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008317 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00008318 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008319 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008320 }
8321
Craig Topperc3ec1492014-05-26 06:22:03 +00008322 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008323 return; // Nothing suspicious was found.
8324
Simon Pilgrim750bde62017-03-31 11:00:53 +00008325 // Parameters are initialized in the calling scope, so taking the address
Richard Trieu81b6c562016-08-05 23:24:47 +00008326 // of a parameter reference doesn't need a warning.
8327 for (auto *DRE : refVars)
8328 if (isa<ParmVarDecl>(DRE->getDecl()))
8329 return;
8330
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008331 SourceLocation diagLoc;
8332 SourceRange diagRange;
8333 if (refVars.empty()) {
8334 diagLoc = stackE->getLocStart();
8335 diagRange = stackE->getSourceRange();
8336 } else {
8337 // We followed through a reference variable. 'stackE' contains the
8338 // problematic expression but we will warn at the return statement pointing
8339 // at the reference variable. We will later display the "trail" of
8340 // reference variables using notes.
8341 diagLoc = refVars[0]->getLocStart();
8342 diagRange = refVars[0]->getSourceRange();
8343 }
8344
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008345 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
8346 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00008347 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008348 << DR->getDecl()->getDeclName() << diagRange;
8349 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008350 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008351 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008352 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008353 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00008354 // If there is an LValue->RValue conversion, then the value of the
8355 // reference type is used, not the reference.
8356 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
8357 if (ICE->getCastKind() == CK_LValueToRValue) {
8358 return;
8359 }
8360 }
Craig Topperda7b27f2015-11-17 05:40:09 +00008361 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
8362 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008363 }
8364
8365 // Display the "trail" of reference variables that we followed until we
8366 // found the problematic expression using notes.
8367 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008368 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008369 // If this var binds to another reference var, show the range of the next
8370 // var, otherwise the var binds to the problematic expression, in which case
8371 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008372 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
8373 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008374 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
8375 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008376 }
8377}
8378
8379/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
8380/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008381/// to a location on the stack, a local block, an address of a label, or a
8382/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008383/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008384/// encounter a subexpression that (1) clearly does not lead to one of the
8385/// above problematic expressions (2) is something we cannot determine leads to
8386/// a problematic expression based on such local checking.
8387///
8388/// Both EvalAddr and EvalVal follow through reference variables to evaluate
8389/// the expression that they point to. Such variables are added to the
8390/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008391///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00008392/// EvalAddr processes expressions that are pointers that are used as
8393/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008394/// At the base case of the recursion is a check for the above problematic
8395/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008396///
8397/// This implementation handles:
8398///
8399/// * pointer-to-pointer casts
8400/// * implicit conversions from array references to pointers
8401/// * taking the address of fields
8402/// * arbitrary interplay between "&" and "*" operators
8403/// * pointer arithmetic from an address of a stack variable
8404/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008405static const Expr *EvalAddr(const Expr *E,
8406 SmallVectorImpl<const DeclRefExpr *> &refVars,
8407 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008408 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00008409 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008410
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008411 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00008412 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00008413 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00008414 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00008415 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00008416
Peter Collingbourne91147592011-04-15 00:35:48 +00008417 E = E->IgnoreParens();
8418
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008419 // Our "symbolic interpreter" is just a dispatch off the currently
8420 // viewed AST node. We then recursively traverse the AST by calling
8421 // EvalAddr and EvalVal appropriately.
8422 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008423 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008424 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008425
Richard Smith40f08eb2014-01-30 22:05:38 +00008426 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00008427 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00008428 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00008429
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008430 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008431 // If this is a reference variable, follow through to the expression that
8432 // it points to.
8433 if (V->hasLocalStorage() &&
8434 V->getType()->isReferenceType() && V->hasInit()) {
8435 // Add the reference variable to the "trail".
8436 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008437 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008438 }
8439
Craig Topperc3ec1492014-05-26 06:22:03 +00008440 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008441 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008442
Chris Lattner934edb22007-12-28 05:31:15 +00008443 case Stmt::UnaryOperatorClass: {
8444 // The only unary operator that make sense to handle here
8445 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008446 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008447
John McCalle3027922010-08-25 11:45:40 +00008448 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008449 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008450 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008451 }
Mike Stump11289f42009-09-09 15:08:12 +00008452
Chris Lattner934edb22007-12-28 05:31:15 +00008453 case Stmt::BinaryOperatorClass: {
8454 // Handle pointer arithmetic. All other binary operators are not valid
8455 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008456 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00008457 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00008458
John McCalle3027922010-08-25 11:45:40 +00008459 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00008460 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008461
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008462 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00008463
8464 // Determine which argument is the real pointer base. It could be
8465 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008466 if (!Base->getType()->isPointerType())
8467 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00008468
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008469 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008470 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00008471 }
Steve Naroff2752a172008-09-10 19:17:48 +00008472
Chris Lattner934edb22007-12-28 05:31:15 +00008473 // For conditional operators we need to see if either the LHS or RHS are
8474 // valid DeclRefExpr*s. If one of them is valid, we return it.
8475 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008476 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008477
Chris Lattner934edb22007-12-28 05:31:15 +00008478 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008479 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008480 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008481 // In C++, we can have a throw-expression, which has 'void' type.
8482 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008483 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008484 return LHS;
8485 }
Chris Lattner934edb22007-12-28 05:31:15 +00008486
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008487 // In C++, we can have a throw-expression, which has 'void' type.
8488 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00008489 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008490
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008491 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00008492 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008493
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008494 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00008495 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008496 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00008497 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008498
8499 case Stmt::AddrLabelExprClass:
8500 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00008501
John McCall28fc7092011-11-10 05:35:25 +00008502 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008503 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8504 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00008505
Ted Kremenekc3b4c522008-08-07 00:49:01 +00008506 // For casts, we need to handle conversions from arrays to
8507 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00008508 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00008509 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00008510 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00008511 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00008512 case Stmt::CXXStaticCastExprClass:
8513 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00008514 case Stmt::CXXConstCastExprClass:
8515 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008516 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00008517 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00008518 case CK_LValueToRValue:
8519 case CK_NoOp:
8520 case CK_BaseToDerived:
8521 case CK_DerivedToBase:
8522 case CK_UncheckedDerivedToBase:
8523 case CK_Dynamic:
8524 case CK_CPointerToObjCPointerCast:
8525 case CK_BlockPointerToObjCPointerCast:
8526 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008527 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00008528
8529 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008530 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00008531
Richard Trieudadefde2014-07-02 04:39:38 +00008532 case CK_BitCast:
8533 if (SubExpr->getType()->isAnyPointerType() ||
8534 SubExpr->getType()->isBlockPointerType() ||
8535 SubExpr->getType()->isObjCQualifiedIdType())
8536 return EvalAddr(SubExpr, refVars, ParentDecl);
8537 else
8538 return nullptr;
8539
Eli Friedman8195ad72012-02-23 23:04:32 +00008540 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00008541 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00008542 }
Chris Lattner934edb22007-12-28 05:31:15 +00008543 }
Mike Stump11289f42009-09-09 15:08:12 +00008544
Douglas Gregorfe314812011-06-21 17:03:29 +00008545 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008546 if (const Expr *Result =
8547 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8548 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00008549 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00008550 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008551
Chris Lattner934edb22007-12-28 05:31:15 +00008552 // Everything else: we simply don't reason about them.
8553 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00008554 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00008555 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008556}
Mike Stump11289f42009-09-09 15:08:12 +00008557
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008558/// EvalVal - This function is complements EvalAddr in the mutual recursion.
8559/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008560static const Expr *EvalVal(const Expr *E,
8561 SmallVectorImpl<const DeclRefExpr *> &refVars,
8562 const Decl *ParentDecl) {
8563 do {
8564 // We should only be called for evaluating non-pointer expressions, or
8565 // expressions with a pointer type that are not used as references but
8566 // instead
8567 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00008568
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008569 // Our "symbolic interpreter" is just a dispatch off the currently
8570 // viewed AST node. We then recursively traverse the AST by calling
8571 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00008572
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008573 E = E->IgnoreParens();
8574 switch (E->getStmtClass()) {
8575 case Stmt::ImplicitCastExprClass: {
8576 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
8577 if (IE->getValueKind() == VK_LValue) {
8578 E = IE->getSubExpr();
8579 continue;
8580 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008581 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008582 }
Richard Smith40f08eb2014-01-30 22:05:38 +00008583
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008584 case Stmt::ExprWithCleanupsClass:
8585 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8586 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008587
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008588 case Stmt::DeclRefExprClass: {
8589 // When we hit a DeclRefExpr we are looking at code that refers to a
8590 // variable's name. If it's not a reference variable we check if it has
8591 // local storage within the function, and if so, return the expression.
8592 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8593
8594 // If we leave the immediate function, the lifetime isn't about to end.
8595 if (DR->refersToEnclosingVariableOrCapture())
8596 return nullptr;
8597
8598 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
8599 // Check if it refers to itself, e.g. "int& i = i;".
8600 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008601 return DR;
8602
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008603 if (V->hasLocalStorage()) {
8604 if (!V->getType()->isReferenceType())
8605 return DR;
8606
8607 // Reference variable, follow through to the expression that
8608 // it points to.
8609 if (V->hasInit()) {
8610 // Add the reference variable to the "trail".
8611 refVars.push_back(DR);
8612 return EvalVal(V->getInit(), refVars, V);
8613 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008614 }
8615 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008616
8617 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008618 }
Mike Stump11289f42009-09-09 15:08:12 +00008619
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008620 case Stmt::UnaryOperatorClass: {
8621 // The only unary operator that make sense to handle here
8622 // is Deref. All others don't resolve to a "name." This includes
8623 // handling all sorts of rvalues passed to a unary operator.
8624 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008625
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008626 if (U->getOpcode() == UO_Deref)
8627 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00008628
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008629 return nullptr;
8630 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008631
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008632 case Stmt::ArraySubscriptExprClass: {
8633 // Array subscripts are potential references to data on the stack. We
8634 // retrieve the DeclRefExpr* for the array variable if it indeed
8635 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00008636 const auto *ASE = cast<ArraySubscriptExpr>(E);
8637 if (ASE->isTypeDependent())
8638 return nullptr;
8639 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008640 }
Mike Stump11289f42009-09-09 15:08:12 +00008641
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008642 case Stmt::OMPArraySectionExprClass: {
8643 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8644 ParentDecl);
8645 }
Mike Stump11289f42009-09-09 15:08:12 +00008646
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008647 case Stmt::ConditionalOperatorClass: {
8648 // For conditional operators we need to see if either the LHS or RHS are
8649 // non-NULL Expr's. If one is non-NULL, we return it.
8650 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008651
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008652 // Handle the GNU extension for missing LHS.
8653 if (const Expr *LHSExpr = C->getLHS()) {
8654 // In C++, we can have a throw-expression, which has 'void' type.
8655 if (!LHSExpr->getType()->isVoidType())
8656 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8657 return LHS;
8658 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008659
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008660 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008661 if (C->getRHS()->getType()->isVoidType())
8662 return nullptr;
8663
8664 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008665 }
8666
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008667 // Accesses to members are potential references to data on the stack.
8668 case Stmt::MemberExprClass: {
8669 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00008670
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008671 // Check for indirect access. We only want direct field accesses.
8672 if (M->isArrow())
8673 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008674
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008675 // Check whether the member type is itself a reference, in which case
8676 // we're not going to refer to the member, but to what the member refers
8677 // to.
8678 if (M->getMemberDecl()->getType()->isReferenceType())
8679 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008680
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008681 return EvalVal(M->getBase(), refVars, ParentDecl);
8682 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00008683
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008684 case Stmt::MaterializeTemporaryExprClass:
8685 if (const Expr *Result =
8686 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8687 refVars, ParentDecl))
8688 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008689 return E;
8690
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008691 default:
8692 // Check that we don't return or take the address of a reference to a
8693 // temporary. This is only useful in C++.
8694 if (!E->isTypeDependent() && E->isRValue())
8695 return E;
8696
8697 // Everything else: we simply don't reason about them.
8698 return nullptr;
8699 }
8700 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008701}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008702
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008703void
8704Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8705 SourceLocation ReturnLoc,
8706 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00008707 const AttrVec *Attrs,
8708 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008709 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8710
8711 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00008712 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8713 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00008714 CheckNonNullExpr(*this, RetValExp))
8715 Diag(ReturnLoc, diag::warn_null_ret)
8716 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00008717
8718 // C++11 [basic.stc.dynamic.allocation]p4:
8719 // If an allocation function declared with a non-throwing
8720 // exception-specification fails to allocate storage, it shall return
8721 // a null pointer. Any other allocation function that fails to allocate
8722 // storage shall indicate failure only by throwing an exception [...]
8723 if (FD) {
8724 OverloadedOperatorKind Op = FD->getOverloadedOperator();
8725 if (Op == OO_New || Op == OO_Array_New) {
8726 const FunctionProtoType *Proto
8727 = FD->getType()->castAs<FunctionProtoType>();
Richard Smitheaf11ad2018-05-03 03:58:32 +00008728 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
Artyom Skrobov9f213442014-01-24 11:10:39 +00008729 CheckNonNullExpr(*this, RetValExp))
8730 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8731 << FD << getLangOpts().CPlusPlus11;
8732 }
8733 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008734}
8735
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008736//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8737
8738/// Check for comparisons of floating point operands using != and ==.
8739/// Issue a warning if these are no self-comparisons, as they are not likely
8740/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00008741void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00008742 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8743 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008744
8745 // Special case: check for x == x (which is OK).
8746 // Do not emit warnings for such cases.
8747 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8748 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8749 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00008750 return;
Mike Stump11289f42009-09-09 15:08:12 +00008751
Ted Kremenekeda40e22007-11-29 00:59:04 +00008752 // Special case: check for comparisons against literals that can be exactly
8753 // represented by APFloat. In such cases, do not emit a warning. This
8754 // is a heuristic: often comparison against such literals are used to
8755 // detect if a value in a variable has not changed. This clearly can
8756 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00008757 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8758 if (FLL->isExact())
8759 return;
8760 } else
8761 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8762 if (FLR->isExact())
8763 return;
Mike Stump11289f42009-09-09 15:08:12 +00008764
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008765 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00008766 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008767 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008768 return;
Mike Stump11289f42009-09-09 15:08:12 +00008769
David Blaikie1f4ff152012-07-16 20:47:22 +00008770 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008771 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008772 return;
Mike Stump11289f42009-09-09 15:08:12 +00008773
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008774 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00008775 Diag(Loc, diag::warn_floatingpoint_eq)
8776 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008777}
John McCallca01b222010-01-04 23:21:16 +00008778
John McCall70aa5392010-01-06 05:24:50 +00008779//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8780//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00008781
John McCall70aa5392010-01-06 05:24:50 +00008782namespace {
John McCallca01b222010-01-04 23:21:16 +00008783
John McCall70aa5392010-01-06 05:24:50 +00008784/// Structure recording the 'active' range of an integer-valued
8785/// expression.
8786struct IntRange {
8787 /// The number of bits active in the int.
8788 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00008789
John McCall70aa5392010-01-06 05:24:50 +00008790 /// True if the int is known not to have negative values.
8791 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00008792
John McCall70aa5392010-01-06 05:24:50 +00008793 IntRange(unsigned Width, bool NonNegative)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008794 : Width(Width), NonNegative(NonNegative) {}
John McCallca01b222010-01-04 23:21:16 +00008795
John McCall817d4af2010-11-10 23:38:19 +00008796 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00008797 static IntRange forBoolType() {
8798 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00008799 }
8800
John McCall817d4af2010-11-10 23:38:19 +00008801 /// Returns the range of an opaque value of the given integral type.
8802 static IntRange forValueOfType(ASTContext &C, QualType T) {
8803 return forValueOfCanonicalType(C,
8804 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00008805 }
8806
John McCall817d4af2010-11-10 23:38:19 +00008807 /// Returns the range of an opaque value of a canonical integral type.
8808 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00008809 assert(T->isCanonicalUnqualified());
8810
8811 if (const VectorType *VT = dyn_cast<VectorType>(T))
8812 T = VT->getElementType().getTypePtr();
8813 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8814 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008815 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8816 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00008817
Roman Lebedevca1aaac2017-10-21 16:44:03 +00008818 if (!C.getLangOpts().CPlusPlus) {
8819 // For enum types in C code, use the underlying datatype.
8820 if (const EnumType *ET = dyn_cast<EnumType>(T))
8821 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8822 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8823 // For enum types in C++, use the known bit width of the enumerators.
David Majnemer6a426652013-06-07 22:07:20 +00008824 EnumDecl *Enum = ET->getDecl();
Richard Smith371e9e8a2017-12-06 03:00:51 +00008825 // In C++11, enums can have a fixed underlying type. Use this type to
8826 // compute the range.
8827 if (Enum->isFixed()) {
Erich Keane69dbbb02017-09-21 19:58:55 +00008828 return IntRange(C.getIntWidth(QualType(T, 0)),
8829 !ET->isSignedIntegerOrEnumerationType());
Richard Smith371e9e8a2017-12-06 03:00:51 +00008830 }
John McCall18a2c2c2010-11-09 22:22:12 +00008831
David Majnemer6a426652013-06-07 22:07:20 +00008832 unsigned NumPositive = Enum->getNumPositiveBits();
8833 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00008834
David Majnemer6a426652013-06-07 22:07:20 +00008835 if (NumNegative == 0)
8836 return IntRange(NumPositive, true/*NonNegative*/);
8837 else
8838 return IntRange(std::max(NumPositive + 1, NumNegative),
8839 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00008840 }
John McCall70aa5392010-01-06 05:24:50 +00008841
8842 const BuiltinType *BT = cast<BuiltinType>(T);
8843 assert(BT->isInteger());
8844
8845 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8846 }
8847
John McCall817d4af2010-11-10 23:38:19 +00008848 /// Returns the "target" range of a canonical integral type, i.e.
8849 /// the range of values expressible in the type.
8850 ///
8851 /// This matches forValueOfCanonicalType except that enums have the
8852 /// full range of their type, not the range of their enumerators.
8853 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8854 assert(T->isCanonicalUnqualified());
8855
8856 if (const VectorType *VT = dyn_cast<VectorType>(T))
8857 T = VT->getElementType().getTypePtr();
8858 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8859 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008860 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8861 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008862 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00008863 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008864
8865 const BuiltinType *BT = cast<BuiltinType>(T);
8866 assert(BT->isInteger());
8867
8868 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8869 }
8870
8871 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00008872 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00008873 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00008874 L.NonNegative && R.NonNegative);
8875 }
8876
John McCall817d4af2010-11-10 23:38:19 +00008877 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008878 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008879 return IntRange(std::min(L.Width, R.Width),
8880 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008881 }
8882};
8883
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008884} // namespace
8885
8886static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
8887 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008888 if (value.isSigned() && value.isNegative())
8889 return IntRange(value.getMinSignedBits(), false);
8890
8891 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008892 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008893
8894 // isNonNegative() just checks the sign bit without considering
8895 // signedness.
8896 return IntRange(value.getActiveBits(), true);
8897}
8898
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008899static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8900 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008901 if (result.isInt())
8902 return GetValueRange(C, result.getInt(), MaxWidth);
8903
8904 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008905 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8906 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8907 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8908 R = IntRange::join(R, El);
8909 }
John McCall70aa5392010-01-06 05:24:50 +00008910 return R;
8911 }
8912
8913 if (result.isComplexInt()) {
8914 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8915 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8916 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008917 }
8918
8919 // This can happen with lossless casts to intptr_t of "based" lvalues.
8920 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008921 // FIXME: The only reason we need to pass the type in here is to get
8922 // the sign right on this one case. It would be nice if APValue
8923 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008924 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008925 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008926}
John McCall70aa5392010-01-06 05:24:50 +00008927
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008928static QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008929 QualType Ty = E->getType();
8930 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8931 Ty = AtomicRHS->getValueType();
8932 return Ty;
8933}
8934
John McCall70aa5392010-01-06 05:24:50 +00008935/// Pseudo-evaluate the given integer expression, estimating the
8936/// range of values it might take.
8937///
8938/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008939static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008940 E = E->IgnoreParens();
8941
8942 // Try a full evaluation first.
8943 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008944 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008945 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008946
8947 // I think we only want to look through implicit casts here; if the
8948 // user has an explicit widening cast, we should treat the value as
8949 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008950 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00008951 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00008952 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8953
Eli Friedmane6d33952013-07-08 20:20:06 +00008954 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00008955
George Burgess IVdf1ed002016-01-13 01:52:39 +00008956 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8957 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00008958
John McCall70aa5392010-01-06 05:24:50 +00008959 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00008960 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00008961 return OutputTypeRange;
8962
8963 IntRange SubRange
8964 = GetExprRange(C, CE->getSubExpr(),
8965 std::min(MaxWidth, OutputTypeRange.Width));
8966
8967 // Bail out if the subexpr's range is as wide as the cast type.
8968 if (SubRange.Width >= OutputTypeRange.Width)
8969 return OutputTypeRange;
8970
8971 // Otherwise, we take the smaller width, and we're non-negative if
8972 // either the output type or the subexpr is.
8973 return IntRange(SubRange.Width,
8974 SubRange.NonNegative || OutputTypeRange.NonNegative);
8975 }
8976
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008977 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008978 // If we can fold the condition, just take that operand.
8979 bool CondResult;
8980 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8981 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8982 : CO->getFalseExpr(),
8983 MaxWidth);
8984
8985 // Otherwise, conservatively merge.
8986 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8987 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8988 return IntRange::join(L, R);
8989 }
8990
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008991 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008992 switch (BO->getOpcode()) {
Richard Smithc70f1d62017-12-14 15:16:18 +00008993 case BO_Cmp:
8994 llvm_unreachable("builtin <=> should have class type");
John McCall70aa5392010-01-06 05:24:50 +00008995
8996 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00008997 case BO_LAnd:
8998 case BO_LOr:
8999 case BO_LT:
9000 case BO_GT:
9001 case BO_LE:
9002 case BO_GE:
9003 case BO_EQ:
9004 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00009005 return IntRange::forBoolType();
9006
John McCallc3688382011-07-13 06:35:24 +00009007 // The type of the assignments is the type of the LHS, so the RHS
9008 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00009009 case BO_MulAssign:
9010 case BO_DivAssign:
9011 case BO_RemAssign:
9012 case BO_AddAssign:
9013 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00009014 case BO_XorAssign:
9015 case BO_OrAssign:
9016 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00009017 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00009018
John McCallc3688382011-07-13 06:35:24 +00009019 // Simple assignments just pass through the RHS, which will have
9020 // been coerced to the LHS type.
9021 case BO_Assign:
9022 // TODO: bitfields?
9023 return GetExprRange(C, BO->getRHS(), MaxWidth);
9024
John McCall70aa5392010-01-06 05:24:50 +00009025 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00009026 case BO_PtrMemD:
9027 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00009028 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009029
John McCall2ce81ad2010-01-06 22:07:33 +00009030 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00009031 case BO_And:
9032 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00009033 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
9034 GetExprRange(C, BO->getRHS(), MaxWidth));
9035
John McCall70aa5392010-01-06 05:24:50 +00009036 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00009037 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00009038 // ...except that we want to treat '1 << (blah)' as logically
9039 // positive. It's an important idiom.
9040 if (IntegerLiteral *I
9041 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
9042 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00009043 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00009044 return IntRange(R.Width, /*NonNegative*/ true);
9045 }
9046 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00009047 LLVM_FALLTHROUGH;
John McCall1bff9932010-04-07 01:14:35 +00009048
John McCalle3027922010-08-25 11:45:40 +00009049 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00009050 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009051
John McCall2ce81ad2010-01-06 22:07:33 +00009052 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00009053 case BO_Shr:
9054 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00009055 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9056
9057 // If the shift amount is a positive constant, drop the width by
9058 // that much.
9059 llvm::APSInt shift;
9060 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
9061 shift.isNonNegative()) {
9062 unsigned zext = shift.getZExtValue();
9063 if (zext >= L.Width)
9064 L.Width = (L.NonNegative ? 0 : 1);
9065 else
9066 L.Width -= zext;
9067 }
9068
9069 return L;
9070 }
9071
9072 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00009073 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00009074 return GetExprRange(C, BO->getRHS(), MaxWidth);
9075
John McCall2ce81ad2010-01-06 22:07:33 +00009076 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00009077 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00009078 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00009079 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009080 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00009081
John McCall51431812011-07-14 22:39:48 +00009082 // The width of a division result is mostly determined by the size
9083 // of the LHS.
9084 case BO_Div: {
9085 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00009086 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009087 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9088
9089 // If the divisor is constant, use that.
9090 llvm::APSInt divisor;
9091 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
9092 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
9093 if (log2 >= L.Width)
9094 L.Width = (L.NonNegative ? 0 : 1);
9095 else
9096 L.Width = std::min(L.Width - log2, MaxWidth);
9097 return L;
9098 }
9099
9100 // Otherwise, just use the LHS's width.
9101 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9102 return IntRange(L.Width, L.NonNegative && R.NonNegative);
9103 }
9104
9105 // The result of a remainder can't be larger than the result of
9106 // either side.
9107 case BO_Rem: {
9108 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00009109 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009110 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9111 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9112
9113 IntRange meet = IntRange::meet(L, R);
9114 meet.Width = std::min(meet.Width, MaxWidth);
9115 return meet;
9116 }
9117
9118 // The default behavior is okay for these.
9119 case BO_Mul:
9120 case BO_Add:
9121 case BO_Xor:
9122 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00009123 break;
9124 }
9125
John McCall51431812011-07-14 22:39:48 +00009126 // The default case is to treat the operation as if it were closed
9127 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00009128 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9129 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
9130 return IntRange::join(L, R);
9131 }
9132
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009133 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00009134 switch (UO->getOpcode()) {
9135 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00009136 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00009137 return IntRange::forBoolType();
9138
9139 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00009140 case UO_Deref:
9141 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00009142 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009143
9144 default:
9145 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
9146 }
9147 }
9148
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009149 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00009150 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
9151
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009152 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00009153 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00009154 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00009155
Eli Friedmane6d33952013-07-08 20:20:06 +00009156 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009157}
John McCall263a48b2010-01-04 23:31:57 +00009158
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009159static IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00009160 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00009161}
9162
John McCall263a48b2010-01-04 23:31:57 +00009163/// Checks whether the given value, which currently has the given
9164/// source semantics, has the same value when coerced through the
9165/// target semantics.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009166static bool IsSameFloatAfterCast(const llvm::APFloat &value,
9167 const llvm::fltSemantics &Src,
9168 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00009169 llvm::APFloat truncated = value;
9170
9171 bool ignored;
9172 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
9173 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
9174
9175 return truncated.bitwiseIsEqual(value);
9176}
9177
9178/// Checks whether the given value, which currently has the given
9179/// source semantics, has the same value when coerced through the
9180/// target semantics.
9181///
9182/// The value might be a vector of floats (or a complex number).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009183static bool IsSameFloatAfterCast(const APValue &value,
9184 const llvm::fltSemantics &Src,
9185 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00009186 if (value.isFloat())
9187 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
9188
9189 if (value.isVector()) {
9190 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
9191 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
9192 return false;
9193 return true;
9194 }
9195
9196 assert(value.isComplexFloat());
9197 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
9198 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
9199}
9200
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009201static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009202
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009203static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00009204 // Suppress cases where we are comparing against an enum constant.
9205 if (const DeclRefExpr *DR =
9206 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
9207 if (isa<EnumConstantDecl>(DR->getDecl()))
Roman Lebedev6de129e2017-10-15 20:13:17 +00009208 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00009209
9210 // Suppress cases where the '0' value is expanded from a macro.
9211 if (E->getLocStart().isMacroID())
Roman Lebedev6de129e2017-10-15 20:13:17 +00009212 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00009213
Roman Lebedev6de129e2017-10-15 20:13:17 +00009214 return false;
9215}
9216
Richard Smith692f66ab2017-12-06 19:23:19 +00009217static bool isKnownToHaveUnsignedValue(Expr *E) {
9218 return E->getType()->isIntegerType() &&
Roman Lebedev6de129e2017-10-15 20:13:17 +00009219 (!E->getType()->isSignedIntegerType() ||
9220 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
9221}
9222
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009223namespace {
Richard Smitha5370fb2017-12-08 22:57:11 +00009224/// The promoted range of values of a type. In general this has the
9225/// following structure:
9226///
9227/// |-----------| . . . |-----------|
9228/// ^ ^ ^ ^
9229/// Min HoleMin HoleMax Max
9230///
9231/// ... where there is only a hole if a signed type is promoted to unsigned
9232/// (in which case Min and Max are the smallest and largest representable
9233/// values).
9234struct PromotedRange {
9235 // Min, or HoleMax if there is a hole.
9236 llvm::APSInt PromotedMin;
9237 // Max, or HoleMin if there is a hole.
9238 llvm::APSInt PromotedMax;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009239
Richard Smitha5370fb2017-12-08 22:57:11 +00009240 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
9241 if (R.Width == 0)
9242 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
9243 else if (R.Width >= BitWidth && !Unsigned) {
9244 // Promotion made the type *narrower*. This happens when promoting
9245 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
9246 // Treat all values of 'signed int' as being in range for now.
9247 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
9248 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
9249 } else {
9250 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
9251 .extOrTrunc(BitWidth);
9252 PromotedMin.setIsUnsigned(Unsigned);
9253
9254 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
9255 .extOrTrunc(BitWidth);
9256 PromotedMax.setIsUnsigned(Unsigned);
9257 }
9258 }
9259
9260 // Determine whether this range is contiguous (has no hole).
9261 bool isContiguous() const { return PromotedMin <= PromotedMax; }
9262
9263 // Where a constant value is within the range.
9264 enum ComparisonResult {
9265 LT = 0x1,
9266 LE = 0x2,
9267 GT = 0x4,
9268 GE = 0x8,
9269 EQ = 0x10,
9270 NE = 0x20,
9271 InRangeFlag = 0x40,
9272
9273 Less = LE | LT | NE,
9274 Min = LE | InRangeFlag,
9275 InRange = InRangeFlag,
9276 Max = GE | InRangeFlag,
9277 Greater = GE | GT | NE,
9278
9279 OnlyValue = LE | GE | EQ | InRangeFlag,
9280 InHole = NE
9281 };
9282
9283 ComparisonResult compare(const llvm::APSInt &Value) const {
9284 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
9285 Value.isUnsigned() == PromotedMin.isUnsigned());
9286 if (!isContiguous()) {
9287 assert(Value.isUnsigned() && "discontiguous range for signed compare");
9288 if (Value.isMinValue()) return Min;
9289 if (Value.isMaxValue()) return Max;
9290 if (Value >= PromotedMin) return InRange;
9291 if (Value <= PromotedMax) return InRange;
9292 return InHole;
9293 }
9294
9295 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
9296 case -1: return Less;
9297 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
9298 case 1:
9299 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
9300 case -1: return InRange;
9301 case 0: return Max;
9302 case 1: return Greater;
9303 }
9304 }
9305
9306 llvm_unreachable("impossible compare result");
9307 }
9308
Richard Smithc70f1d62017-12-14 15:16:18 +00009309 static llvm::Optional<StringRef>
9310 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
9311 if (Op == BO_Cmp) {
9312 ComparisonResult LTFlag = LT, GTFlag = GT;
9313 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
9314
9315 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
9316 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
9317 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
9318 return llvm::None;
9319 }
9320
Richard Smitha5370fb2017-12-08 22:57:11 +00009321 ComparisonResult TrueFlag, FalseFlag;
9322 if (Op == BO_EQ) {
9323 TrueFlag = EQ;
9324 FalseFlag = NE;
9325 } else if (Op == BO_NE) {
9326 TrueFlag = NE;
9327 FalseFlag = EQ;
9328 } else {
9329 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
9330 TrueFlag = LT;
9331 FalseFlag = GE;
9332 } else {
9333 TrueFlag = GT;
9334 FalseFlag = LE;
9335 }
9336 if (Op == BO_GE || Op == BO_LE)
9337 std::swap(TrueFlag, FalseFlag);
9338 }
9339 if (R & TrueFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00009340 return StringRef("true");
Richard Smitha5370fb2017-12-08 22:57:11 +00009341 if (R & FalseFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00009342 return StringRef("false");
Richard Smitha5370fb2017-12-08 22:57:11 +00009343 return llvm::None;
9344 }
Roman Lebedev6de129e2017-10-15 20:13:17 +00009345};
John McCallcc7e5bf2010-05-06 08:58:33 +00009346}
9347
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009348static bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00009349 // Strip off implicit integral promotions.
9350 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00009351 if (ICE->getCastKind() != CK_IntegralCast &&
9352 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00009353 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00009354 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00009355 }
9356
9357 return E->getType()->isEnumeralType();
9358}
9359
Richard Smith692f66ab2017-12-06 19:23:19 +00009360static int classifyConstantValue(Expr *Constant) {
9361 // The values of this enumeration are used in the diagnostics
9362 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
9363 enum ConstantValueKind {
9364 Miscellaneous = 0,
9365 LiteralTrue,
9366 LiteralFalse
9367 };
9368 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
9369 return BL->getValue() ? ConstantValueKind::LiteralTrue
9370 : ConstantValueKind::LiteralFalse;
9371 return ConstantValueKind::Miscellaneous;
9372}
9373
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009374static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
9375 Expr *Constant, Expr *Other,
9376 const llvm::APSInt &Value,
9377 bool RhsConstant) {
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009378 if (S.inTemplateInstantiation())
9379 return false;
9380
Richard Smitha5370fb2017-12-08 22:57:11 +00009381 Expr *OriginalOther = Other;
9382
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009383 Constant = Constant->IgnoreParenImpCasts();
9384 Other = Other->IgnoreParenImpCasts();
9385
Richard Smitha5370fb2017-12-08 22:57:11 +00009386 // Suppress warnings on tautological comparisons between values of the same
9387 // enumeration type. There are only two ways we could warn on this:
9388 // - If the constant is outside the range of representable values of
9389 // the enumeration. In such a case, we should warn about the cast
9390 // to enumeration type, not about the comparison.
9391 // - If the constant is the maximum / minimum in-range value. For an
9392 // enumeratin type, such comparisons can be meaningful and useful.
9393 if (Constant->getType()->isEnumeralType() &&
9394 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
9395 return false;
9396
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009397 // TODO: Investigate using GetExprRange() to get tighter bounds
9398 // on the bit ranges.
9399 QualType OtherT = Other->getType();
9400 if (const auto *AT = OtherT->getAs<AtomicType>())
9401 OtherT = AT->getValueType();
9402 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
9403
9404 // Whether we're treating Other as being a bool because of the form of
9405 // expression despite it having another type (typically 'int' in C).
9406 bool OtherIsBooleanDespiteType =
9407 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
9408 if (OtherIsBooleanDespiteType)
9409 OtherRange = IntRange::forBoolType();
9410
Richard Smitha5370fb2017-12-08 22:57:11 +00009411 // Determine the promoted range of the other type and see if a comparison of
9412 // the constant against that range is tautological.
9413 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
9414 Value.isUnsigned());
9415 auto Cmp = OtherPromotedRange.compare(Value);
9416 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
9417 if (!Result)
9418 return false;
Hans Wennborg5791ce72017-12-08 16:54:08 +00009419
Richard Smitha5370fb2017-12-08 22:57:11 +00009420 // Suppress the diagnostic for an in-range comparison if the constant comes
9421 // from a macro or enumerator. We don't want to diagnose
9422 //
9423 // some_long_value <= INT_MAX
9424 //
9425 // when sizeof(int) == sizeof(long).
9426 bool InRange = Cmp & PromotedRange::InRangeFlag;
9427 if (InRange && IsEnumConstOrFromMacro(S, Constant))
9428 return false;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009429
9430 // If this is a comparison to an enum constant, include that
9431 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00009432 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009433 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
9434 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
9435
Richard Smitha5370fb2017-12-08 22:57:11 +00009436 // Should be enough for uint128 (39 decimal digits)
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009437 SmallString<64> PrettySourceValue;
9438 llvm::raw_svector_ostream OS(PrettySourceValue);
9439 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00009440 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009441 else
9442 OS << Value;
9443
Richard Smitha5370fb2017-12-08 22:57:11 +00009444 // FIXME: We use a somewhat different formatting for the in-range cases and
9445 // cases involving boolean values for historical reasons. We should pick a
9446 // consistent way of presenting these diagnostics.
9447 if (!InRange || Other->isKnownToHaveBooleanValue()) {
9448 S.DiagRuntimeBehavior(
9449 E->getOperatorLoc(), E,
9450 S.PDiag(!InRange ? diag::warn_out_of_range_compare
9451 : diag::warn_tautological_bool_compare)
9452 << OS.str() << classifyConstantValue(Constant)
9453 << OtherT << OtherIsBooleanDespiteType << *Result
9454 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
9455 } else {
9456 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
9457 ? (HasEnumType(OriginalOther)
9458 ? diag::warn_unsigned_enum_always_true_comparison
9459 : diag::warn_unsigned_always_true_comparison)
9460 : diag::warn_tautological_constant_compare;
Roman Lebedev6de129e2017-10-15 20:13:17 +00009461
Richard Smitha5370fb2017-12-08 22:57:11 +00009462 S.Diag(E->getOperatorLoc(), Diag)
9463 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
9464 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
9465 }
9466
9467 return true;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009468}
9469
John McCallcc7e5bf2010-05-06 08:58:33 +00009470/// Analyze the operands of the given comparison. Implements the
9471/// fallback case from AnalyzeComparison.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009472static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00009473 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9474 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009475}
John McCall263a48b2010-01-04 23:31:57 +00009476
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009477/// Implements -Wsign-compare.
John McCallca01b222010-01-04 23:21:16 +00009478///
Richard Trieu82402a02011-09-15 21:56:47 +00009479/// \param E the binary operator to check for warnings
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009480static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009481 // The type the comparison is being performed in.
9482 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00009483
9484 // Only analyze comparison operators where both sides have been converted to
9485 // the same type.
9486 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
9487 return AnalyzeImpConvsInComparison(S, E);
9488
9489 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00009490 if (E->isValueDependent())
9491 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00009492
Roman Lebedev6de129e2017-10-15 20:13:17 +00009493 Expr *LHS = E->getLHS();
9494 Expr *RHS = E->getRHS();
9495
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009496 if (T->isIntegralType(S.Context)) {
9497 llvm::APSInt RHSValue;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009498 llvm::APSInt LHSValue;
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009499
Roman Lebedev6de129e2017-10-15 20:13:17 +00009500 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
9501 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
Roman Lebedevbd1fc222017-10-12 20:16:51 +00009502
Roman Lebedev6de129e2017-10-15 20:13:17 +00009503 // We don't care about expressions whose result is a constant.
9504 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
9505 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6f405db2017-10-12 22:03:20 +00009506
Roman Lebedev6de129e2017-10-15 20:13:17 +00009507 // We only care about expressions where just one side is literal
9508 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
9509 // Is the constant on the RHS or LHS?
9510 const bool RhsConstant = IsRHSIntegralLiteral;
9511 Expr *Const = RhsConstant ? RHS : LHS;
9512 Expr *Other = RhsConstant ? LHS : RHS;
9513 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
9514
9515 // Check whether an integer constant comparison results in a value
9516 // of 'true' or 'false'.
Roman Lebedev6de129e2017-10-15 20:13:17 +00009517 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
9518 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00009519 }
9520 }
9521
9522 if (!T->hasUnsignedIntegerRepresentation()) {
9523 // We don't do anything special if this isn't an unsigned integral
9524 // comparison: we're only interested in integral comparisons, and
9525 // signed comparisons only happen in cases we don't care to warn about.
Roman Lebedev6f405db2017-10-12 22:03:20 +00009526 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00009527 }
9528
9529 LHS = LHS->IgnoreParenImpCasts();
9530 RHS = RHS->IgnoreParenImpCasts();
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009531
Alex Lorenzb57409f2018-02-07 20:45:39 +00009532 if (!S.getLangOpts().CPlusPlus) {
9533 // Avoid warning about comparison of integers with different signs when
9534 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
9535 // the type of `E`.
9536 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
9537 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9538 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
9539 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9540 }
9541
John McCallcc7e5bf2010-05-06 08:58:33 +00009542 // Check to see if one of the (unmodified) operands is of different
9543 // signedness.
9544 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00009545 if (LHS->getType()->hasSignedIntegerRepresentation()) {
9546 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00009547 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00009548 signedOperand = LHS;
9549 unsignedOperand = RHS;
9550 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
9551 signedOperand = RHS;
9552 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00009553 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00009554 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00009555 }
9556
John McCallcc7e5bf2010-05-06 08:58:33 +00009557 // Otherwise, calculate the effective range of the signed operand.
9558 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00009559
John McCallcc7e5bf2010-05-06 08:58:33 +00009560 // Go ahead and analyze implicit conversions in the operands. Note
9561 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00009562 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
9563 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00009564
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009565 // If the signed range is non-negative, -Wsign-compare won't fire.
John McCallcc7e5bf2010-05-06 08:58:33 +00009566 if (signedRange.NonNegative)
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009567 return;
John McCallca01b222010-01-04 23:21:16 +00009568
9569 // For (in)equality comparisons, if the unsigned operand is a
9570 // constant which cannot collide with a overflowed signed operand,
9571 // then reinterpreting the signed operand as unsigned will not
9572 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00009573 if (E->isEqualityOp()) {
9574 unsigned comparisonWidth = S.Context.getIntWidth(T);
9575 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00009576
John McCallcc7e5bf2010-05-06 08:58:33 +00009577 // We should never be unable to prove that the unsigned operand is
9578 // non-negative.
9579 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
9580
9581 if (unsignedRange.Width < comparisonWidth)
9582 return;
9583 }
9584
Douglas Gregorbfb4a212012-05-01 01:53:49 +00009585 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9586 S.PDiag(diag::warn_mixed_sign_comparison)
9587 << LHS->getType() << RHS->getType()
9588 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00009589}
9590
John McCall1f425642010-11-11 03:21:53 +00009591/// Analyzes an attempt to assign the given value to a bitfield.
9592///
9593/// Returns true if there was something fishy about the attempt.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009594static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9595 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00009596 assert(Bitfield->isBitField());
9597 if (Bitfield->isInvalidDecl())
9598 return false;
9599
John McCalldeebbcf2010-11-11 05:33:51 +00009600 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00009601 QualType BitfieldType = Bitfield->getType();
9602 if (BitfieldType->isBooleanType())
9603 return false;
9604
9605 if (BitfieldType->isEnumeralType()) {
9606 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9607 // If the underlying enum type was not explicitly specified as an unsigned
9608 // type and the enum contain only positive values, MSVC++ will cause an
9609 // inconsistency by storing this as a signed type.
9610 if (S.getLangOpts().CPlusPlus11 &&
9611 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9612 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9613 BitfieldEnumDecl->getNumNegativeBits() == 0) {
9614 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9615 << BitfieldEnumDecl->getNameAsString();
9616 }
9617 }
9618
John McCalldeebbcf2010-11-11 05:33:51 +00009619 if (Bitfield->getType()->isBooleanType())
9620 return false;
9621
Douglas Gregor789adec2011-02-04 13:09:01 +00009622 // Ignore value- or type-dependent expressions.
9623 if (Bitfield->getBitWidth()->isValueDependent() ||
9624 Bitfield->getBitWidth()->isTypeDependent() ||
9625 Init->isValueDependent() ||
9626 Init->isTypeDependent())
9627 return false;
9628
John McCall1f425642010-11-11 03:21:53 +00009629 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00009630 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00009631
Richard Smith5fab0c92011-12-28 19:48:30 +00009632 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009633 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9634 Expr::SE_AllowSideEffects)) {
9635 // The RHS is not constant. If the RHS has an enum type, make sure the
9636 // bitfield is wide enough to hold all the values of the enum without
9637 // truncation.
9638 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9639 EnumDecl *ED = EnumTy->getDecl();
9640 bool SignedBitfield = BitfieldType->isSignedIntegerType();
9641
9642 // Enum types are implicitly signed on Windows, so check if there are any
9643 // negative enumerators to see if the enum was intended to be signed or
9644 // not.
9645 bool SignedEnum = ED->getNumNegativeBits() > 0;
9646
9647 // Check for surprising sign changes when assigning enum values to a
9648 // bitfield of different signedness. If the bitfield is signed and we
9649 // have exactly the right number of bits to store this unsigned enum,
9650 // suggest changing the enum to an unsigned type. This typically happens
9651 // on Windows where unfixed enums always use an underlying type of 'int'.
9652 unsigned DiagID = 0;
9653 if (SignedEnum && !SignedBitfield) {
9654 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9655 } else if (SignedBitfield && !SignedEnum &&
9656 ED->getNumPositiveBits() == FieldWidth) {
9657 DiagID = diag::warn_signed_bitfield_enum_conversion;
9658 }
9659
9660 if (DiagID) {
9661 S.Diag(InitLoc, DiagID) << Bitfield << ED;
9662 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9663 SourceRange TypeRange =
9664 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9665 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9666 << SignedEnum << TypeRange;
9667 }
9668
9669 // Compute the required bitwidth. If the enum has negative values, we need
9670 // one more bit than the normal number of positive bits to represent the
9671 // sign bit.
9672 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9673 ED->getNumNegativeBits())
9674 : ED->getNumPositiveBits();
9675
9676 // Check the bitwidth.
9677 if (BitsNeeded > FieldWidth) {
9678 Expr *WidthExpr = Bitfield->getBitWidth();
9679 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9680 << Bitfield << ED;
9681 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9682 << BitsNeeded << ED << WidthExpr->getSourceRange();
9683 }
9684 }
9685
John McCall1f425642010-11-11 03:21:53 +00009686 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009687 }
John McCall1f425642010-11-11 03:21:53 +00009688
John McCall1f425642010-11-11 03:21:53 +00009689 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00009690
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009691 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00009692 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009693 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9694 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00009695
John McCall1f425642010-11-11 03:21:53 +00009696 if (OriginalWidth <= FieldWidth)
9697 return false;
9698
Eli Friedmanc267a322012-01-26 23:11:39 +00009699 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00009700 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00009701 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00009702
Eli Friedmanc267a322012-01-26 23:11:39 +00009703 // Check whether the stored value is equal to the original value.
9704 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00009705 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00009706 return false;
9707
Eli Friedmanc267a322012-01-26 23:11:39 +00009708 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00009709 // therefore don't strictly fit into a signed bitfield of width 1.
9710 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00009711 return false;
9712
John McCall1f425642010-11-11 03:21:53 +00009713 std::string PrettyValue = Value.toString(10);
9714 std::string PrettyTrunc = TruncatedValue.toString(10);
9715
9716 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9717 << PrettyValue << PrettyTrunc << OriginalInit->getType()
9718 << Init->getSourceRange();
9719
9720 return true;
9721}
9722
John McCalld2a53122010-11-09 23:24:47 +00009723/// Analyze the given simple or compound assignment for warning-worthy
9724/// operations.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009725static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00009726 // Just recurse on the LHS.
9727 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9728
9729 // We want to recurse on the RHS as normal unless we're assigning to
9730 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00009731 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009732 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00009733 E->getOperatorLoc())) {
9734 // Recurse, ignoring any implicit conversions on the RHS.
9735 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9736 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00009737 }
9738 }
9739
9740 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9741}
9742
John McCall263a48b2010-01-04 23:31:57 +00009743/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009744static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9745 SourceLocation CContext, unsigned diag,
9746 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009747 if (pruneControlFlow) {
9748 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9749 S.PDiag(diag)
9750 << SourceType << T << E->getSourceRange()
9751 << SourceRange(CContext));
9752 return;
9753 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00009754 S.Diag(E->getExprLoc(), diag)
9755 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9756}
9757
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009758/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009759static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
9760 SourceLocation CContext,
9761 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009762 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009763}
9764
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +00009765/// Analyze the given compound assignment for the possible losing of
9766/// floating-point precision.
9767static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
9768 assert(isa<CompoundAssignOperator>(E) &&
9769 "Must be compound assignment operation");
9770 // Recurse on the LHS and RHS in here
9771 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9772 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9773
9774 // Now check the outermost expression
9775 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
9776 const auto *RBT = cast<CompoundAssignOperator>(E)
9777 ->getComputationResultType()
9778 ->getAs<BuiltinType>();
9779
9780 // If both source and target are floating points.
9781 if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint())
9782 // Builtin FP kinds are ordered by increasing FP rank.
9783 if (ResultBT->getKind() < RBT->getKind())
9784 // We don't want to warn for system macro.
9785 if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
9786 // warn about dropping FP rank.
9787 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(),
9788 E->getOperatorLoc(),
9789 diag::warn_impcast_float_result_precision);
9790}
Richard Trieube234c32016-04-21 21:04:55 +00009791
9792/// Diagnose an implicit cast from a floating point value to an integer value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009793static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9794 SourceLocation CContext) {
Richard Trieube234c32016-04-21 21:04:55 +00009795 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00009796 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00009797
9798 Expr *InnerE = E->IgnoreParenImpCasts();
9799 // We also want to warn on, e.g., "int i = -1.234"
9800 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9801 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9802 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9803
9804 const bool IsLiteral =
9805 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9806
9807 llvm::APFloat Value(0.0);
9808 bool IsConstant =
9809 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9810 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00009811 return DiagnoseImpCast(S, E, T, CContext,
9812 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00009813 }
9814
Chandler Carruth016ef402011-04-10 08:36:24 +00009815 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00009816
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00009817 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9818 T->hasUnsignedIntegerRepresentation());
Erich Keanea4c48c62018-05-08 21:26:21 +00009819 llvm::APFloat::opStatus Result = Value.convertToInteger(
9820 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
9821
9822 if (Result == llvm::APFloat::opOK && isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00009823 if (IsLiteral) return;
9824 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9825 PruneWarnings);
9826 }
9827
Erich Keanea4c48c62018-05-08 21:26:21 +00009828 // Conversion of a floating-point value to a non-bool integer where the
9829 // integral part cannot be represented by the integer type is undefined.
9830 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
9831 return DiagnoseImpCast(
9832 S, E, T, CContext,
9833 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
Richard Trieua2b8fe62018-05-14 23:21:48 +00009834 : diag::warn_impcast_float_to_integer_out_of_range,
9835 PruneWarnings);
Erich Keanea4c48c62018-05-08 21:26:21 +00009836
Richard Trieube234c32016-04-21 21:04:55 +00009837 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00009838 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00009839 // Warn on floating point literal to integer.
9840 DiagID = diag::warn_impcast_literal_float_to_integer;
9841 } else if (IntegerValue == 0) {
9842 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
9843 return DiagnoseImpCast(S, E, T, CContext,
9844 diag::warn_impcast_float_integer, PruneWarnings);
9845 }
9846 // Warn on non-zero to zero conversion.
9847 DiagID = diag::warn_impcast_float_to_integer_zero;
9848 } else {
9849 if (IntegerValue.isUnsigned()) {
9850 if (!IntegerValue.isMaxValue()) {
9851 return DiagnoseImpCast(S, E, T, CContext,
9852 diag::warn_impcast_float_integer, PruneWarnings);
9853 }
9854 } else { // IntegerValue.isSigned()
9855 if (!IntegerValue.isMaxSignedValue() &&
9856 !IntegerValue.isMinSignedValue()) {
9857 return DiagnoseImpCast(S, E, T, CContext,
9858 diag::warn_impcast_float_integer, PruneWarnings);
9859 }
9860 }
9861 // Warn on evaluatable floating point expression to integer conversion.
9862 DiagID = diag::warn_impcast_float_to_integer;
9863 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009864
Eli Friedman07185912013-08-29 23:44:43 +00009865 // FIXME: Force the precision of the source value down so we don't print
9866 // digits which are usually useless (we don't really care here if we
9867 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9868 // would automatically print the shortest representation, but it's a bit
9869 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00009870 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00009871 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9872 precision = (precision * 59 + 195) / 196;
9873 Value.toString(PrettySourceValue, precision);
9874
David Blaikie9b88cc02012-05-15 17:18:27 +00009875 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00009876 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00009877 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00009878 else
David Blaikie9b88cc02012-05-15 17:18:27 +00009879 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00009880
Richard Trieube234c32016-04-21 21:04:55 +00009881 if (PruneWarnings) {
9882 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9883 S.PDiag(DiagID)
9884 << E->getType() << T.getUnqualifiedType()
9885 << PrettySourceValue << PrettyTargetValue
9886 << E->getSourceRange() << SourceRange(CContext));
9887 } else {
9888 S.Diag(E->getExprLoc(), DiagID)
9889 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9890 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9891 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009892}
9893
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009894static std::string PrettyPrintInRange(const llvm::APSInt &Value,
9895 IntRange Range) {
John McCall18a2c2c2010-11-09 22:22:12 +00009896 if (!Range.Width) return "0";
9897
9898 llvm::APSInt ValueInRange = Value;
9899 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00009900 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00009901 return ValueInRange.toString(10);
9902}
9903
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009904static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009905 if (!isa<ImplicitCastExpr>(Ex))
9906 return false;
9907
9908 Expr *InnerE = Ex->IgnoreParenImpCasts();
9909 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9910 const Type *Source =
9911 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9912 if (Target->isDependentType())
9913 return false;
9914
9915 const BuiltinType *FloatCandidateBT =
9916 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9917 const Type *BoolCandidateType = ToBool ? Target : Source;
9918
9919 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9920 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9921}
9922
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009923static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9924 SourceLocation CC) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009925 unsigned NumArgs = TheCall->getNumArgs();
9926 for (unsigned i = 0; i < NumArgs; ++i) {
9927 Expr *CurrA = TheCall->getArg(i);
9928 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9929 continue;
9930
9931 bool IsSwapped = ((i > 0) &&
9932 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9933 IsSwapped |= ((i < (NumArgs - 1)) &&
9934 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9935 if (IsSwapped) {
9936 // Warn on this floating-point to bool conversion.
9937 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9938 CurrA->getType(), CC,
9939 diag::warn_impcast_floating_point_to_bool);
9940 }
9941 }
9942}
9943
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009944static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
9945 SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009946 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9947 E->getExprLoc()))
9948 return;
9949
Richard Trieu09d6b802016-01-08 23:35:06 +00009950 // Don't warn on functions which have return type nullptr_t.
9951 if (isa<CallExpr>(E))
9952 return;
9953
Richard Trieu5b993502014-10-15 03:42:06 +00009954 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9955 const Expr::NullPointerConstantKind NullKind =
9956 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9957 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9958 return;
9959
9960 // Return if target type is a safe conversion.
9961 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9962 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9963 return;
9964
9965 SourceLocation Loc = E->getSourceRange().getBegin();
9966
Richard Trieu0a5e1662016-02-13 00:58:53 +00009967 // Venture through the macro stacks to get to the source of macro arguments.
9968 // The new location is a better location than the complete location that was
9969 // passed in.
George Karpenkov441e8fd2018-02-09 23:30:07 +00009970 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
9971 CC = S.SourceMgr.getTopMacroCallerLoc(CC);
Richard Trieu0a5e1662016-02-13 00:58:53 +00009972
Richard Trieu5b993502014-10-15 03:42:06 +00009973 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00009974 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9975 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9976 Loc, S.SourceMgr, S.getLangOpts());
9977 if (MacroName == "NULL")
Richard Smithb5f81712018-04-30 05:25:48 +00009978 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
Richard Trieu5b993502014-10-15 03:42:06 +00009979 }
9980
9981 // Only warn if the null and context location are in the same macro expansion.
9982 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9983 return;
9984
9985 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009986 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
Richard Trieu5b993502014-10-15 03:42:06 +00009987 << FixItHint::CreateReplacement(Loc,
9988 S.getFixItZeroLiteralForType(T, Loc));
9989}
9990
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009991static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9992 ObjCArrayLiteral *ArrayLiteral);
9993
9994static void
9995checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9996 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00009997
9998/// Check a single element within a collection literal against the
9999/// target element type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010000static void checkObjCCollectionLiteralElement(Sema &S,
10001 QualType TargetElementType,
10002 Expr *Element,
10003 unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000010004 // Skip a bitcast to 'id' or qualified 'id'.
10005 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
10006 if (ICE->getCastKind() == CK_BitCast &&
10007 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
10008 Element = ICE->getSubExpr();
10009 }
10010
10011 QualType ElementType = Element->getType();
10012 ExprResult ElementResult(Element);
10013 if (ElementType->getAs<ObjCObjectPointerType>() &&
10014 S.CheckSingleAssignmentConstraints(TargetElementType,
10015 ElementResult,
10016 false, false)
10017 != Sema::Compatible) {
10018 S.Diag(Element->getLocStart(),
10019 diag::warn_objc_collection_literal_element)
10020 << ElementType << ElementKind << TargetElementType
10021 << Element->getSourceRange();
10022 }
10023
10024 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
10025 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
10026 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
10027 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
10028}
10029
10030/// Check an Objective-C array literal being converted to the given
10031/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010032static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10033 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000010034 if (!S.NSArrayDecl)
10035 return;
10036
10037 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10038 if (!TargetObjCPtr)
10039 return;
10040
10041 if (TargetObjCPtr->isUnspecialized() ||
10042 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10043 != S.NSArrayDecl->getCanonicalDecl())
10044 return;
10045
10046 auto TypeArgs = TargetObjCPtr->getTypeArgs();
10047 if (TypeArgs.size() != 1)
10048 return;
10049
10050 QualType TargetElementType = TypeArgs[0];
10051 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
10052 checkObjCCollectionLiteralElement(S, TargetElementType,
10053 ArrayLiteral->getElement(I),
10054 0);
10055 }
10056}
10057
10058/// Check an Objective-C dictionary literal being converted to the given
10059/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010060static void
10061checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10062 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000010063 if (!S.NSDictionaryDecl)
10064 return;
10065
10066 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10067 if (!TargetObjCPtr)
10068 return;
10069
10070 if (TargetObjCPtr->isUnspecialized() ||
10071 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10072 != S.NSDictionaryDecl->getCanonicalDecl())
10073 return;
10074
10075 auto TypeArgs = TargetObjCPtr->getTypeArgs();
10076 if (TypeArgs.size() != 2)
10077 return;
10078
10079 QualType TargetKeyType = TypeArgs[0];
10080 QualType TargetObjectType = TypeArgs[1];
10081 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
10082 auto Element = DictionaryLiteral->getKeyValueElement(I);
10083 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
10084 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
10085 }
10086}
10087
Richard Trieufc404c72016-02-05 23:02:38 +000010088// Helper function to filter out cases for constant width constant conversion.
10089// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010090static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
10091 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +000010092 // If initializing from a constant, and the constant starts with '0',
10093 // then it is a binary, octal, or hexadecimal. Allow these constants
10094 // to fill all the bits, even if there is a sign change.
10095 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
10096 const char FirstLiteralCharacter =
10097 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
10098 if (FirstLiteralCharacter == '0')
10099 return false;
10100 }
10101
10102 // If the CC location points to a '{', and the type is char, then assume
10103 // assume it is an array initialization.
10104 if (CC.isValid() && T->isCharType()) {
10105 const char FirstContextCharacter =
10106 S.getSourceManager().getCharacterData(CC)[0];
10107 if (FirstContextCharacter == '{')
10108 return false;
10109 }
10110
10111 return true;
10112}
10113
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010114static void
10115CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
10116 bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010117 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +000010118
John McCallcc7e5bf2010-05-06 08:58:33 +000010119 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
10120 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
10121 if (Source == Target) return;
10122 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +000010123
Chandler Carruthc22845a2011-07-26 05:40:03 +000010124 // If the conversion context location is invalid don't complain. We also
10125 // don't want to emit a warning if the issue occurs from the expansion of
10126 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
10127 // delay this check as long as possible. Once we detect we are in that
10128 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010129 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +000010130 return;
10131
Richard Trieu021baa32011-09-23 20:10:00 +000010132 // Diagnose implicit casts to bool.
10133 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
10134 if (isa<StringLiteral>(E))
10135 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +000010136 // and expressions, for instance, assert(0 && "error here"), are
10137 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +000010138 return DiagnoseImpCast(S, E, T, CC,
10139 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +000010140 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
10141 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
10142 // This covers the literal expressions that evaluate to Objective-C
10143 // objects.
10144 return DiagnoseImpCast(S, E, T, CC,
10145 diag::warn_impcast_objective_c_literal_to_bool);
10146 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010147 if (Source->isPointerType() || Source->canDecayToPointerType()) {
10148 // Warn on pointer to bool conversion that is always true.
10149 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
10150 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +000010151 }
Richard Trieu021baa32011-09-23 20:10:00 +000010152 }
John McCall263a48b2010-01-04 23:31:57 +000010153
Douglas Gregor5054cb02015-07-07 03:58:22 +000010154 // Check implicit casts from Objective-C collection literals to specialized
10155 // collection types, e.g., NSArray<NSString *> *.
10156 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
10157 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
10158 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
10159 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
10160
John McCall263a48b2010-01-04 23:31:57 +000010161 // Strip vector types.
10162 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010163 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010164 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010165 return;
John McCallacf0ee52010-10-08 02:01:28 +000010166 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010167 }
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010168
Chris Lattneree7286f2011-06-14 04:51:15 +000010169 // If the vector cast is cast between two vectors of the same size, it is
10170 // a bitcast, not a conversion.
10171 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
10172 return;
John McCall263a48b2010-01-04 23:31:57 +000010173
10174 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
10175 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
10176 }
Stephen Canon3ba640d2014-04-03 10:33:25 +000010177 if (auto VecTy = dyn_cast<VectorType>(Target))
10178 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +000010179
10180 // Strip complex types.
10181 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010182 if (!isa<ComplexType>(Target)) {
Tim Northover02416372017-08-08 23:18:05 +000010183 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010184 return;
10185
Tim Northover02416372017-08-08 23:18:05 +000010186 return DiagnoseImpCast(S, E, T, CC,
10187 S.getLangOpts().CPlusPlus
10188 ? diag::err_impcast_complex_scalar
10189 : diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010190 }
John McCall263a48b2010-01-04 23:31:57 +000010191
10192 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
10193 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
10194 }
10195
10196 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
10197 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
10198
10199 // If the source is floating point...
10200 if (SourceBT && SourceBT->isFloatingPoint()) {
10201 // ...and the target is floating point...
10202 if (TargetBT && TargetBT->isFloatingPoint()) {
10203 // ...then warn if we're dropping FP rank.
10204
10205 // Builtin FP kinds are ordered by increasing FP rank.
10206 if (SourceBT->getKind() > TargetBT->getKind()) {
10207 // Don't warn about float constants that are precisely
10208 // representable in the target type.
10209 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +000010210 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +000010211 // Value might be a float, a float vector, or a float complex.
10212 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +000010213 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
10214 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +000010215 return;
10216 }
10217
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010218 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010219 return;
10220
John McCallacf0ee52010-10-08 02:01:28 +000010221 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +000010222 }
10223 // ... or possibly if we're increasing rank, too
10224 else if (TargetBT->getKind() > SourceBT->getKind()) {
10225 if (S.SourceMgr.isInSystemMacro(CC))
10226 return;
10227
10228 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +000010229 }
10230 return;
10231 }
10232
Richard Trieube234c32016-04-21 21:04:55 +000010233 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +000010234 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010235 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010236 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +000010237
Richard Trieube234c32016-04-21 21:04:55 +000010238 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +000010239 }
John McCall263a48b2010-01-04 23:31:57 +000010240
Richard Smith54894fd2015-12-30 01:06:52 +000010241 // Detect the case where a call result is converted from floating-point to
10242 // to bool, and the final argument to the call is converted from bool, to
10243 // discover this typo:
10244 //
10245 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
10246 //
10247 // FIXME: This is an incredibly special case; is there some more general
10248 // way to detect this class of misplaced-parentheses bug?
10249 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010250 // Check last argument of function call to see if it is an
10251 // implicit cast from a type matching the type the result
10252 // is being cast to.
10253 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +000010254 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010255 Expr *LastA = CEx->getArg(NumArgs - 1);
10256 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +000010257 if (isa<ImplicitCastExpr>(LastA) &&
10258 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010259 // Warn on this floating-point to bool conversion
10260 DiagnoseImpCast(S, E, T, CC,
10261 diag::warn_impcast_floating_point_to_bool);
10262 }
10263 }
10264 }
John McCall263a48b2010-01-04 23:31:57 +000010265 return;
10266 }
10267
Richard Trieu5b993502014-10-15 03:42:06 +000010268 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +000010269
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010270 S.DiscardMisalignedMemberAddress(Target, E);
10271
David Blaikie9366d2b2012-06-19 21:19:06 +000010272 if (!Source->isIntegerType() || !Target->isIntegerType())
10273 return;
10274
David Blaikie7555b6a2012-05-15 16:56:36 +000010275 // TODO: remove this early return once the false positives for constant->bool
10276 // in templates, macros, etc, are reduced or removed.
10277 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
10278 return;
10279
John McCallcc7e5bf2010-05-06 08:58:33 +000010280 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +000010281 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +000010282
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010283 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +000010284 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010285 // TODO: this should happen for bitfield stores, too.
10286 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +000010287 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010288 if (S.SourceMgr.isInSystemMacro(CC))
10289 return;
10290
John McCall18a2c2c2010-11-09 22:22:12 +000010291 std::string PrettySourceValue = Value.toString(10);
10292 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010293
Ted Kremenek33ba9952011-10-22 02:37:33 +000010294 S.DiagRuntimeBehavior(E->getExprLoc(), E,
10295 S.PDiag(diag::warn_impcast_integer_precision_constant)
10296 << PrettySourceValue << PrettyTargetValue
10297 << E->getType() << T << E->getSourceRange()
10298 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +000010299 return;
10300 }
10301
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010302 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
10303 if (S.SourceMgr.isInSystemMacro(CC))
10304 return;
10305
David Blaikie9455da02012-04-12 22:40:54 +000010306 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +000010307 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
10308 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +000010309 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +000010310 }
10311
Richard Trieudcb55572016-01-29 23:51:16 +000010312 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
10313 SourceRange.NonNegative && Source->isSignedIntegerType()) {
10314 // Warn when doing a signed to signed conversion, warn if the positive
10315 // source value is exactly the width of the target type, which will
10316 // cause a negative value to be stored.
10317
10318 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +000010319 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
10320 !S.SourceMgr.isInSystemMacro(CC)) {
10321 if (isSameWidthConstantConversion(S, E, T, CC)) {
10322 std::string PrettySourceValue = Value.toString(10);
10323 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +000010324
Richard Trieufc404c72016-02-05 23:02:38 +000010325 S.DiagRuntimeBehavior(
10326 E->getExprLoc(), E,
10327 S.PDiag(diag::warn_impcast_integer_precision_constant)
10328 << PrettySourceValue << PrettyTargetValue << E->getType() << T
10329 << E->getSourceRange() << clang::SourceRange(CC));
10330 return;
Richard Trieudcb55572016-01-29 23:51:16 +000010331 }
10332 }
Richard Trieufc404c72016-02-05 23:02:38 +000010333
Richard Trieudcb55572016-01-29 23:51:16 +000010334 // Fall through for non-constants to give a sign conversion warning.
10335 }
10336
John McCallcc7e5bf2010-05-06 08:58:33 +000010337 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
10338 (!TargetRange.NonNegative && SourceRange.NonNegative &&
10339 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010340 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010341 return;
10342
John McCallcc7e5bf2010-05-06 08:58:33 +000010343 unsigned DiagID = diag::warn_impcast_integer_sign;
10344
10345 // Traditionally, gcc has warned about this under -Wsign-compare.
10346 // We also want to warn about it in -Wconversion.
10347 // So if -Wconversion is off, use a completely identical diagnostic
10348 // in the sign-compare group.
10349 // The conditional-checking code will
10350 if (ICContext) {
10351 DiagID = diag::warn_impcast_integer_sign_conditional;
10352 *ICContext = true;
10353 }
10354
John McCallacf0ee52010-10-08 02:01:28 +000010355 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +000010356 }
10357
Douglas Gregora78f1932011-02-22 02:45:07 +000010358 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +000010359 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
10360 // type, to give us better diagnostics.
10361 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000010362 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +000010363 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10364 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
10365 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
10366 SourceType = S.Context.getTypeDeclType(Enum);
10367 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
10368 }
10369 }
10370
Douglas Gregora78f1932011-02-22 02:45:07 +000010371 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
10372 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +000010373 if (SourceEnum->getDecl()->hasNameForLinkage() &&
10374 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010375 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010376 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010377 return;
10378
Douglas Gregor364f7db2011-03-12 00:14:31 +000010379 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +000010380 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010381 }
John McCall263a48b2010-01-04 23:31:57 +000010382}
10383
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010384static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10385 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010386
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010387static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
10388 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010389 E = E->IgnoreParenImpCasts();
10390
10391 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +000010392 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010393
John McCallacf0ee52010-10-08 02:01:28 +000010394 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010395 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000010396 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +000010397}
10398
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010399static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10400 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +000010401 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +000010402
10403 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +000010404 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
10405 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000010406
10407 // If -Wconversion would have warned about either of the candidates
10408 // for a signedness conversion to the context type...
10409 if (!Suspicious) return;
10410
10411 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010412 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +000010413 return;
10414
John McCallcc7e5bf2010-05-06 08:58:33 +000010415 // ...then check whether it would have warned about either of the
10416 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +000010417 if (E->getType() == T) return;
10418
10419 Suspicious = false;
10420 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
10421 E->getType(), CC, &Suspicious);
10422 if (!Suspicious)
10423 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +000010424 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000010425}
10426
Richard Trieu65724892014-11-15 06:37:39 +000010427/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10428/// Input argument E is a logical expression.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010429static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +000010430 if (S.getLangOpts().Bool)
10431 return;
10432 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
10433}
10434
John McCallcc7e5bf2010-05-06 08:58:33 +000010435/// AnalyzeImplicitConversions - Find and report any interesting
10436/// implicit conversions in the given expression. There are a couple
10437/// of competing diagnostics here, -Wconversion and -Wsign-compare.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010438static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
10439 SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +000010440 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +000010441 Expr *E = OrigE->IgnoreParenImpCasts();
10442
Douglas Gregor6e8da6a2011-10-10 17:38:18 +000010443 if (E->isTypeDependent() || E->isValueDependent())
10444 return;
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010445
John McCallcc7e5bf2010-05-06 08:58:33 +000010446 // For conditional operators, we analyze the arguments as if they
10447 // were being fed directly into the output.
10448 if (isa<ConditionalOperator>(E)) {
10449 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +000010450 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010451 return;
10452 }
10453
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010454 // Check implicit argument conversions for function calls.
10455 if (CallExpr *Call = dyn_cast<CallExpr>(E))
10456 CheckImplicitArgumentConversions(S, Call, CC);
10457
John McCallcc7e5bf2010-05-06 08:58:33 +000010458 // Go ahead and check any implicit conversions we might have skipped.
10459 // The non-canonical typecheck is just an optimization;
10460 // CheckImplicitConversion will filter out dead implicit conversions.
10461 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000010462 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010463
10464 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +000010465
10466 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
10467 // The bound subexpressions in a PseudoObjectExpr are not reachable
10468 // as transitive children.
10469 // FIXME: Use a more uniform representation for this.
10470 for (auto *SE : POE->semantics())
10471 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
10472 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +000010473 }
Richard Smithd7bed4d2015-11-22 02:57:17 +000010474
John McCallcc7e5bf2010-05-06 08:58:33 +000010475 // Skip past explicit casts.
10476 if (isa<ExplicitCastExpr>(E)) {
10477 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +000010478 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010479 }
10480
John McCalld2a53122010-11-09 23:24:47 +000010481 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10482 // Do a somewhat different check with comparison operators.
10483 if (BO->isComparisonOp())
10484 return AnalyzeComparison(S, BO);
10485
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010486 // And with simple assignments.
10487 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +000010488 return AnalyzeAssignment(S, BO);
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010489 // And with compound assignments.
10490 if (BO->isAssignmentOp())
10491 return AnalyzeCompoundAssignment(S, BO);
John McCalld2a53122010-11-09 23:24:47 +000010492 }
John McCallcc7e5bf2010-05-06 08:58:33 +000010493
10494 // These break the otherwise-useful invariant below. Fortunately,
10495 // we don't really need to recurse into them, because any internal
10496 // expressions should have been analyzed already when they were
10497 // built into statements.
10498 if (isa<StmtExpr>(E)) return;
10499
10500 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +000010501 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +000010502
10503 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +000010504 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +000010505 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +000010506 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +000010507 for (Stmt *SubStmt : E->children()) {
10508 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +000010509 if (!ChildExpr)
10510 continue;
10511
Richard Trieu955231d2014-01-25 01:10:35 +000010512 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +000010513 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +000010514 // Ignore checking string literals that are in logical and operators.
10515 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +000010516 continue;
10517 AnalyzeImplicitConversions(S, ChildExpr, CC);
10518 }
Richard Trieu791b86e2014-11-19 06:08:18 +000010519
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010520 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +000010521 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
10522 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000010523 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +000010524
10525 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
10526 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000010527 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010528 }
Richard Trieu791b86e2014-11-19 06:08:18 +000010529
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010530 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
10531 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +000010532 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010533}
10534
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000010535/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000010536static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
10537 // Taking into account implicit conversions,
10538 // allow any integer.
10539 if (!E->getType()->isIntegerType()) {
10540 S.Diag(E->getLocStart(),
10541 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
10542 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010543 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000010544 // Potentially emit standard warnings for implicit conversions if enabled
10545 // using -Wconversion.
10546 CheckImplicitConversion(S, E, IntT, E->getLocStart());
10547 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010548}
10549
Richard Trieuc1888e02014-06-28 23:25:37 +000010550// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
10551// Returns true when emitting a warning about taking the address of a reference.
10552static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +000010553 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +000010554 E = E->IgnoreParenImpCasts();
10555
10556 const FunctionDecl *FD = nullptr;
10557
10558 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10559 if (!DRE->getDecl()->getType()->isReferenceType())
10560 return false;
10561 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10562 if (!M->getMemberDecl()->getType()->isReferenceType())
10563 return false;
10564 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +000010565 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +000010566 return false;
10567 FD = Call->getDirectCallee();
10568 } else {
10569 return false;
10570 }
10571
10572 SemaRef.Diag(E->getExprLoc(), PD);
10573
10574 // If possible, point to location of function.
10575 if (FD) {
10576 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
10577 }
10578
10579 return true;
10580}
10581
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010582// Returns true if the SourceLocation is expanded from any macro body.
10583// Returns false if the SourceLocation is invalid, is from not in a macro
10584// expansion, or is from expanded from a top-level macro argument.
10585static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
10586 if (Loc.isInvalid())
10587 return false;
10588
10589 while (Loc.isMacroID()) {
10590 if (SM.isMacroBodyExpansion(Loc))
10591 return true;
10592 Loc = SM.getImmediateMacroCallerLoc(Loc);
10593 }
10594
10595 return false;
10596}
10597
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010598/// Diagnose pointers that are always non-null.
Richard Trieu3bb8b562014-02-26 02:36:06 +000010599/// \param E the expression containing the pointer
10600/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
10601/// compared to a null pointer
10602/// \param IsEqual True when the comparison is equal to a null pointer
10603/// \param Range Extra SourceRange to highlight in the diagnostic
10604void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
10605 Expr::NullPointerConstantKind NullKind,
10606 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +000010607 if (!E)
10608 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010609
10610 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010611 if (E->getExprLoc().isMacroID()) {
10612 const SourceManager &SM = getSourceManager();
10613 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
10614 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +000010615 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010616 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010617 E = E->IgnoreImpCasts();
10618
10619 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10620
Richard Trieuf7432752014-06-06 21:39:26 +000010621 if (isa<CXXThisExpr>(E)) {
10622 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10623 : diag::warn_this_bool_conversion;
10624 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10625 return;
10626 }
10627
Richard Trieu3bb8b562014-02-26 02:36:06 +000010628 bool IsAddressOf = false;
10629
10630 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10631 if (UO->getOpcode() != UO_AddrOf)
10632 return;
10633 IsAddressOf = true;
10634 E = UO->getSubExpr();
10635 }
10636
Richard Trieuc1888e02014-06-28 23:25:37 +000010637 if (IsAddressOf) {
10638 unsigned DiagID = IsCompare
10639 ? diag::warn_address_of_reference_null_compare
10640 : diag::warn_address_of_reference_bool_conversion;
10641 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10642 << IsEqual;
10643 if (CheckForReference(*this, E, PD)) {
10644 return;
10645 }
10646 }
10647
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010648 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10649 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +000010650 std::string Str;
10651 llvm::raw_string_ostream S(Str);
10652 E->printPretty(S, nullptr, getPrintingPolicy());
10653 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10654 : diag::warn_cast_nonnull_to_bool;
10655 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10656 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010657 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +000010658 };
10659
10660 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10661 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10662 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010663 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10664 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010665 return;
10666 }
10667 }
10668 }
10669
Richard Trieu3bb8b562014-02-26 02:36:06 +000010670 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +000010671 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010672 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10673 D = R->getDecl();
10674 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10675 D = M->getMemberDecl();
10676 }
10677
10678 // Weak Decls can be null.
10679 if (!D || D->isWeak())
10680 return;
George Burgess IV850269a2015-12-08 22:02:00 +000010681
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010682 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +000010683 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10684 if (getCurFunction() &&
10685 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010686 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10687 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010688 return;
10689 }
10690
10691 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +000010692 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +000010693 assert(ParamIter != FD->param_end());
10694 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10695
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010696 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10697 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010698 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +000010699 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010700 }
George Burgess IV850269a2015-12-08 22:02:00 +000010701
Joel E. Denny81508102018-03-13 14:51:22 +000010702 for (const ParamIdx &ArgNo : NonNull->args()) {
10703 if (ArgNo.getASTIndex() == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010704 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010705 return;
10706 }
George Burgess IV850269a2015-12-08 22:02:00 +000010707 }
10708 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010709 }
10710 }
George Burgess IV850269a2015-12-08 22:02:00 +000010711 }
10712
Richard Trieu3bb8b562014-02-26 02:36:06 +000010713 QualType T = D->getType();
10714 const bool IsArray = T->isArrayType();
10715 const bool IsFunction = T->isFunctionType();
10716
Richard Trieuc1888e02014-06-28 23:25:37 +000010717 // Address of function is used to silence the function warning.
10718 if (IsAddressOf && IsFunction) {
10719 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010720 }
10721
10722 // Found nothing.
10723 if (!IsAddressOf && !IsFunction && !IsArray)
10724 return;
10725
10726 // Pretty print the expression for the diagnostic.
10727 std::string Str;
10728 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +000010729 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +000010730
10731 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10732 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +000010733 enum {
10734 AddressOf,
10735 FunctionPointer,
10736 ArrayPointer
10737 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010738 if (IsAddressOf)
10739 DiagType = AddressOf;
10740 else if (IsFunction)
10741 DiagType = FunctionPointer;
10742 else if (IsArray)
10743 DiagType = ArrayPointer;
10744 else
10745 llvm_unreachable("Could not determine diagnostic.");
10746 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10747 << Range << IsEqual;
10748
10749 if (!IsFunction)
10750 return;
10751
10752 // Suggest '&' to silence the function warning.
10753 Diag(E->getExprLoc(), diag::note_function_warning_silence)
10754 << FixItHint::CreateInsertion(E->getLocStart(), "&");
10755
10756 // Check to see if '()' fixit should be emitted.
10757 QualType ReturnType;
10758 UnresolvedSet<4> NonTemplateOverloads;
10759 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10760 if (ReturnType.isNull())
10761 return;
10762
10763 if (IsCompare) {
10764 // There are two cases here. If there is null constant, the only suggest
10765 // for a pointer return type. If the null is 0, then suggest if the return
10766 // type is a pointer or an integer type.
10767 if (!ReturnType->isPointerType()) {
10768 if (NullKind == Expr::NPCK_ZeroExpression ||
10769 NullKind == Expr::NPCK_ZeroLiteral) {
10770 if (!ReturnType->isIntegerType())
10771 return;
10772 } else {
10773 return;
10774 }
10775 }
10776 } else { // !IsCompare
10777 // For function to bool, only suggest if the function pointer has bool
10778 // return type.
10779 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10780 return;
10781 }
10782 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +000010783 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +000010784}
10785
John McCallcc7e5bf2010-05-06 08:58:33 +000010786/// Diagnoses "dangerous" implicit conversions within the given
10787/// expression (which is a full expression). Implements -Wconversion
10788/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +000010789///
10790/// \param CC the "context" location of the implicit conversion, i.e.
10791/// the most location of the syntactic entity requiring the implicit
10792/// conversion
10793void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010794 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +000010795 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +000010796 return;
10797
10798 // Don't diagnose for value- or type-dependent expressions.
10799 if (E->isTypeDependent() || E->isValueDependent())
10800 return;
10801
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010802 // Check for array bounds violations in cases where the check isn't triggered
10803 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10804 // ArraySubscriptExpr is on the RHS of a variable initialization.
10805 CheckArrayAccess(E);
10806
John McCallacf0ee52010-10-08 02:01:28 +000010807 // This is not the right CC for (e.g.) a variable initialization.
10808 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010809}
10810
Richard Trieu65724892014-11-15 06:37:39 +000010811/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10812/// Input argument E is a logical expression.
10813void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10814 ::CheckBoolLikeConversion(*this, E, CC);
10815}
10816
Richard Smith9f7df0c2017-06-26 23:19:32 +000010817/// Diagnose when expression is an integer constant expression and its evaluation
10818/// results in integer overflow
10819void Sema::CheckForIntOverflow (Expr *E) {
10820 // Use a work list to deal with nested struct initializers.
10821 SmallVector<Expr *, 2> Exprs(1, E);
10822
10823 do {
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010824 Expr *OriginalE = Exprs.pop_back_val();
10825 Expr *E = OriginalE->IgnoreParenCasts();
Richard Smith9f7df0c2017-06-26 23:19:32 +000010826
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010827 if (isa<BinaryOperator>(E)) {
10828 E->EvaluateForOverflow(Context);
Richard Smith9f7df0c2017-06-26 23:19:32 +000010829 continue;
10830 }
10831
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010832 if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
Richard Smith9f7df0c2017-06-26 23:19:32 +000010833 Exprs.append(InitList->inits().begin(), InitList->inits().end());
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010834 else if (isa<ObjCBoxedExpr>(OriginalE))
10835 E->EvaluateForOverflow(Context);
10836 else if (auto Call = dyn_cast<CallExpr>(E))
10837 Exprs.append(Call->arg_begin(), Call->arg_end());
10838 else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
10839 Exprs.append(Message->arg_begin(), Message->arg_end());
Richard Smith9f7df0c2017-06-26 23:19:32 +000010840 } while (!Exprs.empty());
10841}
10842
Richard Smithc406cb72013-01-17 01:17:56 +000010843namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010844
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010845/// Visitor for expressions which looks for unsequenced operations on the
Richard Smithc406cb72013-01-17 01:17:56 +000010846/// same object.
10847class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010848 using Base = EvaluatedExprVisitor<SequenceChecker>;
Richard Smithe3dbfe02013-06-30 10:40:20 +000010849
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010850 /// A tree of sequenced regions within an expression. Two regions are
Richard Smithc406cb72013-01-17 01:17:56 +000010851 /// unsequenced if one is an ancestor or a descendent of the other. When we
10852 /// finish processing an expression with sequencing, such as a comma
10853 /// expression, we fold its tree nodes into its parent, since they are
10854 /// unsequenced with respect to nodes we will visit later.
10855 class SequenceTree {
10856 struct Value {
10857 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10858 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +000010859 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +000010860 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010861 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +000010862
10863 public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010864 /// A region within an expression which may be sequenced with respect
Richard Smithc406cb72013-01-17 01:17:56 +000010865 /// to some other region.
10866 class Seq {
Richard Smithc406cb72013-01-17 01:17:56 +000010867 friend class SequenceTree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010868
10869 unsigned Index = 0;
10870
10871 explicit Seq(unsigned N) : Index(N) {}
10872
Richard Smithc406cb72013-01-17 01:17:56 +000010873 public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010874 Seq() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010875 };
10876
10877 SequenceTree() { Values.push_back(Value(0)); }
10878 Seq root() const { return Seq(0); }
10879
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010880 /// Create a new sequence of operations, which is an unsequenced
Richard Smithc406cb72013-01-17 01:17:56 +000010881 /// subset of \p Parent. This sequence of operations is sequenced with
10882 /// respect to other children of \p Parent.
10883 Seq allocate(Seq Parent) {
10884 Values.push_back(Value(Parent.Index));
10885 return Seq(Values.size() - 1);
10886 }
10887
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010888 /// Merge a sequence of operations into its parent.
Richard Smithc406cb72013-01-17 01:17:56 +000010889 void merge(Seq S) {
10890 Values[S.Index].Merged = true;
10891 }
10892
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010893 /// Determine whether two operations are unsequenced. This operation
Richard Smithc406cb72013-01-17 01:17:56 +000010894 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10895 /// should have been merged into its parent as appropriate.
10896 bool isUnsequenced(Seq Cur, Seq Old) {
10897 unsigned C = representative(Cur.Index);
10898 unsigned Target = representative(Old.Index);
10899 while (C >= Target) {
10900 if (C == Target)
10901 return true;
10902 C = Values[C].Parent;
10903 }
10904 return false;
10905 }
10906
10907 private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010908 /// Pick a representative for a sequence.
Richard Smithc406cb72013-01-17 01:17:56 +000010909 unsigned representative(unsigned K) {
10910 if (Values[K].Merged)
10911 // Perform path compression as we go.
10912 return Values[K].Parent = representative(Values[K].Parent);
10913 return K;
10914 }
10915 };
10916
10917 /// An object for which we can track unsequenced uses.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010918 using Object = NamedDecl *;
Richard Smithc406cb72013-01-17 01:17:56 +000010919
10920 /// Different flavors of object usage which we track. We only track the
10921 /// least-sequenced usage of each kind.
10922 enum UsageKind {
10923 /// A read of an object. Multiple unsequenced reads are OK.
10924 UK_Use,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010925
Richard Smithc406cb72013-01-17 01:17:56 +000010926 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000010927 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000010928 UK_ModAsValue,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010929
Richard Smithc406cb72013-01-17 01:17:56 +000010930 /// A modification of an object which is not sequenced before the value
10931 /// computation of the expression, such as n++.
10932 UK_ModAsSideEffect,
10933
10934 UK_Count = UK_ModAsSideEffect + 1
10935 };
10936
10937 struct Usage {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010938 Expr *Use = nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010939 SequenceTree::Seq Seq;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010940
10941 Usage() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010942 };
10943
10944 struct UsageInfo {
Richard Smithc406cb72013-01-17 01:17:56 +000010945 Usage Uses[UK_Count];
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010946
Richard Smithc406cb72013-01-17 01:17:56 +000010947 /// Have we issued a diagnostic for this variable already?
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010948 bool Diagnosed = false;
10949
10950 UsageInfo() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010951 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010952 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
Richard Smithc406cb72013-01-17 01:17:56 +000010953
10954 Sema &SemaRef;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010955
Richard Smithc406cb72013-01-17 01:17:56 +000010956 /// Sequenced regions within the expression.
10957 SequenceTree Tree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010958
Richard Smithc406cb72013-01-17 01:17:56 +000010959 /// Declaration modifications and references which we have seen.
10960 UsageInfoMap UsageMap;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010961
Richard Smithc406cb72013-01-17 01:17:56 +000010962 /// The region we are currently within.
10963 SequenceTree::Seq Region;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010964
Richard Smithc406cb72013-01-17 01:17:56 +000010965 /// Filled in with declarations which were modified as a side-effect
10966 /// (that is, post-increment operations).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010967 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
10968
Richard Smithd33f5202013-01-17 23:18:09 +000010969 /// Expressions to check later. We defer checking these to reduce
10970 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010971 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000010972
10973 /// RAII object wrapping the visitation of a sequenced subexpression of an
10974 /// expression. At the end of this process, the side-effects of the evaluation
10975 /// become sequenced with respect to the value computation of the result, so
10976 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10977 /// UK_ModAsValue.
10978 struct SequencedSubexpression {
10979 SequencedSubexpression(SequenceChecker &Self)
10980 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10981 Self.ModAsSideEffect = &ModAsSideEffect;
10982 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010983
Richard Smithc406cb72013-01-17 01:17:56 +000010984 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000010985 for (auto &M : llvm::reverse(ModAsSideEffect)) {
10986 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000010987 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000010988 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10989 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000010990 }
10991 Self.ModAsSideEffect = OldModAsSideEffect;
10992 }
10993
10994 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010995 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010996 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000010997 };
10998
Richard Smith40238f02013-06-20 22:21:56 +000010999 /// RAII object wrapping the visitation of a subexpression which we might
11000 /// choose to evaluate as a constant. If any subexpression is evaluated and
11001 /// found to be non-constant, this allows us to suppress the evaluation of
11002 /// the outer expression.
11003 class EvaluationTracker {
11004 public:
11005 EvaluationTracker(SequenceChecker &Self)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011006 : Self(Self), Prev(Self.EvalTracker) {
Richard Smith40238f02013-06-20 22:21:56 +000011007 Self.EvalTracker = this;
11008 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011009
Richard Smith40238f02013-06-20 22:21:56 +000011010 ~EvaluationTracker() {
11011 Self.EvalTracker = Prev;
11012 if (Prev)
11013 Prev->EvalOK &= EvalOK;
11014 }
11015
11016 bool evaluate(const Expr *E, bool &Result) {
11017 if (!EvalOK || E->isValueDependent())
11018 return false;
11019 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
11020 return EvalOK;
11021 }
11022
11023 private:
11024 SequenceChecker &Self;
11025 EvaluationTracker *Prev;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011026 bool EvalOK = true;
11027 } *EvalTracker = nullptr;
Richard Smith40238f02013-06-20 22:21:56 +000011028
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011029 /// Find the object which is produced by the specified expression,
Richard Smithc406cb72013-01-17 01:17:56 +000011030 /// if any.
11031 Object getObject(Expr *E, bool Mod) const {
11032 E = E->IgnoreParenCasts();
11033 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11034 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
11035 return getObject(UO->getSubExpr(), Mod);
11036 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11037 if (BO->getOpcode() == BO_Comma)
11038 return getObject(BO->getRHS(), Mod);
11039 if (Mod && BO->isAssignmentOp())
11040 return getObject(BO->getLHS(), Mod);
11041 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11042 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
11043 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
11044 return ME->getMemberDecl();
11045 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11046 // FIXME: If this is a reference, map through to its value.
11047 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000011048 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000011049 }
11050
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011051 /// Note that an object was modified or used by an expression.
Richard Smithc406cb72013-01-17 01:17:56 +000011052 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
11053 Usage &U = UI.Uses[UK];
11054 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
11055 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
11056 ModAsSideEffect->push_back(std::make_pair(O, U));
11057 U.Use = Ref;
11058 U.Seq = Region;
11059 }
11060 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011061
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011062 /// Check whether a modification or use conflicts with a prior usage.
Richard Smithc406cb72013-01-17 01:17:56 +000011063 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
11064 bool IsModMod) {
11065 if (UI.Diagnosed)
11066 return;
11067
11068 const Usage &U = UI.Uses[OtherKind];
11069 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
11070 return;
11071
11072 Expr *Mod = U.Use;
11073 Expr *ModOrUse = Ref;
11074 if (OtherKind == UK_Use)
11075 std::swap(Mod, ModOrUse);
11076
11077 SemaRef.Diag(Mod->getExprLoc(),
11078 IsModMod ? diag::warn_unsequenced_mod_mod
11079 : diag::warn_unsequenced_mod_use)
11080 << O << SourceRange(ModOrUse->getExprLoc());
11081 UI.Diagnosed = true;
11082 }
11083
11084 void notePreUse(Object O, Expr *Use) {
11085 UsageInfo &U = UsageMap[O];
11086 // Uses conflict with other modifications.
11087 checkUsage(O, U, Use, UK_ModAsValue, false);
11088 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011089
Richard Smithc406cb72013-01-17 01:17:56 +000011090 void notePostUse(Object O, Expr *Use) {
11091 UsageInfo &U = UsageMap[O];
11092 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
11093 addUsage(U, O, Use, UK_Use);
11094 }
11095
11096 void notePreMod(Object O, Expr *Mod) {
11097 UsageInfo &U = UsageMap[O];
11098 // Modifications conflict with other modifications and with uses.
11099 checkUsage(O, U, Mod, UK_ModAsValue, true);
11100 checkUsage(O, U, Mod, UK_Use, false);
11101 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011102
Richard Smithc406cb72013-01-17 01:17:56 +000011103 void notePostMod(Object O, Expr *Use, UsageKind UK) {
11104 UsageInfo &U = UsageMap[O];
11105 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
11106 addUsage(U, O, Use, UK);
11107 }
11108
11109public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011110 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011111 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
Richard Smithc406cb72013-01-17 01:17:56 +000011112 Visit(E);
11113 }
11114
11115 void VisitStmt(Stmt *S) {
11116 // Skip all statements which aren't expressions for now.
11117 }
11118
11119 void VisitExpr(Expr *E) {
11120 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000011121 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000011122 }
11123
11124 void VisitCastExpr(CastExpr *E) {
11125 Object O = Object();
11126 if (E->getCastKind() == CK_LValueToRValue)
11127 O = getObject(E->getSubExpr(), false);
11128
11129 if (O)
11130 notePreUse(O, E);
11131 VisitExpr(E);
11132 if (O)
11133 notePostUse(O, E);
11134 }
11135
11136 void VisitBinComma(BinaryOperator *BO) {
11137 // C++11 [expr.comma]p1:
11138 // Every value computation and side effect associated with the left
11139 // expression is sequenced before every value computation and side
11140 // effect associated with the right expression.
11141 SequenceTree::Seq LHS = Tree.allocate(Region);
11142 SequenceTree::Seq RHS = Tree.allocate(Region);
11143 SequenceTree::Seq OldRegion = Region;
11144
11145 {
11146 SequencedSubexpression SeqLHS(*this);
11147 Region = LHS;
11148 Visit(BO->getLHS());
11149 }
11150
11151 Region = RHS;
11152 Visit(BO->getRHS());
11153
11154 Region = OldRegion;
11155
11156 // Forget that LHS and RHS are sequenced. They are both unsequenced
11157 // with respect to other stuff.
11158 Tree.merge(LHS);
11159 Tree.merge(RHS);
11160 }
11161
11162 void VisitBinAssign(BinaryOperator *BO) {
11163 // The modification is sequenced after the value computation of the LHS
11164 // and RHS, so check it before inspecting the operands and update the
11165 // map afterwards.
11166 Object O = getObject(BO->getLHS(), true);
11167 if (!O)
11168 return VisitExpr(BO);
11169
11170 notePreMod(O, BO);
11171
11172 // C++11 [expr.ass]p7:
11173 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
11174 // only once.
11175 //
11176 // Therefore, for a compound assignment operator, O is considered used
11177 // everywhere except within the evaluation of E1 itself.
11178 if (isa<CompoundAssignOperator>(BO))
11179 notePreUse(O, BO);
11180
11181 Visit(BO->getLHS());
11182
11183 if (isa<CompoundAssignOperator>(BO))
11184 notePostUse(O, BO);
11185
11186 Visit(BO->getRHS());
11187
Richard Smith83e37bee2013-06-26 23:16:51 +000011188 // C++11 [expr.ass]p1:
11189 // the assignment is sequenced [...] before the value computation of the
11190 // assignment expression.
11191 // C11 6.5.16/3 has no such rule.
11192 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11193 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000011194 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011195
Richard Smithc406cb72013-01-17 01:17:56 +000011196 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
11197 VisitBinAssign(CAO);
11198 }
11199
11200 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11201 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11202 void VisitUnaryPreIncDec(UnaryOperator *UO) {
11203 Object O = getObject(UO->getSubExpr(), true);
11204 if (!O)
11205 return VisitExpr(UO);
11206
11207 notePreMod(O, UO);
11208 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000011209 // C++11 [expr.pre.incr]p1:
11210 // the expression ++x is equivalent to x+=1
11211 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11212 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000011213 }
11214
11215 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11216 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11217 void VisitUnaryPostIncDec(UnaryOperator *UO) {
11218 Object O = getObject(UO->getSubExpr(), true);
11219 if (!O)
11220 return VisitExpr(UO);
11221
11222 notePreMod(O, UO);
11223 Visit(UO->getSubExpr());
11224 notePostMod(O, UO, UK_ModAsSideEffect);
11225 }
11226
11227 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
11228 void VisitBinLOr(BinaryOperator *BO) {
11229 // The side-effects of the LHS of an '&&' are sequenced before the
11230 // value computation of the RHS, and hence before the value computation
11231 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
11232 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000011233 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000011234 {
11235 SequencedSubexpression Sequenced(*this);
11236 Visit(BO->getLHS());
11237 }
11238
11239 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011240 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000011241 if (!Result)
11242 Visit(BO->getRHS());
11243 } else {
11244 // Check for unsequenced operations in the RHS, treating it as an
11245 // entirely separate evaluation.
11246 //
11247 // FIXME: If there are operations in the RHS which are unsequenced
11248 // with respect to operations outside the RHS, and those operations
11249 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000011250 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000011251 }
Richard Smithc406cb72013-01-17 01:17:56 +000011252 }
11253 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000011254 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000011255 {
11256 SequencedSubexpression Sequenced(*this);
11257 Visit(BO->getLHS());
11258 }
11259
11260 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011261 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000011262 if (Result)
11263 Visit(BO->getRHS());
11264 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000011265 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000011266 }
Richard Smithc406cb72013-01-17 01:17:56 +000011267 }
11268
11269 // Only visit the condition, unless we can be sure which subexpression will
11270 // be chosen.
11271 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000011272 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000011273 {
11274 SequencedSubexpression Sequenced(*this);
11275 Visit(CO->getCond());
11276 }
Richard Smithc406cb72013-01-17 01:17:56 +000011277
11278 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011279 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000011280 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000011281 else {
Richard Smithd33f5202013-01-17 23:18:09 +000011282 WorkList.push_back(CO->getTrueExpr());
11283 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000011284 }
Richard Smithc406cb72013-01-17 01:17:56 +000011285 }
11286
Richard Smithe3dbfe02013-06-30 10:40:20 +000011287 void VisitCallExpr(CallExpr *CE) {
11288 // C++11 [intro.execution]p15:
11289 // When calling a function [...], every value computation and side effect
11290 // associated with any argument expression, or with the postfix expression
11291 // designating the called function, is sequenced before execution of every
11292 // expression or statement in the body of the function [and thus before
11293 // the value computation of its result].
11294 SequencedSubexpression Sequenced(*this);
11295 Base::VisitCallExpr(CE);
11296
11297 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
11298 }
11299
Richard Smithc406cb72013-01-17 01:17:56 +000011300 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000011301 // This is a call, so all subexpressions are sequenced before the result.
11302 SequencedSubexpression Sequenced(*this);
11303
Richard Smithc406cb72013-01-17 01:17:56 +000011304 if (!CCE->isListInitialization())
11305 return VisitExpr(CCE);
11306
11307 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011308 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000011309 SequenceTree::Seq Parent = Region;
11310 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
11311 E = CCE->arg_end();
11312 I != E; ++I) {
11313 Region = Tree.allocate(Parent);
11314 Elts.push_back(Region);
11315 Visit(*I);
11316 }
11317
11318 // Forget that the initializers are sequenced.
11319 Region = Parent;
11320 for (unsigned I = 0; I < Elts.size(); ++I)
11321 Tree.merge(Elts[I]);
11322 }
11323
11324 void VisitInitListExpr(InitListExpr *ILE) {
11325 if (!SemaRef.getLangOpts().CPlusPlus11)
11326 return VisitExpr(ILE);
11327
11328 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011329 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000011330 SequenceTree::Seq Parent = Region;
11331 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
11332 Expr *E = ILE->getInit(I);
11333 if (!E) continue;
11334 Region = Tree.allocate(Parent);
11335 Elts.push_back(Region);
11336 Visit(E);
11337 }
11338
11339 // Forget that the initializers are sequenced.
11340 Region = Parent;
11341 for (unsigned I = 0; I < Elts.size(); ++I)
11342 Tree.merge(Elts[I]);
11343 }
11344};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011345
11346} // namespace
Richard Smithc406cb72013-01-17 01:17:56 +000011347
11348void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011349 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000011350 WorkList.push_back(E);
11351 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000011352 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000011353 SequenceChecker(*this, Item, WorkList);
11354 }
Richard Smithc406cb72013-01-17 01:17:56 +000011355}
11356
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011357void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
11358 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000011359 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000011360 if (!E->isInstantiationDependent())
11361 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011362 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000011363 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011364 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000011365}
11366
John McCall1f425642010-11-11 03:21:53 +000011367void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
11368 FieldDecl *BitField,
11369 Expr *Init) {
11370 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
11371}
11372
David Majnemer61a5bbf2015-04-07 22:08:51 +000011373static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
11374 SourceLocation Loc) {
11375 if (!PType->isVariablyModifiedType())
11376 return;
11377 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
11378 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
11379 return;
11380 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000011381 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
11382 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
11383 return;
11384 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000011385 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
11386 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
11387 return;
11388 }
11389
11390 const ArrayType *AT = S.Context.getAsArrayType(PType);
11391 if (!AT)
11392 return;
11393
11394 if (AT->getSizeModifier() != ArrayType::Star) {
11395 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
11396 return;
11397 }
11398
11399 S.Diag(Loc, diag::err_array_star_in_function_definition);
11400}
11401
Mike Stump0c2ec772010-01-21 03:59:47 +000011402/// CheckParmsForFunctionDef - Check that the parameters of the given
11403/// function are appropriate for the definition of a function. This
11404/// takes care of any checks that cannot be performed on the
11405/// declaration itself, e.g., that the types of each of the function
11406/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000011407bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000011408 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011409 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000011410 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011411 // C99 6.7.5.3p4: the parameters in a parameter type list in a
11412 // function declarator that is part of a function definition of
11413 // that function shall not have incomplete type.
11414 //
11415 // This is also C++ [dcl.fct]p6.
11416 if (!Param->isInvalidDecl() &&
11417 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011418 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011419 Param->setInvalidDecl();
11420 HasInvalidParm = true;
11421 }
11422
11423 // C99 6.9.1p5: If the declarator includes a parameter type list, the
11424 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000011425 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000011426 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000011427 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000011428 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000011429 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000011430
11431 // C99 6.7.5.3p12:
11432 // If the function declarator is not part of a definition of that
11433 // function, parameters may have incomplete type and may use the [*]
11434 // notation in their sequences of declarator specifiers to specify
11435 // variable length array types.
11436 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000011437 // FIXME: This diagnostic should point the '[*]' if source-location
11438 // information is added for it.
11439 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000011440
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011441 // If the parameter is a c++ class type and it has to be destructed in the
11442 // callee function, declare the destructor so that it can be called by the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000011443 // callee function. Do not perform any direct access check on the dtor here.
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011444 if (!Param->isInvalidDecl()) {
11445 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
11446 if (!ClassDecl->isInvalidDecl() &&
11447 !ClassDecl->hasIrrelevantDestructor() &&
11448 !ClassDecl->isDependentContext() &&
Akira Hatanaka85282972018-05-15 21:00:30 +000011449 ClassDecl->isParamDestroyedInCallee()) {
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011450 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11451 MarkFunctionReferenced(Param->getLocation(), Destructor);
11452 DiagnoseUseOfDecl(Destructor, Param->getLocation());
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000011453 }
11454 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000011455 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011456
11457 // Parameters with the pass_object_size attribute only need to be marked
11458 // constant at function definitions. Because we lack information about
11459 // whether we're on a declaration or definition when we're instantiating the
11460 // attribute, we need to check for constness here.
11461 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
11462 if (!Param->getType().isConstQualified())
11463 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
11464 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000011465 }
11466
11467 return HasInvalidParm;
11468}
John McCall2b5c1b22010-08-12 21:44:57 +000011469
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000011470/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
11471/// or MemberExpr.
11472static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
11473 ASTContext &Context) {
11474 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
11475 return Context.getDeclAlign(DRE->getDecl());
11476
11477 if (const auto *ME = dyn_cast<MemberExpr>(E))
11478 return Context.getDeclAlign(ME->getMemberDecl());
11479
11480 return TypeAlign;
11481}
11482
John McCall2b5c1b22010-08-12 21:44:57 +000011483/// CheckCastAlign - Implements -Wcast-align, which warns when a
11484/// pointer cast increases the alignment requirements.
11485void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
11486 // This is actually a lot of work to potentially be doing on every
11487 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011488 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000011489 return;
11490
11491 // Ignore dependent types.
11492 if (T->isDependentType() || Op->getType()->isDependentType())
11493 return;
11494
11495 // Require that the destination be a pointer type.
11496 const PointerType *DestPtr = T->getAs<PointerType>();
11497 if (!DestPtr) return;
11498
11499 // If the destination has alignment 1, we're done.
11500 QualType DestPointee = DestPtr->getPointeeType();
11501 if (DestPointee->isIncompleteType()) return;
11502 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
11503 if (DestAlign.isOne()) return;
11504
11505 // Require that the source be a pointer type.
11506 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
11507 if (!SrcPtr) return;
11508 QualType SrcPointee = SrcPtr->getPointeeType();
11509
11510 // Whitelist casts from cv void*. We already implicitly
11511 // whitelisted casts to cv void*, since they have alignment 1.
11512 // Also whitelist casts involving incomplete types, which implicitly
11513 // includes 'void'.
11514 if (SrcPointee->isIncompleteType()) return;
11515
11516 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000011517
11518 if (auto *CE = dyn_cast<CastExpr>(Op)) {
11519 if (CE->getCastKind() == CK_ArrayToPointerDecay)
11520 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
11521 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
11522 if (UO->getOpcode() == UO_AddrOf)
11523 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
11524 }
11525
John McCall2b5c1b22010-08-12 21:44:57 +000011526 if (SrcAlign >= DestAlign) return;
11527
11528 Diag(TRange.getBegin(), diag::warn_cast_align)
11529 << Op->getType() << T
11530 << static_cast<unsigned>(SrcAlign.getQuantity())
11531 << static_cast<unsigned>(DestAlign.getQuantity())
11532 << TRange << Op->getSourceRange();
11533}
11534
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011535/// Check whether this array fits the idiom of a size-one tail padded
Chandler Carruth28389f02011-08-05 09:10:50 +000011536/// array member of a struct.
11537///
11538/// We avoid emitting out-of-bounds access warnings for such arrays as they are
11539/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000011540static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000011541 const NamedDecl *ND) {
11542 if (Size != 1 || !ND) return false;
11543
11544 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
11545 if (!FD) return false;
11546
11547 // Don't consider sizes resulting from macro expansions or template argument
11548 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000011549
11550 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011551 while (TInfo) {
11552 TypeLoc TL = TInfo->getTypeLoc();
11553 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000011554 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
11555 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011556 TInfo = TDL->getTypeSourceInfo();
11557 continue;
11558 }
David Blaikie6adc78e2013-02-18 22:06:02 +000011559 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
11560 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000011561 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
11562 return false;
11563 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011564 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000011565 }
Chandler Carruth28389f02011-08-05 09:10:50 +000011566
11567 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000011568 if (!RD) return false;
11569 if (RD->isUnion()) return false;
11570 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11571 if (!CRD->isStandardLayout()) return false;
11572 }
Chandler Carruth28389f02011-08-05 09:10:50 +000011573
Benjamin Kramer8c543672011-08-06 03:04:42 +000011574 // See if this is the last field decl in the record.
11575 const Decl *D = FD;
11576 while ((D = D->getNextDeclInContext()))
11577 if (isa<FieldDecl>(D))
11578 return false;
11579 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000011580}
11581
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011582void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011583 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000011584 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011585 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011586 if (IndexExpr->isValueDependent())
11587 return;
11588
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011589 const Type *EffectiveType =
11590 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011591 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011592 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011593 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011594 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000011595 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000011596
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011597 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000011598 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000011599 return;
Richard Smith13f67182011-12-16 19:31:14 +000011600 if (IndexNegated)
11601 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000011602
Craig Topperc3ec1492014-05-26 06:22:03 +000011603 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000011604 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011605 ND = DRE->getDecl();
Chandler Carruth28389f02011-08-05 09:10:50 +000011606 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011607 ND = ME->getMemberDecl();
Chandler Carruth126b1552011-08-05 08:07:29 +000011608
Ted Kremeneke4b316c2011-02-23 23:06:04 +000011609 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011610 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000011611 if (!size.isStrictlyPositive())
11612 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011613
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011614 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000011615 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011616 // Make sure we're comparing apples to apples when comparing index to size
11617 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
11618 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000011619 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000011620 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011621 if (ptrarith_typesize != array_typesize) {
11622 // There's a cast to a different size type involved
11623 uint64_t ratio = array_typesize / ptrarith_typesize;
11624 // TODO: Be smarter about handling cases where array_typesize is not a
11625 // multiple of ptrarith_typesize
11626 if (ptrarith_typesize * ratio == array_typesize)
11627 size *= llvm::APInt(size.getBitWidth(), ratio);
11628 }
11629 }
11630
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011631 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011632 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011633 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011634 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011635
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011636 // For array subscripting the index must be less than size, but for pointer
11637 // arithmetic also allow the index (offset) to be equal to size since
11638 // computing the next address after the end of the array is legal and
11639 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011640 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000011641 return;
11642
11643 // Also don't warn for arrays of size 1 which are members of some
11644 // structure. These are often used to approximate flexible arrays in C89
11645 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011646 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000011647 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011648
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011649 // Suppress the warning if the subscript expression (as identified by the
11650 // ']' location) and the index expression are both from macro expansions
11651 // within a system header.
11652 if (ASE) {
11653 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11654 ASE->getRBracketLoc());
11655 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11656 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11657 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000011658 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011659 return;
11660 }
11661 }
11662
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011663 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011664 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011665 DiagID = diag::warn_array_index_exceeds_bounds;
11666
11667 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11668 PDiag(DiagID) << index.toString(10, true)
11669 << size.toString(10, true)
11670 << (unsigned)size.getLimitedValue(~0U)
11671 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011672 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011673 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011674 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011675 DiagID = diag::warn_ptr_arith_precedes_bounds;
11676 if (index.isNegative()) index = -index;
11677 }
11678
11679 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11680 PDiag(DiagID) << index.toString(10, true)
11681 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000011682 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000011683
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011684 if (!ND) {
11685 // Try harder to find a NamedDecl to point at in the note.
11686 while (const ArraySubscriptExpr *ASE =
11687 dyn_cast<ArraySubscriptExpr>(BaseExpr))
11688 BaseExpr = ASE->getBase()->IgnoreParenCasts();
11689 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011690 ND = DRE->getDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011691 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011692 ND = ME->getMemberDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011693 }
11694
Chandler Carruth1af88f12011-02-17 21:10:52 +000011695 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011696 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11697 PDiag(diag::note_array_index_out_of_bounds)
11698 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000011699}
11700
Ted Kremenekdf26df72011-03-01 18:41:00 +000011701void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011702 int AllowOnePastEnd = 0;
11703 while (expr) {
11704 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000011705 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011706 case Stmt::ArraySubscriptExprClass: {
11707 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011708 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011709 AllowOnePastEnd > 0);
Aaron Ballman93c6ba12018-04-24 19:21:04 +000011710 expr = ASE->getBase();
11711 break;
11712 }
11713 case Stmt::MemberExprClass: {
11714 expr = cast<MemberExpr>(expr)->getBase();
11715 break;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011716 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000011717 case Stmt::OMPArraySectionExprClass: {
11718 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11719 if (ASE->getLowerBound())
11720 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11721 /*ASE=*/nullptr, AllowOnePastEnd > 0);
11722 return;
11723 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011724 case Stmt::UnaryOperatorClass: {
11725 // Only unwrap the * and & unary operators
11726 const UnaryOperator *UO = cast<UnaryOperator>(expr);
11727 expr = UO->getSubExpr();
11728 switch (UO->getOpcode()) {
11729 case UO_AddrOf:
11730 AllowOnePastEnd++;
11731 break;
11732 case UO_Deref:
11733 AllowOnePastEnd--;
11734 break;
11735 default:
11736 return;
11737 }
11738 break;
11739 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011740 case Stmt::ConditionalOperatorClass: {
11741 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11742 if (const Expr *lhs = cond->getLHS())
11743 CheckArrayAccess(lhs);
11744 if (const Expr *rhs = cond->getRHS())
11745 CheckArrayAccess(rhs);
11746 return;
11747 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000011748 case Stmt::CXXOperatorCallExprClass: {
11749 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11750 for (const auto *Arg : OCE->arguments())
11751 CheckArrayAccess(Arg);
11752 return;
11753 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011754 default:
11755 return;
11756 }
Peter Collingbourne91147592011-04-15 00:35:48 +000011757 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011758}
John McCall31168b02011-06-15 23:02:42 +000011759
11760//===--- CHECK: Objective-C retain cycles ----------------------------------//
11761
11762namespace {
John McCall31168b02011-06-15 23:02:42 +000011763
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011764struct RetainCycleOwner {
11765 VarDecl *Variable = nullptr;
11766 SourceRange Range;
11767 SourceLocation Loc;
11768 bool Indirect = false;
11769
11770 RetainCycleOwner() = default;
11771
11772 void setLocsFrom(Expr *e) {
11773 Loc = e->getExprLoc();
11774 Range = e->getSourceRange();
11775 }
11776};
11777
11778} // namespace
John McCall31168b02011-06-15 23:02:42 +000011779
11780/// Consider whether capturing the given variable can possibly lead to
11781/// a retain cycle.
11782static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000011783 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000011784 // lifetime. In MRR, it's captured strongly if the variable is
11785 // __block and has an appropriate type.
11786 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11787 return false;
11788
11789 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011790 if (ref)
11791 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000011792 return true;
11793}
11794
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011795static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000011796 while (true) {
11797 e = e->IgnoreParens();
11798 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11799 switch (cast->getCastKind()) {
11800 case CK_BitCast:
11801 case CK_LValueBitCast:
11802 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000011803 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000011804 e = cast->getSubExpr();
11805 continue;
11806
John McCall31168b02011-06-15 23:02:42 +000011807 default:
11808 return false;
11809 }
11810 }
11811
11812 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11813 ObjCIvarDecl *ivar = ref->getDecl();
11814 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11815 return false;
11816
11817 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011818 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000011819 return false;
11820
11821 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11822 owner.Indirect = true;
11823 return true;
11824 }
11825
11826 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11827 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11828 if (!var) return false;
11829 return considerVariable(var, ref, owner);
11830 }
11831
John McCall31168b02011-06-15 23:02:42 +000011832 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11833 if (member->isArrow()) return false;
11834
11835 // Don't count this as an indirect ownership.
11836 e = member->getBase();
11837 continue;
11838 }
11839
John McCallfe96e0b2011-11-06 09:01:30 +000011840 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11841 // Only pay attention to pseudo-objects on property references.
11842 ObjCPropertyRefExpr *pre
11843 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11844 ->IgnoreParens());
11845 if (!pre) return false;
11846 if (pre->isImplicitProperty()) return false;
11847 ObjCPropertyDecl *property = pre->getExplicitProperty();
11848 if (!property->isRetaining() &&
11849 !(property->getPropertyIvarDecl() &&
11850 property->getPropertyIvarDecl()->getType()
11851 .getObjCLifetime() == Qualifiers::OCL_Strong))
11852 return false;
11853
11854 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011855 if (pre->isSuperReceiver()) {
11856 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11857 if (!owner.Variable)
11858 return false;
11859 owner.Loc = pre->getLocation();
11860 owner.Range = pre->getSourceRange();
11861 return true;
11862 }
John McCallfe96e0b2011-11-06 09:01:30 +000011863 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11864 ->getSourceExpr());
11865 continue;
11866 }
11867
John McCall31168b02011-06-15 23:02:42 +000011868 // Array ivars?
11869
11870 return false;
11871 }
11872}
11873
11874namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011875
John McCall31168b02011-06-15 23:02:42 +000011876 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011877 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000011878 VarDecl *Variable;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011879 Expr *Capturer = nullptr;
11880 bool VarWillBeReased = false;
11881
11882 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11883 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11884 Context(Context), Variable(variable) {}
John McCall31168b02011-06-15 23:02:42 +000011885
11886 void VisitDeclRefExpr(DeclRefExpr *ref) {
11887 if (ref->getDecl() == Variable && !Capturer)
11888 Capturer = ref;
11889 }
11890
John McCall31168b02011-06-15 23:02:42 +000011891 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11892 if (Capturer) return;
11893 Visit(ref->getBase());
11894 if (Capturer && ref->isFreeIvar())
11895 Capturer = ref;
11896 }
11897
11898 void VisitBlockExpr(BlockExpr *block) {
11899 // Look inside nested blocks
11900 if (block->getBlockDecl()->capturesVariable(Variable))
11901 Visit(block->getBlockDecl()->getBody());
11902 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000011903
11904 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11905 if (Capturer) return;
11906 if (OVE->getSourceExpr())
11907 Visit(OVE->getSourceExpr());
11908 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011909
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011910 void VisitBinaryOperator(BinaryOperator *BinOp) {
11911 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11912 return;
11913 Expr *LHS = BinOp->getLHS();
11914 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11915 if (DRE->getDecl() != Variable)
11916 return;
11917 if (Expr *RHS = BinOp->getRHS()) {
11918 RHS = RHS->IgnoreParenCasts();
11919 llvm::APSInt Value;
11920 VarWillBeReased =
11921 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11922 }
11923 }
11924 }
John McCall31168b02011-06-15 23:02:42 +000011925 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011926
11927} // namespace
John McCall31168b02011-06-15 23:02:42 +000011928
11929/// Check whether the given argument is a block which captures a
11930/// variable.
11931static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11932 assert(owner.Variable && owner.Loc.isValid());
11933
11934 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000011935
11936 // Look through [^{...} copy] and Block_copy(^{...}).
11937 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11938 Selector Cmd = ME->getSelector();
11939 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11940 e = ME->getInstanceReceiver();
11941 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000011942 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000011943 e = e->IgnoreParenCasts();
11944 }
11945 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11946 if (CE->getNumArgs() == 1) {
11947 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000011948 if (Fn) {
11949 const IdentifierInfo *FnI = Fn->getIdentifier();
11950 if (FnI && FnI->isStr("_Block_copy")) {
11951 e = CE->getArg(0)->IgnoreParenCasts();
11952 }
11953 }
Jordan Rose67e887c2012-09-17 17:54:30 +000011954 }
11955 }
11956
John McCall31168b02011-06-15 23:02:42 +000011957 BlockExpr *block = dyn_cast<BlockExpr>(e);
11958 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000011959 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011960
11961 FindCaptureVisitor visitor(S.Context, owner.Variable);
11962 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011963 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000011964}
11965
11966static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11967 RetainCycleOwner &owner) {
11968 assert(capturer);
11969 assert(owner.Variable && owner.Loc.isValid());
11970
11971 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11972 << owner.Variable << capturer->getSourceRange();
11973 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11974 << owner.Indirect << owner.Range;
11975}
11976
11977/// Check for a keyword selector that starts with the word 'add' or
11978/// 'set'.
11979static bool isSetterLikeSelector(Selector sel) {
11980 if (sel.isUnarySelector()) return false;
11981
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011982 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000011983 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011984 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000011985 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011986 else if (str.startswith("add")) {
11987 // Specially whitelist 'addOperationWithBlock:'.
11988 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11989 return false;
11990 str = str.substr(3);
11991 }
John McCall31168b02011-06-15 23:02:42 +000011992 else
11993 return false;
11994
11995 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000011996 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000011997}
11998
Benjamin Kramer3a743452015-03-09 15:03:32 +000011999static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
12000 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012001 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
12002 Message->getReceiverInterface(),
12003 NSAPI::ClassId_NSMutableArray);
12004 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012005 return None;
12006 }
12007
12008 Selector Sel = Message->getSelector();
12009
12010 Optional<NSAPI::NSArrayMethodKind> MKOpt =
12011 S.NSAPIObj->getNSArrayMethodKind(Sel);
12012 if (!MKOpt) {
12013 return None;
12014 }
12015
12016 NSAPI::NSArrayMethodKind MK = *MKOpt;
12017
12018 switch (MK) {
12019 case NSAPI::NSMutableArr_addObject:
12020 case NSAPI::NSMutableArr_insertObjectAtIndex:
12021 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
12022 return 0;
12023 case NSAPI::NSMutableArr_replaceObjectAtIndex:
12024 return 1;
12025
12026 default:
12027 return None;
12028 }
12029
12030 return None;
12031}
12032
12033static
12034Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
12035 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012036 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
12037 Message->getReceiverInterface(),
12038 NSAPI::ClassId_NSMutableDictionary);
12039 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012040 return None;
12041 }
12042
12043 Selector Sel = Message->getSelector();
12044
12045 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
12046 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
12047 if (!MKOpt) {
12048 return None;
12049 }
12050
12051 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
12052
12053 switch (MK) {
12054 case NSAPI::NSMutableDict_setObjectForKey:
12055 case NSAPI::NSMutableDict_setValueForKey:
12056 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
12057 return 0;
12058
12059 default:
12060 return None;
12061 }
12062
12063 return None;
12064}
12065
12066static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012067 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
12068 Message->getReceiverInterface(),
12069 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000012070
Alex Denisov5dfac812015-08-06 04:51:14 +000012071 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
12072 Message->getReceiverInterface(),
12073 NSAPI::ClassId_NSMutableOrderedSet);
12074 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012075 return None;
12076 }
12077
12078 Selector Sel = Message->getSelector();
12079
12080 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
12081 if (!MKOpt) {
12082 return None;
12083 }
12084
12085 NSAPI::NSSetMethodKind MK = *MKOpt;
12086
12087 switch (MK) {
12088 case NSAPI::NSMutableSet_addObject:
12089 case NSAPI::NSOrderedSet_setObjectAtIndex:
12090 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
12091 case NSAPI::NSOrderedSet_insertObjectAtIndex:
12092 return 0;
12093 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
12094 return 1;
12095 }
12096
12097 return None;
12098}
12099
12100void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
12101 if (!Message->isInstanceMessage()) {
12102 return;
12103 }
12104
12105 Optional<int> ArgOpt;
12106
12107 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
12108 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
12109 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
12110 return;
12111 }
12112
12113 int ArgIndex = *ArgOpt;
12114
Alex Denisove1d882c2015-03-04 17:55:52 +000012115 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
12116 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
12117 Arg = OE->getSourceExpr()->IgnoreImpCasts();
12118 }
12119
Alex Denisov5dfac812015-08-06 04:51:14 +000012120 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012121 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012122 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012123 Diag(Message->getSourceRange().getBegin(),
12124 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012125 << ArgRE->getDecl() << StringRef("'super'");
Alex Denisove1d882c2015-03-04 17:55:52 +000012126 }
12127 }
Alex Denisov5dfac812015-08-06 04:51:14 +000012128 } else {
12129 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
12130
12131 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
12132 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
12133 }
12134
12135 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
12136 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
12137 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
12138 ValueDecl *Decl = ReceiverRE->getDecl();
12139 Diag(Message->getSourceRange().getBegin(),
12140 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012141 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012142 if (!ArgRE->isObjCSelfExpr()) {
12143 Diag(Decl->getLocation(),
12144 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000012145 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012146 }
12147 }
12148 }
12149 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
12150 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
12151 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
12152 ObjCIvarDecl *Decl = IvarRE->getDecl();
12153 Diag(Message->getSourceRange().getBegin(),
12154 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012155 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012156 Diag(Decl->getLocation(),
12157 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000012158 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012159 }
Alex Denisove1d882c2015-03-04 17:55:52 +000012160 }
12161 }
12162 }
Alex Denisove1d882c2015-03-04 17:55:52 +000012163}
12164
John McCall31168b02011-06-15 23:02:42 +000012165/// Check a message send to see if it's likely to cause a retain cycle.
12166void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
12167 // Only check instance methods whose selector looks like a setter.
12168 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
12169 return;
12170
12171 // Try to find a variable that the receiver is strongly owned by.
12172 RetainCycleOwner owner;
12173 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012174 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000012175 return;
12176 } else {
12177 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
12178 owner.Variable = getCurMethodDecl()->getSelfDecl();
12179 owner.Loc = msg->getSuperLoc();
12180 owner.Range = msg->getSuperLoc();
12181 }
12182
12183 // Check whether the receiver is captured by any of the arguments.
Alex Lorenz42a97a92017-11-17 20:44:25 +000012184 const ObjCMethodDecl *MD = msg->getMethodDecl();
12185 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
12186 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
12187 // noescape blocks should not be retained by the method.
12188 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
12189 continue;
John McCall31168b02011-06-15 23:02:42 +000012190 return diagnoseRetainCycle(*this, capturer, owner);
Alex Lorenz42a97a92017-11-17 20:44:25 +000012191 }
12192 }
John McCall31168b02011-06-15 23:02:42 +000012193}
12194
12195/// Check a property assign to see if it's likely to cause a retain cycle.
12196void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
12197 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012198 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000012199 return;
12200
12201 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
12202 diagnoseRetainCycle(*this, capturer, owner);
12203}
12204
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012205void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
12206 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000012207 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012208 return;
12209
12210 // Because we don't have an expression for the variable, we have to set the
12211 // location explicitly here.
12212 Owner.Loc = Var->getLocation();
12213 Owner.Range = Var->getSourceRange();
12214
12215 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
12216 diagnoseRetainCycle(*this, Capturer, Owner);
12217}
12218
Ted Kremenek9304da92012-12-21 08:04:28 +000012219static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
12220 Expr *RHS, bool isProperty) {
12221 // Check if RHS is an Objective-C object literal, which also can get
12222 // immediately zapped in a weak reference. Note that we explicitly
12223 // allow ObjCStringLiterals, since those are designed to never really die.
12224 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012225
Ted Kremenek64873352012-12-21 22:46:35 +000012226 // This enum needs to match with the 'select' in
12227 // warn_objc_arc_literal_assign (off-by-1).
12228 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
12229 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
12230 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012231
12232 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000012233 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000012234 << (isProperty ? 0 : 1)
12235 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012236
12237 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000012238}
12239
Ted Kremenekc1f014a2012-12-21 19:45:30 +000012240static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
12241 Qualifiers::ObjCLifetime LT,
12242 Expr *RHS, bool isProperty) {
12243 // Strip off any implicit cast added to get to the one ARC-specific.
12244 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
12245 if (cast->getCastKind() == CK_ARCConsumeObject) {
12246 S.Diag(Loc, diag::warn_arc_retained_assign)
12247 << (LT == Qualifiers::OCL_ExplicitNone)
12248 << (isProperty ? 0 : 1)
12249 << RHS->getSourceRange();
12250 return true;
12251 }
12252 RHS = cast->getSubExpr();
12253 }
12254
12255 if (LT == Qualifiers::OCL_Weak &&
12256 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
12257 return true;
12258
12259 return false;
12260}
12261
Ted Kremenekb36234d2012-12-21 08:04:20 +000012262bool Sema::checkUnsafeAssigns(SourceLocation Loc,
12263 QualType LHS, Expr *RHS) {
12264 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
12265
12266 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
12267 return false;
12268
12269 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
12270 return true;
12271
12272 return false;
12273}
12274
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012275void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
12276 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012277 QualType LHSType;
12278 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000012279 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012280 ObjCPropertyRefExpr *PRE
12281 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
12282 if (PRE && !PRE->isImplicitProperty()) {
12283 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12284 if (PD)
12285 LHSType = PD->getType();
12286 }
12287
12288 if (LHSType.isNull())
12289 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000012290
12291 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
12292
12293 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012294 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000012295 getCurFunction()->markSafeWeakUse(LHS);
12296 }
12297
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012298 if (checkUnsafeAssigns(Loc, LHSType, RHS))
12299 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000012300
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012301 // FIXME. Check for other life times.
12302 if (LT != Qualifiers::OCL_None)
12303 return;
12304
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012305 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012306 if (PRE->isImplicitProperty())
12307 return;
12308 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12309 if (!PD)
12310 return;
12311
Bill Wendling44426052012-12-20 19:22:21 +000012312 unsigned Attributes = PD->getPropertyAttributes();
12313 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012314 // when 'assign' attribute was not explicitly specified
12315 // by user, ignore it and rely on property type itself
12316 // for lifetime info.
12317 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
12318 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
12319 LHSType->isObjCRetainableType())
12320 return;
12321
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012322 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000012323 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012324 Diag(Loc, diag::warn_arc_retained_property_assign)
12325 << RHS->getSourceRange();
12326 return;
12327 }
12328 RHS = cast->getSubExpr();
12329 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012330 }
Bill Wendling44426052012-12-20 19:22:21 +000012331 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000012332 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
12333 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000012334 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012335 }
12336}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012337
12338//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
12339
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012340static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
12341 SourceLocation StmtLoc,
12342 const NullStmt *Body) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012343 // Do not warn if the body is a macro that expands to nothing, e.g:
12344 //
12345 // #define CALL(x)
12346 // if (condition)
12347 // CALL(0);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012348 if (Body->hasLeadingEmptyMacro())
12349 return false;
12350
12351 // Get line numbers of statement and body.
12352 bool StmtLineInvalid;
Hans Wennborg95419752017-11-20 17:38:16 +000012353 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012354 &StmtLineInvalid);
12355 if (StmtLineInvalid)
12356 return false;
12357
12358 bool BodyLineInvalid;
12359 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
12360 &BodyLineInvalid);
12361 if (BodyLineInvalid)
12362 return false;
12363
12364 // Warn if null statement and body are on the same line.
12365 if (StmtLine != BodyLine)
12366 return false;
12367
12368 return true;
12369}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012370
12371void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
12372 const Stmt *Body,
12373 unsigned DiagID) {
12374 // Since this is a syntactic check, don't emit diagnostic for template
12375 // instantiations, this just adds noise.
12376 if (CurrentInstantiationScope)
12377 return;
12378
12379 // The body should be a null statement.
12380 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
12381 if (!NBody)
12382 return;
12383
12384 // Do the usual checks.
12385 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12386 return;
12387
12388 Diag(NBody->getSemiLoc(), DiagID);
12389 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12390}
12391
12392void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
12393 const Stmt *PossibleBody) {
12394 assert(!CurrentInstantiationScope); // Ensured by caller
12395
12396 SourceLocation StmtLoc;
12397 const Stmt *Body;
12398 unsigned DiagID;
12399 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
12400 StmtLoc = FS->getRParenLoc();
12401 Body = FS->getBody();
12402 DiagID = diag::warn_empty_for_body;
12403 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
12404 StmtLoc = WS->getCond()->getSourceRange().getEnd();
12405 Body = WS->getBody();
12406 DiagID = diag::warn_empty_while_body;
12407 } else
12408 return; // Neither `for' nor `while'.
12409
12410 // The body should be a null statement.
12411 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
12412 if (!NBody)
12413 return;
12414
12415 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012416 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012417 return;
12418
12419 // Do the usual checks.
12420 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12421 return;
12422
12423 // `for(...);' and `while(...);' are popular idioms, so in order to keep
12424 // noise level low, emit diagnostics only if for/while is followed by a
12425 // CompoundStmt, e.g.:
12426 // for (int i = 0; i < n; i++);
12427 // {
12428 // a(i);
12429 // }
12430 // or if for/while is followed by a statement with more indentation
12431 // than for/while itself:
12432 // for (int i = 0; i < n; i++);
12433 // a(i);
12434 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
12435 if (!ProbableTypo) {
12436 bool BodyColInvalid;
12437 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
12438 PossibleBody->getLocStart(),
12439 &BodyColInvalid);
12440 if (BodyColInvalid)
12441 return;
12442
12443 bool StmtColInvalid;
12444 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
12445 S->getLocStart(),
12446 &StmtColInvalid);
12447 if (StmtColInvalid)
12448 return;
12449
12450 if (BodyCol > StmtCol)
12451 ProbableTypo = true;
12452 }
12453
12454 if (ProbableTypo) {
12455 Diag(NBody->getSemiLoc(), DiagID);
12456 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12457 }
12458}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012459
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012460//===--- CHECK: Warn on self move with std::move. -------------------------===//
12461
12462/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
12463void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
12464 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012465 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
12466 return;
12467
Richard Smith51ec0cf2017-02-21 01:17:38 +000012468 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012469 return;
12470
12471 // Strip parens and casts away.
12472 LHSExpr = LHSExpr->IgnoreParenImpCasts();
12473 RHSExpr = RHSExpr->IgnoreParenImpCasts();
12474
12475 // Check for a call expression
12476 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
12477 if (!CE || CE->getNumArgs() != 1)
12478 return;
12479
12480 // Check for a call to std::move
Nico Weberb688d132017-09-28 16:16:39 +000012481 if (!CE->isCallToStdMove())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012482 return;
12483
12484 // Get argument from std::move
12485 RHSExpr = CE->getArg(0);
12486
12487 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12488 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12489
12490 // Two DeclRefExpr's, check that the decls are the same.
12491 if (LHSDeclRef && RHSDeclRef) {
12492 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12493 return;
12494 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12495 RHSDeclRef->getDecl()->getCanonicalDecl())
12496 return;
12497
12498 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12499 << LHSExpr->getSourceRange()
12500 << RHSExpr->getSourceRange();
12501 return;
12502 }
12503
12504 // Member variables require a different approach to check for self moves.
12505 // MemberExpr's are the same if every nested MemberExpr refers to the same
12506 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
12507 // the base Expr's are CXXThisExpr's.
12508 const Expr *LHSBase = LHSExpr;
12509 const Expr *RHSBase = RHSExpr;
12510 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
12511 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
12512 if (!LHSME || !RHSME)
12513 return;
12514
12515 while (LHSME && RHSME) {
12516 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
12517 RHSME->getMemberDecl()->getCanonicalDecl())
12518 return;
12519
12520 LHSBase = LHSME->getBase();
12521 RHSBase = RHSME->getBase();
12522 LHSME = dyn_cast<MemberExpr>(LHSBase);
12523 RHSME = dyn_cast<MemberExpr>(RHSBase);
12524 }
12525
12526 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
12527 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
12528 if (LHSDeclRef && RHSDeclRef) {
12529 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12530 return;
12531 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12532 RHSDeclRef->getDecl()->getCanonicalDecl())
12533 return;
12534
12535 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12536 << LHSExpr->getSourceRange()
12537 << RHSExpr->getSourceRange();
12538 return;
12539 }
12540
12541 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
12542 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12543 << LHSExpr->getSourceRange()
12544 << RHSExpr->getSourceRange();
12545}
12546
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012547//===--- Layout compatibility ----------------------------------------------//
12548
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012549static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012550
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012551/// Check if two enumeration types are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012552static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012553 // C++11 [dcl.enum] p8:
12554 // Two enumeration types are layout-compatible if they have the same
12555 // underlying type.
12556 return ED1->isComplete() && ED2->isComplete() &&
12557 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
12558}
12559
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012560/// Check if two fields are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012561static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
12562 FieldDecl *Field2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012563 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
12564 return false;
12565
12566 if (Field1->isBitField() != Field2->isBitField())
12567 return false;
12568
12569 if (Field1->isBitField()) {
12570 // Make sure that the bit-fields are the same length.
12571 unsigned Bits1 = Field1->getBitWidthValue(C);
12572 unsigned Bits2 = Field2->getBitWidthValue(C);
12573
12574 if (Bits1 != Bits2)
12575 return false;
12576 }
12577
12578 return true;
12579}
12580
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012581/// Check if two standard-layout structs are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012582/// (C++11 [class.mem] p17)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012583static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
12584 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012585 // If both records are C++ classes, check that base classes match.
12586 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
12587 // If one of records is a CXXRecordDecl we are in C++ mode,
12588 // thus the other one is a CXXRecordDecl, too.
12589 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
12590 // Check number of base classes.
12591 if (D1CXX->getNumBases() != D2CXX->getNumBases())
12592 return false;
12593
12594 // Check the base classes.
12595 for (CXXRecordDecl::base_class_const_iterator
12596 Base1 = D1CXX->bases_begin(),
12597 BaseEnd1 = D1CXX->bases_end(),
12598 Base2 = D2CXX->bases_begin();
12599 Base1 != BaseEnd1;
12600 ++Base1, ++Base2) {
12601 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
12602 return false;
12603 }
12604 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
12605 // If only RD2 is a C++ class, it should have zero base classes.
12606 if (D2CXX->getNumBases() > 0)
12607 return false;
12608 }
12609
12610 // Check the fields.
12611 RecordDecl::field_iterator Field2 = RD2->field_begin(),
12612 Field2End = RD2->field_end(),
12613 Field1 = RD1->field_begin(),
12614 Field1End = RD1->field_end();
12615 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
12616 if (!isLayoutCompatible(C, *Field1, *Field2))
12617 return false;
12618 }
12619 if (Field1 != Field1End || Field2 != Field2End)
12620 return false;
12621
12622 return true;
12623}
12624
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012625/// Check if two standard-layout unions are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012626/// (C++11 [class.mem] p18)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012627static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
12628 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012629 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012630 for (auto *Field2 : RD2->fields())
12631 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012632
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012633 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012634 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12635 I = UnmatchedFields.begin(),
12636 E = UnmatchedFields.end();
12637
12638 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012639 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012640 bool Result = UnmatchedFields.erase(*I);
12641 (void) Result;
12642 assert(Result);
12643 break;
12644 }
12645 }
12646 if (I == E)
12647 return false;
12648 }
12649
12650 return UnmatchedFields.empty();
12651}
12652
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012653static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
12654 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012655 if (RD1->isUnion() != RD2->isUnion())
12656 return false;
12657
12658 if (RD1->isUnion())
12659 return isLayoutCompatibleUnion(C, RD1, RD2);
12660 else
12661 return isLayoutCompatibleStruct(C, RD1, RD2);
12662}
12663
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012664/// Check if two types are layout-compatible in C++11 sense.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012665static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012666 if (T1.isNull() || T2.isNull())
12667 return false;
12668
12669 // C++11 [basic.types] p11:
12670 // If two types T1 and T2 are the same type, then T1 and T2 are
12671 // layout-compatible types.
12672 if (C.hasSameType(T1, T2))
12673 return true;
12674
12675 T1 = T1.getCanonicalType().getUnqualifiedType();
12676 T2 = T2.getCanonicalType().getUnqualifiedType();
12677
12678 const Type::TypeClass TC1 = T1->getTypeClass();
12679 const Type::TypeClass TC2 = T2->getTypeClass();
12680
12681 if (TC1 != TC2)
12682 return false;
12683
12684 if (TC1 == Type::Enum) {
12685 return isLayoutCompatible(C,
12686 cast<EnumType>(T1)->getDecl(),
12687 cast<EnumType>(T2)->getDecl());
12688 } else if (TC1 == Type::Record) {
12689 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12690 return false;
12691
12692 return isLayoutCompatible(C,
12693 cast<RecordType>(T1)->getDecl(),
12694 cast<RecordType>(T2)->getDecl());
12695 }
12696
12697 return false;
12698}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012699
12700//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12701
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012702/// Given a type tag expression find the type tag itself.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012703///
12704/// \param TypeExpr Type tag expression, as it appears in user's code.
12705///
12706/// \param VD Declaration of an identifier that appears in a type tag.
12707///
12708/// \param MagicValue Type tag magic value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012709static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12710 const ValueDecl **VD, uint64_t *MagicValue) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012711 while(true) {
12712 if (!TypeExpr)
12713 return false;
12714
12715 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12716
12717 switch (TypeExpr->getStmtClass()) {
12718 case Stmt::UnaryOperatorClass: {
12719 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12720 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12721 TypeExpr = UO->getSubExpr();
12722 continue;
12723 }
12724 return false;
12725 }
12726
12727 case Stmt::DeclRefExprClass: {
12728 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12729 *VD = DRE->getDecl();
12730 return true;
12731 }
12732
12733 case Stmt::IntegerLiteralClass: {
12734 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12735 llvm::APInt MagicValueAPInt = IL->getValue();
12736 if (MagicValueAPInt.getActiveBits() <= 64) {
12737 *MagicValue = MagicValueAPInt.getZExtValue();
12738 return true;
12739 } else
12740 return false;
12741 }
12742
12743 case Stmt::BinaryConditionalOperatorClass:
12744 case Stmt::ConditionalOperatorClass: {
12745 const AbstractConditionalOperator *ACO =
12746 cast<AbstractConditionalOperator>(TypeExpr);
12747 bool Result;
12748 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12749 if (Result)
12750 TypeExpr = ACO->getTrueExpr();
12751 else
12752 TypeExpr = ACO->getFalseExpr();
12753 continue;
12754 }
12755 return false;
12756 }
12757
12758 case Stmt::BinaryOperatorClass: {
12759 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12760 if (BO->getOpcode() == BO_Comma) {
12761 TypeExpr = BO->getRHS();
12762 continue;
12763 }
12764 return false;
12765 }
12766
12767 default:
12768 return false;
12769 }
12770 }
12771}
12772
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012773/// Retrieve the C type corresponding to type tag TypeExpr.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012774///
12775/// \param TypeExpr Expression that specifies a type tag.
12776///
12777/// \param MagicValues Registered magic values.
12778///
12779/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12780/// kind.
12781///
12782/// \param TypeInfo Information about the corresponding C type.
12783///
12784/// \returns true if the corresponding C type was found.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012785static bool GetMatchingCType(
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012786 const IdentifierInfo *ArgumentKind,
12787 const Expr *TypeExpr, const ASTContext &Ctx,
12788 const llvm::DenseMap<Sema::TypeTagMagicValue,
12789 Sema::TypeTagData> *MagicValues,
12790 bool &FoundWrongKind,
12791 Sema::TypeTagData &TypeInfo) {
12792 FoundWrongKind = false;
12793
12794 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000012795 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012796
12797 uint64_t MagicValue;
12798
12799 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12800 return false;
12801
12802 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000012803 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012804 if (I->getArgumentKind() != ArgumentKind) {
12805 FoundWrongKind = true;
12806 return false;
12807 }
12808 TypeInfo.Type = I->getMatchingCType();
12809 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12810 TypeInfo.MustBeNull = I->getMustBeNull();
12811 return true;
12812 }
12813 return false;
12814 }
12815
12816 if (!MagicValues)
12817 return false;
12818
12819 llvm::DenseMap<Sema::TypeTagMagicValue,
12820 Sema::TypeTagData>::const_iterator I =
12821 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12822 if (I == MagicValues->end())
12823 return false;
12824
12825 TypeInfo = I->second;
12826 return true;
12827}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012828
12829void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12830 uint64_t MagicValue, QualType Type,
12831 bool LayoutCompatible,
12832 bool MustBeNull) {
12833 if (!TypeTagForDatatypeMagicValues)
12834 TypeTagForDatatypeMagicValues.reset(
12835 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12836
12837 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12838 (*TypeTagForDatatypeMagicValues)[Magic] =
12839 TypeTagData(Type, LayoutCompatible, MustBeNull);
12840}
12841
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012842static bool IsSameCharType(QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012843 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12844 if (!BT1)
12845 return false;
12846
12847 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12848 if (!BT2)
12849 return false;
12850
12851 BuiltinType::Kind T1Kind = BT1->getKind();
12852 BuiltinType::Kind T2Kind = BT2->getKind();
12853
12854 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
12855 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
12856 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12857 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12858}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012859
12860void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012861 const ArrayRef<const Expr *> ExprArgs,
12862 SourceLocation CallSiteLoc) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012863 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12864 bool IsPointerAttr = Attr->getIsPointer();
12865
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012866 // Retrieve the argument representing the 'type_tag'.
Joel E. Denny81508102018-03-13 14:51:22 +000012867 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
12868 if (TypeTagIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012869 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000012870 << 0 << Attr->getTypeTagIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012871 return;
12872 }
Joel E. Denny81508102018-03-13 14:51:22 +000012873 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012874 bool FoundWrongKind;
12875 TypeTagData TypeInfo;
12876 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12877 TypeTagForDatatypeMagicValues.get(),
12878 FoundWrongKind, TypeInfo)) {
12879 if (FoundWrongKind)
12880 Diag(TypeTagExpr->getExprLoc(),
12881 diag::warn_type_tag_for_datatype_wrong_kind)
12882 << TypeTagExpr->getSourceRange();
12883 return;
12884 }
12885
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012886 // Retrieve the argument representing the 'arg_idx'.
Joel E. Denny81508102018-03-13 14:51:22 +000012887 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
12888 if (ArgumentIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012889 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000012890 << 1 << Attr->getArgumentIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012891 return;
12892 }
Joel E. Denny81508102018-03-13 14:51:22 +000012893 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012894 if (IsPointerAttr) {
12895 // Skip implicit cast of pointer to `void *' (as a function argument).
12896 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000012897 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000012898 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012899 ArgumentExpr = ICE->getSubExpr();
12900 }
12901 QualType ArgumentType = ArgumentExpr->getType();
12902
12903 // Passing a `void*' pointer shouldn't trigger a warning.
12904 if (IsPointerAttr && ArgumentType->isVoidPointerType())
12905 return;
12906
12907 if (TypeInfo.MustBeNull) {
12908 // Type tag with matching void type requires a null pointer.
12909 if (!ArgumentExpr->isNullPointerConstant(Context,
12910 Expr::NPC_ValueDependentIsNotNull)) {
12911 Diag(ArgumentExpr->getExprLoc(),
12912 diag::warn_type_safety_null_pointer_required)
12913 << ArgumentKind->getName()
12914 << ArgumentExpr->getSourceRange()
12915 << TypeTagExpr->getSourceRange();
12916 }
12917 return;
12918 }
12919
12920 QualType RequiredType = TypeInfo.Type;
12921 if (IsPointerAttr)
12922 RequiredType = Context.getPointerType(RequiredType);
12923
12924 bool mismatch = false;
12925 if (!TypeInfo.LayoutCompatible) {
12926 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12927
12928 // C++11 [basic.fundamental] p1:
12929 // Plain char, signed char, and unsigned char are three distinct types.
12930 //
12931 // But we treat plain `char' as equivalent to `signed char' or `unsigned
12932 // char' depending on the current char signedness mode.
12933 if (mismatch)
12934 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12935 RequiredType->getPointeeType())) ||
12936 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12937 mismatch = false;
12938 } else
12939 if (IsPointerAttr)
12940 mismatch = !isLayoutCompatible(Context,
12941 ArgumentType->getPointeeType(),
12942 RequiredType->getPointeeType());
12943 else
12944 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12945
12946 if (mismatch)
12947 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000012948 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012949 << TypeInfo.LayoutCompatible << RequiredType
12950 << ArgumentExpr->getSourceRange()
12951 << TypeTagExpr->getSourceRange();
12952}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012953
12954void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12955 CharUnits Alignment) {
12956 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12957}
12958
12959void Sema::DiagnoseMisalignedMembers() {
12960 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000012961 const NamedDecl *ND = m.RD;
12962 if (ND->getName().empty()) {
12963 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12964 ND = TD;
12965 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012966 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000012967 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012968 }
12969 MisalignedMembers.clear();
12970}
12971
12972void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012973 E = E->IgnoreParens();
12974 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012975 return;
12976 if (isa<UnaryOperator>(E) &&
12977 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12978 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12979 if (isa<MemberExpr>(Op)) {
12980 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12981 MisalignedMember(Op));
12982 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012983 (T->isIntegerType() ||
Roger Ferrer Ibanezd80d6c52017-12-07 09:23:50 +000012984 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
12985 Context.getTypeAlignInChars(
12986 T->getPointeeType()) <= MA->Alignment))))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012987 MisalignedMembers.erase(MA);
12988 }
12989 }
12990}
12991
12992void Sema::RefersToMemberWithReducedAlignment(
12993 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000012994 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12995 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012996 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012997 if (!ME)
12998 return;
12999
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000013000 // No need to check expressions with an __unaligned-qualified type.
13001 if (E->getType().getQualifiers().hasUnaligned())
13002 return;
13003
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013004 // For a chain of MemberExpr like "a.b.c.d" this list
13005 // will keep FieldDecl's like [d, c, b].
13006 SmallVector<FieldDecl *, 4> ReverseMemberChain;
13007 const MemberExpr *TopME = nullptr;
13008 bool AnyIsPacked = false;
13009 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013010 QualType BaseType = ME->getBase()->getType();
13011 if (ME->isArrow())
13012 BaseType = BaseType->getPointeeType();
13013 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000013014 if (RD->isInvalidDecl())
13015 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013016
13017 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013018 auto *FD = dyn_cast<FieldDecl>(MD);
13019 // We do not care about non-data members.
13020 if (!FD || FD->isInvalidDecl())
13021 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013022
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013023 AnyIsPacked =
13024 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
13025 ReverseMemberChain.push_back(FD);
13026
13027 TopME = ME;
13028 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
13029 } while (ME);
13030 assert(TopME && "We did not compute a topmost MemberExpr!");
13031
13032 // Not the scope of this diagnostic.
13033 if (!AnyIsPacked)
13034 return;
13035
13036 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
13037 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
13038 // TODO: The innermost base of the member expression may be too complicated.
13039 // For now, just disregard these cases. This is left for future
13040 // improvement.
13041 if (!DRE && !isa<CXXThisExpr>(TopBase))
13042 return;
13043
13044 // Alignment expected by the whole expression.
13045 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
13046
13047 // No need to do anything else with this case.
13048 if (ExpectedAlignment.isOne())
13049 return;
13050
13051 // Synthesize offset of the whole access.
13052 CharUnits Offset;
13053 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
13054 I++) {
13055 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
13056 }
13057
13058 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
13059 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
13060 ReverseMemberChain.back()->getParent()->getTypeForDecl());
13061
13062 // The base expression of the innermost MemberExpr may give
13063 // stronger guarantees than the class containing the member.
13064 if (DRE && !TopME->isArrow()) {
13065 const ValueDecl *VD = DRE->getDecl();
13066 if (!VD->getType()->isReferenceType())
13067 CompleteObjectAlignment =
13068 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
13069 }
13070
13071 // Check if the synthesized offset fulfills the alignment.
13072 if (Offset % ExpectedAlignment != 0 ||
13073 // It may fulfill the offset it but the effective alignment may still be
13074 // lower than the expected expression alignment.
13075 CompleteObjectAlignment < ExpectedAlignment) {
13076 // If this happens, we want to determine a sensible culprit of this.
13077 // Intuitively, watching the chain of member expressions from right to
13078 // left, we start with the required alignment (as required by the field
13079 // type) but some packed attribute in that chain has reduced the alignment.
13080 // It may happen that another packed structure increases it again. But if
13081 // we are here such increase has not been enough. So pointing the first
13082 // FieldDecl that either is packed or else its RecordDecl is,
13083 // seems reasonable.
13084 FieldDecl *FD = nullptr;
13085 CharUnits Alignment;
13086 for (FieldDecl *FDI : ReverseMemberChain) {
13087 if (FDI->hasAttr<PackedAttr>() ||
13088 FDI->getParent()->hasAttr<PackedAttr>()) {
13089 FD = FDI;
13090 Alignment = std::min(
13091 Context.getTypeAlignInChars(FD->getType()),
13092 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
13093 break;
13094 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013095 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013096 assert(FD && "We did not find a packed FieldDecl!");
13097 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013098 }
13099}
13100
13101void Sema::CheckAddressOfPackedMember(Expr *rhs) {
13102 using namespace std::placeholders;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013103
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013104 RefersToMemberWithReducedAlignment(
13105 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
13106 _2, _3, _4));
13107}